From 5122a932b60e81a61934d2b87d5bfa16bc6f3069 Mon Sep 17 00:00:00 2001 From: Nicholas Llewellyn Date: Wed, 9 Apr 2025 10:56:12 +0100 Subject: [PATCH 01/10] [camera_android_camerax] Fix target rotation not being set to default when capture orientation not locked. Fixes target rotation not being set to default when capture orientation is not locked. The major changes in this PR: 1. Corrects the logic for detecting when capture orientation is locked. --- .../camera_android_camerax/lib/src/android_camera_camerax.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/camera/camera_android_camerax/lib/src/android_camera_camerax.dart b/packages/camera/camera_android_camerax/lib/src/android_camera_camerax.dart index 8e61727cc616..a35ed56188fb 100644 --- a/packages/camera/camera_android_camerax/lib/src/android_camera_camerax.dart +++ b/packages/camera/camera_android_camerax/lib/src/android_camera_camerax.dart @@ -885,7 +885,7 @@ class AndroidCameraCameraX extends CameraPlatform { // Set target rotation to default CameraX rotation only if capture // orientation not locked. - if (!captureOrientationLocked && shouldSetDefaultRotation) { + if (!(captureOrientationLocked && shouldSetDefaultRotation)) { await imageCapture! .setTargetRotation(await proxy.getDefaultDisplayRotation()); } From 65a702c8b04eddf7466289c9314eab73b0b1683c Mon Sep 17 00:00:00 2001 From: ash2moon Date: Wed, 9 Apr 2025 10:54:19 -0700 Subject: [PATCH 02/10] [shared_preferences] Allow reading int as long in SharedPreferences #165781 (#9032) Resolves issue [#165781](https://github.com/flutter/flutter/issues/165781) by falling back to reading preference as an int then upcasted to a Long. ## Pre-Review Checklist [^1]: Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling. --- .../shared_preferences_android/CHANGELOG.md | 4 ++++ .../sharedpreferences/SharedPreferencesPlugin.kt | 8 +++++++- .../shared_preferences_example/MainActivity.java | 3 ++- .../integration_test/shared_preferences_test.dart | 12 ++++++++++++ .../shared_preferences_android/pubspec.yaml | 2 +- 5 files changed, 26 insertions(+), 3 deletions(-) diff --git a/packages/shared_preferences/shared_preferences_android/CHANGELOG.md b/packages/shared_preferences/shared_preferences_android/CHANGELOG.md index d07fda05552e..f801ee978960 100644 --- a/packages/shared_preferences/shared_preferences_android/CHANGELOG.md +++ b/packages/shared_preferences/shared_preferences_android/CHANGELOG.md @@ -1,3 +1,7 @@ +## 2.4.9 + +* Enables callers to use `getInt` to read preference of type `int` that was written to shared preferences by native code without passing though plugin code. + ## 2.4.8 * Updates compileSdk 34 to flutter.compileSdkVersion. diff --git a/packages/shared_preferences/shared_preferences_android/android/src/main/kotlin/io/flutter/plugins/sharedpreferences/SharedPreferencesPlugin.kt b/packages/shared_preferences/shared_preferences_android/android/src/main/kotlin/io/flutter/plugins/sharedpreferences/SharedPreferencesPlugin.kt index 32b628a91c0b..d6456df3ef5c 100644 --- a/packages/shared_preferences/shared_preferences_android/android/src/main/kotlin/io/flutter/plugins/sharedpreferences/SharedPreferencesPlugin.kt +++ b/packages/shared_preferences/shared_preferences_android/android/src/main/kotlin/io/flutter/plugins/sharedpreferences/SharedPreferencesPlugin.kt @@ -23,6 +23,7 @@ import io.flutter.plugin.common.BinaryMessenger import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.ObjectOutputStream +import java.lang.ClassCastException import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.map @@ -379,7 +380,12 @@ class SharedPreferencesBackend( override fun getInt(key: String, options: SharedPreferencesPigeonOptions): Long? { val preferences = createSharedPreferences(options) return if (preferences.contains(key)) { - preferences.getLong(key, 0) + try { + preferences.getLong(key, 0) + } catch (e: ClassCastException) { + // Retry with getInt in case the preference was written by native code directly. + preferences.getInt(key, 0).toLong() + } } else { null } diff --git a/packages/shared_preferences/shared_preferences_android/example/android/app/src/main/java/dev/flutter/plugins/shared_preferences_example/MainActivity.java b/packages/shared_preferences/shared_preferences_android/example/android/app/src/main/java/dev/flutter/plugins/shared_preferences_example/MainActivity.java index 1ef654a61dc0..2fb6e1471b9d 100644 --- a/packages/shared_preferences/shared_preferences_android/example/android/app/src/main/java/dev/flutter/plugins/shared_preferences_example/MainActivity.java +++ b/packages/shared_preferences/shared_preferences_android/example/android/app/src/main/java/dev/flutter/plugins/shared_preferences_example/MainActivity.java @@ -17,9 +17,10 @@ public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); - // This call adds a preference for later testing in the Dart integration tests. + // These calls add preferences for later testing in the Dart integration tests. preferences .edit() + .putInt("thisIntIsWrittenInTheExampleAppJavaCode", 5) .putString("thisStringIsWrittenInTheExampleAppJavaCode", "testString") .commit(); } diff --git a/packages/shared_preferences/shared_preferences_android/example/integration_test/shared_preferences_test.dart b/packages/shared_preferences/shared_preferences_android/example/integration_test/shared_preferences_test.dart index 6a221bfdfab3..80663a4dc6d6 100644 --- a/packages/shared_preferences/shared_preferences_android/example/integration_test/shared_preferences_test.dart +++ b/packages/shared_preferences/shared_preferences_android/example/integration_test/shared_preferences_test.dart @@ -914,4 +914,16 @@ void main() { 'thisStringIsWrittenInTheExampleAppJavaCode', options), 'testString'); }); + + testWidgets('Shared Preferences can read ints by conversion to long', + (WidgetTester _) async { + final SharedPreferencesAsyncAndroidOptions options = + getOptions(useDataStore: false); + final SharedPreferencesAsyncPlatform preferences = getPreferences(); + + expect( + await preferences.getInt( + 'thisIntIsWrittenInTheExampleAppJavaCode', options), + 5); + }); } diff --git a/packages/shared_preferences/shared_preferences_android/pubspec.yaml b/packages/shared_preferences/shared_preferences_android/pubspec.yaml index e0e858decdf6..2fcf2454e401 100644 --- a/packages/shared_preferences/shared_preferences_android/pubspec.yaml +++ b/packages/shared_preferences/shared_preferences_android/pubspec.yaml @@ -2,7 +2,7 @@ name: shared_preferences_android description: Android implementation of the shared_preferences plugin repository: https://github.com/flutter/packages/tree/main/packages/shared_preferences/shared_preferences_android issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+shared_preferences%22 -version: 2.4.8 +version: 2.4.9 environment: sdk: ^3.6.0 From 26190faeb0ba544e9e8814261702586f5880e0a3 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Wed, 9 Apr 2025 14:29:26 -0400 Subject: [PATCH 03/10] Manual roll Flutter from 02f13c37841f to 212064a3e558 (21 revisions) (#9036) Manual roll requested by stuartmorgan@google.com https://github.com/flutter/flutter/compare/02f13c37841f...212064a3e558 2025-04-06 engine-flutter-autoroll@skia.org Roll Skia from 8f1638231e34 to da7929d79c28 (1 revision) (flutter/flutter#166657) 2025-04-06 engine-flutter-autoroll@skia.org Roll Skia from 943df306bc3a to 8f1638231e34 (2 revisions) (flutter/flutter#166647) 2025-04-05 98614782+auto-submit[bot]@users.noreply.github.com Reverts "[web] fix text selection offset in multi-line fields (#166565)" (flutter/flutter#166644) 2025-04-04 engine-flutter-autoroll@skia.org Roll Skia from a7da13848085 to 943df306bc3a (8 revisions) (flutter/flutter#166609) 2025-04-04 47866232+chunhtai@users.noreply.github.com Adds semantics input type (flutter/flutter#165925) 2025-04-04 flar@google.com Relands "[Impeller] Render conics without conversion from Flutter apps (#166305)" (flutter/flutter#166598) 2025-04-04 yjbanov@google.com [web] fix text selection offset in multi-line fields (flutter/flutter#166565) 2025-04-04 jonahwilliams@google.com [Impeller] if drawTextFrame scale is massive, convert to Path. (flutter/flutter#166234) 2025-04-04 bkonyi@google.com [ Widget Previews ] Add `widget_preview_scaffold.shard` to test the `widget_preview_scaffold` template contents (flutter/flutter#166358) 2025-04-04 matej.knopp@gmail.com [Embedder] Only call removeview callback when raster thread is done with the view (flutter/flutter#164571) 2025-04-04 engine-flutter-autoroll@skia.org Roll Packages from 4a36dc63f719 to 267ac7b66308 (2 revisions) (flutter/flutter#166583) 2025-04-04 engine-flutter-autoroll@skia.org Roll Dart SDK from 4293d50dd30d to 87965ab4864e (3 revisions) (flutter/flutter#166571) 2025-04-04 jacksongardner@google.com Disable firefox image_to_byte_data_test as a group. (flutter/flutter#166559) 2025-04-04 jiahaog@users.noreply.github.com Add x64 ddm variants (flutter/flutter#166511) 2025-04-04 engine-flutter-autoroll@skia.org Roll Skia from af7ff0e98c4e to a7da13848085 (3 revisions) (flutter/flutter#166560) 2025-04-04 98614782+auto-submit[bot]@users.noreply.github.com Reverts "[Impeller] Render conics without conversion from Flutter apps (#166305)" (flutter/flutter#166591) 2025-04-03 engine-flutter-autoroll@skia.org Roll Dart SDK from d174ec16c3ea to 4293d50dd30d (1 revision) (flutter/flutter#166557) 2025-04-03 engine-flutter-autoroll@skia.org Roll Skia from 5f65df75febd to af7ff0e98c4e (7 revisions) (flutter/flutter#166551) 2025-04-03 flar@google.com [Impeller] Render conics without conversion from Flutter apps (flutter/flutter#166305) 2025-04-03 katelovett@google.com Update localizations from console (flutter/flutter#166496) 2025-04-03 engine-flutter-autoroll@skia.org Roll Fuchsia GN SDK from K_1kHDN1WfObPYHya... to jsZSHIOmQAs3URvWU... (flutter/flutter#166544) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-packages Please CC stuartmorgan@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Packages: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- .ci/flutter_master.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.ci/flutter_master.version b/.ci/flutter_master.version index 8328856de244..6bd4bc0ddd7e 100644 --- a/.ci/flutter_master.version +++ b/.ci/flutter_master.version @@ -1 +1 @@ -02f13c37841f7426d8c493af16bc037176eb641b +212064a3e558357ef64e0ecece2ae16ce89c4fb9 From a7e131c3e6e2f43263bfc4df218c6631d61b1abb Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Thu, 10 Apr 2025 15:16:41 -0400 Subject: [PATCH 04/10] Manual roll Flutter from 212064a3e558 to 9bf18f097137 (32 revisions) (#9041) Manual roll Flutter from 212064a3e558 to 9bf18f097137 (32 revisions) Manual roll requested by stuartmorgan@google.com https://github.com/flutter/flutter/compare/212064a3e558...9bf18f097137 2025-04-08 1063596+reidbaker@users.noreply.github.com bump warn agp version from 7.3 to 8.3 (flutter/flutter#166555) 2025-04-08 engine-flutter-autoroll@skia.org Roll Skia from 57a1644f0f8f to 7b929584566c (1 revision) (flutter/flutter#166760) 2025-04-08 matanlurey@users.noreply.github.com Enable a swath of `bringup: true` builds that were forgotten to the void. (flutter/flutter#166757) 2025-04-08 muhatashim@google.com add check for announcement support per platform (flutter/flutter#166099) 2025-04-08 engine-flutter-autoroll@skia.org Roll Skia from 515eb6238867 to 57a1644f0f8f (1 revision) (flutter/flutter#166748) 2025-04-08 engine-flutter-autoroll@skia.org Roll Skia from 3ea44c88d37b to 515eb6238867 (1 revision) (flutter/flutter#166742) 2025-04-08 engine-flutter-autoroll@skia.org Roll Skia from 7d56b9cc7ce9 to 3ea44c88d37b (1 revision) (flutter/flutter#166741) 2025-04-08 engine-flutter-autoroll@skia.org Roll Skia from 245d2b8fb042 to 7d56b9cc7ce9 (2 revisions) (flutter/flutter#166737) 2025-04-08 103958012+ahmedrasar@users.noreply.github.com Fix `DropdownMenu` keyboard navigation on filtered entries (flutter/flutter#165868) 2025-04-08 43089218+chika3742@users.noreply.github.com Fix: DraggableScrollableSheet may not close if snapping is enabled (flutter/flutter#165557) 2025-04-08 137456488+flutter-pub-roller-bot@users.noreply.github.com Roll pub packages (flutter/flutter#166503) 2025-04-08 dkwingsmt@users.noreply.github.com Add `RoundedSuperellipseBorder` and apply it to `CupertinoActionSheet` (flutter/flutter#166303) 2025-04-07 engine-flutter-autoroll@skia.org Roll Skia from f493d403c01b to 245d2b8fb042 (3 revisions) (flutter/flutter#166720) 2025-04-07 yjbanov@google.com [web] reland fix text selection offset in multi-line fields (flutter/flutter#166714) 2025-04-07 58529443+srujzs@users.noreply.github.com [flutter_tools] Update dwds version to 24.3.10 (flutter/flutter#166699) 2025-04-07 engine-flutter-autoroll@skia.org Roll Skia from 5f0f9b76b975 to f493d403c01b (3 revisions) (flutter/flutter#166710) 2025-04-07 jason-simmons@users.noreply.github.com Roll HarfBuzz to 11.0.0 (flutter/flutter#166596) 2025-04-07 34465683+rkishan516@users.noreply.github.com Fix: CupertinoSheetTransition moves SystemUIOverlayStyle to outside of delegatedTransition and only changes top bar (flutter/flutter#164680) 2025-04-07 98614782+auto-submit[bot]@users.noreply.github.com Reverts "Reverts "Remove `bringup:true` from Linux tool_tests_widget_preview_scaffold (#166687)" (#166700)" (flutter/flutter#166711) 2025-04-07 bkonyi@google.com [ Widget Preview ] Update generated test files (flutter/flutter#166701) 2025-04-07 engine-flutter-autoroll@skia.org Roll Skia from 339ef4f48c29 to 5f0f9b76b975 (1 revision) (flutter/flutter#166690) 2025-04-07 98614782+auto-submit[bot]@users.noreply.github.com Reverts "Remove `bringup:true` from Linux tool_tests_widget_preview_scaffold (#166687)" (flutter/flutter#166700) 2025-04-07 34871572+gmackall@users.noreply.github.com [reland] Convert the Flutter Gradle Plugin entirely to Kotlin source (flutter/flutter#166676) 2025-04-07 bkonyi@google.com Remove `bringup:true` from Linux tool_tests_widget_preview_scaffold (flutter/flutter#166687) 2025-04-07 jessy.yameogo@gmail.com [Widget Preview] implemented gridview and listview layouts (flutter/flutter#166150) 2025-04-07 engine-flutter-autoroll@skia.org Roll Skia from 966d9c665eed to 339ef4f48c29 (1 revision) (flutter/flutter#166680) 2025-04-07 engine-flutter-autoroll@skia.org Roll Skia from 8505be5b584e to 966d9c665eed (2 revisions) (flutter/flutter#166675) 2025-04-07 34465683+rkishan516@users.noreply.github.com Feat: Add yearShape property to DatePickerThemeData (flutter/flutter#163909) 2025-04-07 98614782+auto-submit[bot]@users.noreply.github.com Reverts "Convert the Flutter Gradle Plugin entirely to Kotlin source (#166114)" (flutter/flutter#166666) 2025-04-07 34871572+gmackall@users.noreply.github.com Convert the Flutter Gradle Plugin entirely to Kotlin source (flutter/flutter#166114) 2025-04-06 liama@google.com Make coverage collection aware of workspaces (flutter/flutter#166389) 2025-04-06 engine-flutter-autoroll@skia.org Roll Skia from da7929d79c28 to 8505be5b584e (1 revision) (flutter/flutter#166661) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-packages Please CC stuartmorgan@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Packages: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 ... --- .ci.yaml | 2 +- .ci/flutter_master.version | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.ci.yaml b/.ci.yaml index 894dcdeac649..38ba297be117 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -114,7 +114,7 @@ platform_properties: targets: - name: Linux repo_checks recipe: packages/packages - timeout: 30 + timeout: 60 properties: add_recipes_cq: "true" target_file: repo_checks.yaml diff --git a/.ci/flutter_master.version b/.ci/flutter_master.version index 6bd4bc0ddd7e..be41c314c7a7 100644 --- a/.ci/flutter_master.version +++ b/.ci/flutter_master.version @@ -1 +1 @@ -212064a3e558357ef64e0ecece2ae16ce89c4fb9 +9bf18f09713766d3c1f427e5054ee47d5343e92d From d5ea500c0a1799a86eb9a6b3656abf4aa3d9c144 Mon Sep 17 00:00:00 2001 From: engine-flutter-autoroll Date: Fri, 11 Apr 2025 08:07:21 -0400 Subject: [PATCH 05/10] Manual roll Flutter from 9bf18f097137 to 30e53b0d9caa (1 revision) (#9053) Manual roll requested by stuartmorgan@google.com https://github.com/flutter/flutter/compare/9bf18f097137...30e53b0d9caa 2025-04-08 bkonyi@google.com [ Widget Preview ] Add initial support for communications over the Dart Tooling Daemon (DTD) (flutter/flutter#166698) If this roll has caused a breakage, revert this CL and stop the roller using the controls here: https://autoroll.skia.org/r/flutter-packages Please CC stuartmorgan@google.com on the revert to ensure that a human is aware of the problem. To file a bug in Packages: https://github.com/flutter/flutter/issues/new/choose To report a problem with the AutoRoller itself, please file a bug: https://issues.skia.org/issues/new?component=1389291&template=1850622 Documentation for the AutoRoller is here: https://skia.googlesource.com/buildbot/+doc/main/autoroll/README.md --- .ci/flutter_master.version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.ci/flutter_master.version b/.ci/flutter_master.version index be41c314c7a7..d31606cf81f9 100644 --- a/.ci/flutter_master.version +++ b/.ci/flutter_master.version @@ -1 +1 @@ -9bf18f09713766d3c1f427e5054ee47d5343e92d +30e53b0d9caadce80eff6d09f6975046b9a93033 From bddd4c1ca1884968dc85ecf57557ef4b0ac6ecc7 Mon Sep 17 00:00:00 2001 From: stuartmorgan-g Date: Mon, 14 Apr 2025 07:57:39 -0700 Subject: [PATCH 06/10] [various] Update Android example toolchains (#9062) Almost all packages in the repository are using AGP 8.5+ and KGP 1.9+, but a few are still using older versions, and Flutter `master` prints warnings that they will be unsupported in future Flutter versions. This updates them to match the rest of the repo, to avoid later breakage. --- packages/flutter_markdown/example/android/settings.gradle | 2 +- .../example/android/settings.gradle | 4 ++-- packages/go_router/example/android/settings.gradle | 2 +- .../path_provider/example/android/settings.gradle | 2 +- .../path_provider_android/example/android/settings.gradle | 2 +- packages/rfw/example/hello/android/settings.gradle | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/flutter_markdown/example/android/settings.gradle b/packages/flutter_markdown/example/android/settings.gradle index 68585549fcf0..d056e4db3665 100644 --- a/packages/flutter_markdown/example/android/settings.gradle +++ b/packages/flutter_markdown/example/android/settings.gradle @@ -19,7 +19,7 @@ pluginManagement { // See https://github.com/flutter/flutter/blob/master/docs/ecosystem/Plugins-and-Packages-repository-structure.md#gradle-structure for more info. plugins { id "dev.flutter.flutter-plugin-loader" version "1.0.0" - id "com.android.application" version "8.1.0" apply false + id "com.android.application" version "8.5.1" apply false id "org.jetbrains.kotlin.android" version "1.9.0" apply false id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1" } diff --git a/packages/flutter_plugin_android_lifecycle/example/android/settings.gradle b/packages/flutter_plugin_android_lifecycle/example/android/settings.gradle index ff2e510ec4c0..732af92e26f0 100644 --- a/packages/flutter_plugin_android_lifecycle/example/android/settings.gradle +++ b/packages/flutter_plugin_android_lifecycle/example/android/settings.gradle @@ -30,8 +30,8 @@ buildscript { plugins { id "dev.flutter.flutter-plugin-loader" version "1.0.0" - id "com.android.application" version "8.1.0" apply false - id "org.jetbrains.kotlin.android" version "1.7.10" apply false + id "com.android.application" version "8.5.1" apply false + id "org.jetbrains.kotlin.android" version "1.9.0" apply false id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1" } diff --git a/packages/go_router/example/android/settings.gradle b/packages/go_router/example/android/settings.gradle index 68585549fcf0..d056e4db3665 100644 --- a/packages/go_router/example/android/settings.gradle +++ b/packages/go_router/example/android/settings.gradle @@ -19,7 +19,7 @@ pluginManagement { // See https://github.com/flutter/flutter/blob/master/docs/ecosystem/Plugins-and-Packages-repository-structure.md#gradle-structure for more info. plugins { id "dev.flutter.flutter-plugin-loader" version "1.0.0" - id "com.android.application" version "8.1.0" apply false + id "com.android.application" version "8.5.1" apply false id "org.jetbrains.kotlin.android" version "1.9.0" apply false id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1" } diff --git a/packages/path_provider/path_provider/example/android/settings.gradle b/packages/path_provider/path_provider/example/android/settings.gradle index 81c38fbe1d50..c921f079da12 100644 --- a/packages/path_provider/path_provider/example/android/settings.gradle +++ b/packages/path_provider/path_provider/example/android/settings.gradle @@ -20,7 +20,7 @@ pluginManagement { plugins { id "dev.flutter.flutter-plugin-loader" version "1.0.0" id "com.android.application" version "8.6.0" apply false - id "org.jetbrains.kotlin.android" version "1.7.10" apply false + id "org.jetbrains.kotlin.android" version "1.9.0" apply false id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1" } diff --git a/packages/path_provider/path_provider_android/example/android/settings.gradle b/packages/path_provider/path_provider_android/example/android/settings.gradle index bb344fb79fff..078698fe752d 100644 --- a/packages/path_provider/path_provider_android/example/android/settings.gradle +++ b/packages/path_provider/path_provider_android/example/android/settings.gradle @@ -20,7 +20,7 @@ pluginManagement { plugins { id "dev.flutter.flutter-plugin-loader" version "1.0.0" id "com.android.application" version "8.5.1" apply false - id "org.jetbrains.kotlin.android" version "1.7.10" apply false + id "org.jetbrains.kotlin.android" version "1.9.0" apply false id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1" } diff --git a/packages/rfw/example/hello/android/settings.gradle b/packages/rfw/example/hello/android/settings.gradle index fbeeadb8722f..29a37a993223 100644 --- a/packages/rfw/example/hello/android/settings.gradle +++ b/packages/rfw/example/hello/android/settings.gradle @@ -19,7 +19,7 @@ pluginManagement { // See https://github.com/flutter/flutter/blob/master/docs/ecosystem/Plugins-and-Packages-repository-structure.md#gradle-structure for more info. plugins { id "dev.flutter.flutter-plugin-loader" version "1.0.0" - id "com.android.application" version "8.1.0" apply false + id "com.android.application" version "8.5.1" apply false id "org.jetbrains.kotlin.android" version "1.9.0" apply false id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1" From 13881bbcab617f6f714814b334d5c403ad34799e Mon Sep 17 00:00:00 2001 From: Maurice Parrish <10687576+bparrishMines@users.noreply.github.com> Date: Mon, 14 Apr 2025 11:59:08 -0600 Subject: [PATCH 07/10] [webview_flutter_wkwebview] Fixes `loadFlutterAsset` exception and updates native wrapper for `SecTrust` and `SecCertificate` (#9016) Adds support to the native wrapper to handle `SecTrust` and `SecCertificate`. This is a part of landing https://github.com/flutter/packages/pull/7893 by splitting of the native wrapper implementation. Also fixes https://github.com/flutter/flutter/issues/162938 and adds an integration test for `loadFlutterAsset`. ## Pre-Review Checklist [^1]: Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling. --- .../webview_flutter_wkwebview/CHANGELOG.md | 5 + .../GetTrustResultResponseProxyAPITests.swift | 29 + .../Tests/SecCertificateProxyAPITests.swift | 43 ++ .../darwin/Tests/SecTrustProxyAPITests.swift | 133 +++++ .../darwin/Tests/TestProxyApiRegistrar.swift | 4 +- .../URLProtectionSpaceProxyAPITests.swift | 30 + .../FlutterAssetManager.swift | 30 +- .../GetTrustResultResponse.swift | 20 + ...tTrustResultResponseProxyAPIDelegate.swift | 42 ++ .../ProxyAPIRegistrar.swift | 28 +- .../SecCertificateProxyAPIDelegate.swift | 31 + .../SecTrustProxyAPIDelegate.swift | 135 +++++ .../SecWrappers.swift | 31 + .../URLProtectionSpaceProxyAPIDelegate.swift | 10 + .../WebKitLibrary.g.swift | 434 +++++++++++++- .../WebViewProxyAPIDelegate.swift | 10 +- .../example/assets/test_cert.der | Bin 0 -> 829 bytes .../webview_flutter_test.dart | 30 + .../ios/Runner.xcodeproj/project.pbxproj | 20 +- .../WebpagePreferencesProxyAPITests.swift | 23 - .../macos/Runner.xcodeproj/project.pbxproj | 22 +- .../WebpagePreferencesProxyAPITests.swift | 23 - .../example/pubspec.yaml | 2 + .../lib/src/common/web_kit.g.dart | 543 +++++++++++++++++- .../pigeons/web_kit.dart | 90 +++ .../webview_flutter_wkwebview/pubspec.yaml | 4 +- 26 files changed, 1698 insertions(+), 74 deletions(-) create mode 100644 packages/webview_flutter/webview_flutter_wkwebview/darwin/Tests/GetTrustResultResponseProxyAPITests.swift create mode 100644 packages/webview_flutter/webview_flutter_wkwebview/darwin/Tests/SecCertificateProxyAPITests.swift create mode 100644 packages/webview_flutter/webview_flutter_wkwebview/darwin/Tests/SecTrustProxyAPITests.swift create mode 100644 packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/GetTrustResultResponse.swift create mode 100644 packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/GetTrustResultResponseProxyAPIDelegate.swift create mode 100644 packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/SecCertificateProxyAPIDelegate.swift create mode 100644 packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/SecTrustProxyAPIDelegate.swift create mode 100644 packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/SecWrappers.swift create mode 100644 packages/webview_flutter/webview_flutter_wkwebview/example/assets/test_cert.der delete mode 100644 packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/WebpagePreferencesProxyAPITests.swift delete mode 100644 packages/webview_flutter/webview_flutter_wkwebview/example/macos/RunnerTests/WebpagePreferencesProxyAPITests.swift diff --git a/packages/webview_flutter/webview_flutter_wkwebview/CHANGELOG.md b/packages/webview_flutter/webview_flutter_wkwebview/CHANGELOG.md index a4ea405f9618..11dbc2c5a864 100644 --- a/packages/webview_flutter/webview_flutter_wkwebview/CHANGELOG.md +++ b/packages/webview_flutter/webview_flutter_wkwebview/CHANGELOG.md @@ -1,3 +1,8 @@ +## 3.18.6 + +* Fixes `PlatformException` when calling `loadFlutterAsset` on macOS. +* Updates native wrapper with methods handling `SecTust` and `SecCertificate`. + ## 3.18.5 * Fixes crash when sending undefined message via JavaScript channel. diff --git a/packages/webview_flutter/webview_flutter_wkwebview/darwin/Tests/GetTrustResultResponseProxyAPITests.swift b/packages/webview_flutter/webview_flutter_wkwebview/darwin/Tests/GetTrustResultResponseProxyAPITests.swift new file mode 100644 index 000000000000..0ab7203f063d --- /dev/null +++ b/packages/webview_flutter/webview_flutter_wkwebview/darwin/Tests/GetTrustResultResponseProxyAPITests.swift @@ -0,0 +1,29 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import XCTest + +@testable import webview_flutter_wkwebview + +class GetTrustResultResponseProxyAPITests: XCTestCase { + func testResult() { + let registrar = TestProxyApiRegistrar() + let api = registrar.apiDelegate.pigeonApiGetTrustResultResponse(registrar) + + let instance = GetTrustResultResponse(result: SecTrustResultType.invalid, resultCode: -1) + let value = try? api.pigeonDelegate.result(pigeonApi: api, pigeonInstance: instance) + + XCTAssertEqual(value, DartSecTrustResultType.invalid) + } + + func testResultCode() { + let registrar = TestProxyApiRegistrar() + let api = registrar.apiDelegate.pigeonApiGetTrustResultResponse(registrar) + + let instance = GetTrustResultResponse(result: SecTrustResultType.invalid, resultCode: -1) + let value = try? api.pigeonDelegate.resultCode(pigeonApi: api, pigeonInstance: instance) + + XCTAssertEqual(value, -1) + } +} diff --git a/packages/webview_flutter/webview_flutter_wkwebview/darwin/Tests/SecCertificateProxyAPITests.swift b/packages/webview_flutter/webview_flutter_wkwebview/darwin/Tests/SecCertificateProxyAPITests.swift new file mode 100644 index 000000000000..7057b53e7913 --- /dev/null +++ b/packages/webview_flutter/webview_flutter_wkwebview/darwin/Tests/SecCertificateProxyAPITests.swift @@ -0,0 +1,43 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import XCTest + +@testable import webview_flutter_wkwebview + +#if os(iOS) + import Flutter +#elseif os(macOS) + import FlutterMacOS +#else + #error("Unsupported platform.") +#endif + +class SecCertificateProxyAPITests: XCTestCase { + func createDummyCertificate() -> SecCertificate { + let url = FlutterAssetManager().urlForAsset("assets/test_cert.der")! + let certificateData = NSData(contentsOf: url) + + return SecCertificateCreateWithData(nil, certificateData!)! + } + + func testCopyData() { + let registrar = TestProxyApiRegistrar() + let delegate = TestSecCertificateProxyAPIDelegate() + let api = PigeonApiSecCertificate(pigeonRegistrar: registrar, delegate: delegate) + + let value = try? api.pigeonDelegate.copyData( + pigeonApi: api, certificate: SecCertificateWrapper(value: createDummyCertificate())) + + XCTAssertEqual(value?.data, delegate.data) + } +} + +class TestSecCertificateProxyAPIDelegate: SecCertificateProxyAPIDelegate { + let data = Data() + + override func secCertificateCopyData(_ certificate: SecCertificate) -> CFData { + return data as CFData + } +} diff --git a/packages/webview_flutter/webview_flutter_wkwebview/darwin/Tests/SecTrustProxyAPITests.swift b/packages/webview_flutter/webview_flutter_wkwebview/darwin/Tests/SecTrustProxyAPITests.swift new file mode 100644 index 000000000000..ef92c27eb5f2 --- /dev/null +++ b/packages/webview_flutter/webview_flutter_wkwebview/darwin/Tests/SecTrustProxyAPITests.swift @@ -0,0 +1,133 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import XCTest + +@testable import webview_flutter_wkwebview + +#if os(iOS) + import Flutter +#elseif os(macOS) + import FlutterMacOS +#else + #error("Unsupported platform.") +#endif + +class SecTrustProxyAPITests: XCTestCase { + func createTrust(delegate: TestSecTrustProxyAPIDelegate) -> SecTrustWrapper { + var trust: SecTrust? + SecTrustCreateWithCertificates( + [delegate.createDummyCertificate()] as AnyObject, SecPolicyCreateBasicX509(), &trust) + + return SecTrustWrapper(value: trust!) + } + + func testEvaluateWithError() { + let registrar = TestProxyApiRegistrar() + let delegate = TestSecTrustProxyAPIDelegate() + let api = PigeonApiSecTrust(pigeonRegistrar: registrar, delegate: delegate) + + let expect = expectation(description: "Wait for setCookie.") + let trust = createTrust(delegate: delegate) + var resultValue: Bool? + + api.pigeonDelegate.evaluateWithError(pigeonApi: api, trust: trust) { result in + switch result { + case .success(let value): + resultValue = value + case .failure(_): + break + } + expect.fulfill() + } + + wait(for: [expect], timeout: 5.0) + XCTAssertEqual(resultValue, true) + } + + func testCopyExceptions() { + let registrar = TestProxyApiRegistrar() + let delegate = TestSecTrustProxyAPIDelegate() + let api = PigeonApiSecTrust(pigeonRegistrar: registrar, delegate: delegate) + + let trust = createTrust(delegate: delegate) + let value = try? api.pigeonDelegate.copyExceptions(pigeonApi: api, trust: trust) + + XCTAssertEqual(value?.data, Data()) + } + + func testSetExceptions() { + let registrar = TestProxyApiRegistrar() + let delegate = TestSecTrustProxyAPIDelegate() + let api = PigeonApiSecTrust(pigeonRegistrar: registrar, delegate: delegate) + + let trust = createTrust(delegate: delegate) + let value = try? api.pigeonDelegate.setExceptions( + pigeonApi: api, trust: trust, exceptions: FlutterStandardTypedData(bytes: Data())) + + XCTAssertEqual(value, false) + } + + func testGetTrustResult() { + let registrar = TestProxyApiRegistrar() + let delegate = TestSecTrustProxyAPIDelegate() + let api = PigeonApiSecTrust(pigeonRegistrar: registrar, delegate: delegate) + + let trust = createTrust(delegate: delegate) + let value = try? api.pigeonDelegate.getTrustResult(pigeonApi: api, trust: trust) + + XCTAssertEqual(value?.result, SecTrustResultType.invalid) + XCTAssertEqual(value?.resultCode, -1) + } + + func testCopyCertificateChain() { + let registrar = TestProxyApiRegistrar() + let delegate = TestSecTrustProxyAPIDelegate() + let api = PigeonApiSecTrust(pigeonRegistrar: registrar, delegate: delegate) + + let trust = createTrust(delegate: delegate) + let value = try? api.pigeonDelegate.copyCertificateChain(pigeonApi: api, trust: trust) + + XCTAssertEqual(value?.count, 1) + XCTAssertNotNil(value?.first?.value) + } +} + +class TestSecTrustProxyAPIDelegate: SecTrustProxyAPIDelegate { + func createDummyCertificate() -> SecCertificate { + let url = FlutterAssetManager().urlForAsset("assets/test_cert.der")! + let certificateData = NSData(contentsOf: url) + + return SecCertificateCreateWithData(nil, certificateData!)! + } + + override func secTrustEvaluateWithError( + _ trust: SecTrust, _ error: UnsafeMutablePointer? + ) -> Bool { + return true + } + + override func secTrustCopyExceptions(_ trust: SecTrust) -> CFData? { + return Data() as CFData + } + + override func secTrustSetExceptions(_ trust: SecTrust, _ exceptions: CFData?) -> Bool { + return false + } + + override func secTrustGetTrustResult( + _ trust: SecTrust, _ result: UnsafeMutablePointer + ) -> OSStatus { + result.pointee = SecTrustResultType.invalid + return -1 + } + + override func secTrustCopyCertificateChain(_ trust: SecTrust) -> CFArray? { + if #available(iOS 15.0, *) { + return [createDummyCertificate()] as CFArray + } + + return nil + } +} diff --git a/packages/webview_flutter/webview_flutter_wkwebview/darwin/Tests/TestProxyApiRegistrar.swift b/packages/webview_flutter/webview_flutter_wkwebview/darwin/Tests/TestProxyApiRegistrar.swift index 98142d219fd0..be7c1bde17de 100644 --- a/packages/webview_flutter/webview_flutter_wkwebview/darwin/Tests/TestProxyApiRegistrar.swift +++ b/packages/webview_flutter/webview_flutter_wkwebview/darwin/Tests/TestProxyApiRegistrar.swift @@ -8,7 +8,9 @@ import XCTest class TestProxyApiRegistrar: ProxyAPIRegistrar { init() { - super.init(binaryMessenger: TestBinaryMessenger(), bundle: TestBundle()) + super.init( + binaryMessenger: TestBinaryMessenger(), + assetManager: FlutterAssetManager(bundle: TestBundle())) } override func dispatchOnMainThread( diff --git a/packages/webview_flutter/webview_flutter_wkwebview/darwin/Tests/URLProtectionSpaceProxyAPITests.swift b/packages/webview_flutter/webview_flutter_wkwebview/darwin/Tests/URLProtectionSpaceProxyAPITests.swift index fcb9e9e4fb94..0ca297dd2f57 100644 --- a/packages/webview_flutter/webview_flutter_wkwebview/darwin/Tests/URLProtectionSpaceProxyAPITests.swift +++ b/packages/webview_flutter/webview_flutter_wkwebview/darwin/Tests/URLProtectionSpaceProxyAPITests.swift @@ -56,4 +56,34 @@ class ProtectionSpaceProxyAPITests: XCTestCase { XCTAssertEqual(value, instance.authenticationMethod) } + func testGetServerTrust() { + let registrar = TestProxyApiRegistrar() + let api = registrar.apiDelegate.pigeonApiURLProtectionSpace(registrar) + + let instance = TestProtectionSpace( + host: "host", port: 23, protocol: "protocol", realm: "realm", authenticationMethod: "myMethod" + ) + let value = try? api.pigeonDelegate.getServerTrust(pigeonApi: api, pigeonInstance: instance) + + XCTAssertEqual(value!.value, instance.serverTrust) + } +} + +class TestProtectionSpace: URLProtectionSpace, @unchecked Sendable { + var serverTrustVal: SecTrust? + + override var serverTrust: SecTrust? { + if serverTrustVal == nil { + let url = FlutterAssetManager().urlForAsset("assets/test_cert.der")! + + let certificateData = NSData(contentsOf: url) + let dummyCertificate: SecCertificate! = SecCertificateCreateWithData(nil, certificateData!) + + var trust: SecTrust? + SecTrustCreateWithCertificates( + [dummyCertificate] as AnyObject, SecPolicyCreateBasicX509(), &trust) + serverTrustVal = trust! + } + return serverTrustVal + } } diff --git a/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/FlutterAssetManager.swift b/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/FlutterAssetManager.swift index 2c66d735a46a..6d5aa3b2b72d 100644 --- a/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/FlutterAssetManager.swift +++ b/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/FlutterAssetManager.swift @@ -11,7 +11,35 @@ #endif open class FlutterAssetManager { - func lookupKeyForAsset(_ asset: String) -> String { + let bundle: Bundle + + init(bundle: Bundle = Bundle.main) { + self.bundle = bundle + } + + func lookupKeyForAsset(_ asset: String) -> String? { return FlutterDartProject.lookupKey(forAsset: asset) } + + func urlForAsset(_ asset: String) -> URL? { + let assetFilePath: String? = lookupKeyForAsset(asset) + + guard let assetFilePath = assetFilePath else { + return nil + } + + var url: URL? = bundle.url( + forResource: (assetFilePath as NSString).deletingPathExtension, + withExtension: (assetFilePath as NSString).pathExtension) + + #if os(macOS) + // See https://github.com/flutter/flutter/issues/135302 + // TODO(stuartmorgan): Remove this if the asset APIs are adjusted to work better for macOS. + if url == nil { + url = URL(string: assetFilePath, relativeTo: bundle.bundleURL) + } + #endif + + return url + } } diff --git a/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/GetTrustResultResponse.swift b/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/GetTrustResultResponse.swift new file mode 100644 index 000000000000..85393ad5be1a --- /dev/null +++ b/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/GetTrustResultResponse.swift @@ -0,0 +1,20 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import Darwin +import Security + +/// Data class used to respond to `SecTrustGetTrustResult`. +/// +/// The native method needs to return two values, so this custom class is +/// created to support this. +class GetTrustResultResponse { + let result: SecTrustResultType + let resultCode: OSStatus + + init(result: SecTrustResultType, resultCode: OSStatus) { + self.result = result + self.resultCode = resultCode + } +} diff --git a/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/GetTrustResultResponseProxyAPIDelegate.swift b/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/GetTrustResultResponseProxyAPIDelegate.swift new file mode 100644 index 000000000000..f6d5bd5807a9 --- /dev/null +++ b/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/GetTrustResultResponseProxyAPIDelegate.swift @@ -0,0 +1,42 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import Foundation + +/// ProxyApi implementation for `GetTrustResultResponse`. +/// +/// This class may handle instantiating native object instances that are attached to a Dart instance +/// or handle method calls on the associated native class or an instance of that class. +class GetTrustResultResponseProxyAPIDelegate: PigeonApiDelegateGetTrustResultResponse { + func result(pigeonApi: PigeonApiGetTrustResultResponse, pigeonInstance: GetTrustResultResponse) + throws -> DartSecTrustResultType + { + switch pigeonInstance.result { + case .unspecified: + return .unspecified + case .proceed: + return .proceed + case .deny: + return .deny + case .recoverableTrustFailure: + return .recoverableTrustFailure + case .fatalTrustFailure: + return .fatalTrustFailure + case .otherError: + return .otherError + case .invalid: + return .invalid + case .confirm: + return .confirm + @unknown default: + return .unknown + } + } + + func resultCode( + pigeonApi: PigeonApiGetTrustResultResponse, pigeonInstance: GetTrustResultResponse + ) throws -> Int64 { + return Int64(pigeonInstance.resultCode) + } +} diff --git a/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/ProxyAPIRegistrar.swift b/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/ProxyAPIRegistrar.swift index 607001b2bc56..0c451567b62a 100644 --- a/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/ProxyAPIRegistrar.swift +++ b/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/ProxyAPIRegistrar.swift @@ -16,11 +16,13 @@ import Foundation /// Implementation of `WebKitLibraryPigeonProxyApiRegistrar` that provides any additional resources needed by API implementations. open class ProxyAPIRegistrar: WebKitLibraryPigeonProxyApiRegistrar { - let assetManager = FlutterAssetManager() - let bundle: Bundle + let assetManager: FlutterAssetManager - init(binaryMessenger: FlutterBinaryMessenger, bundle: Bundle = Bundle.main) { - self.bundle = bundle + init( + binaryMessenger: FlutterBinaryMessenger, + assetManager: FlutterAssetManager = FlutterAssetManager() + ) { + self.assetManager = assetManager super.init(binaryMessenger: binaryMessenger, apiDelegate: ProxyAPIDelegate()) } @@ -280,4 +282,22 @@ class ProxyAPIDelegate: WebKitLibraryPigeonProxyApiDelegate { return PigeonApiWKWebpagePreferences( pigeonRegistrar: registrar, delegate: WebpagePreferencesProxyAPIDelegate()) } + + func pigeonApiGetTrustResultResponse(_ registrar: WebKitLibraryPigeonProxyApiRegistrar) + -> PigeonApiGetTrustResultResponse + { + return PigeonApiGetTrustResultResponse( + pigeonRegistrar: registrar, delegate: GetTrustResultResponseProxyAPIDelegate()) + } + + func pigeonApiSecTrust(_ registrar: WebKitLibraryPigeonProxyApiRegistrar) -> PigeonApiSecTrust { + return PigeonApiSecTrust(pigeonRegistrar: registrar, delegate: SecTrustProxyAPIDelegate()) + } + + func pigeonApiSecCertificate(_ registrar: WebKitLibraryPigeonProxyApiRegistrar) + -> PigeonApiSecCertificate + { + return PigeonApiSecCertificate( + pigeonRegistrar: registrar, delegate: SecCertificateProxyAPIDelegate()) + } } diff --git a/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/SecCertificateProxyAPIDelegate.swift b/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/SecCertificateProxyAPIDelegate.swift new file mode 100644 index 000000000000..3853154c90a1 --- /dev/null +++ b/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/SecCertificateProxyAPIDelegate.swift @@ -0,0 +1,31 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import Foundation + +#if os(iOS) + import Flutter +#elseif os(macOS) + import FlutterMacOS +#else + #error("Unsupported platform.") +#endif + +/// ProxyApi implementation for `SecCertificate`. +/// +/// This class may handle instantiating native object instances that are attached to a Dart instance +/// or handle method calls on the associated native class or an instance of that class. +class SecCertificateProxyAPIDelegate: PigeonApiDelegateSecCertificate { + func copyData(pigeonApi: PigeonApiSecCertificate, certificate: SecCertificateWrapper) throws + -> FlutterStandardTypedData + { + let data = secCertificateCopyData(certificate.value) + return FlutterStandardTypedData(bytes: data as Data) + } + + // Overridable for testing. + internal func secCertificateCopyData(_ certificate: SecCertificate) -> CFData { + return SecCertificateCopyData(certificate) + } +} diff --git a/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/SecTrustProxyAPIDelegate.swift b/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/SecTrustProxyAPIDelegate.swift new file mode 100644 index 000000000000..69b91c6c969e --- /dev/null +++ b/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/SecTrustProxyAPIDelegate.swift @@ -0,0 +1,135 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import Foundation + +#if os(iOS) + import Flutter +#elseif os(macOS) + import FlutterMacOS +#else + #error("Unsupported platform.") +#endif + +/// ProxyApi implementation for `SecTrust`. +/// +/// This class may handle instantiating native object instances that are attached to a Dart instance +/// or handle method calls on the associated native class or an instance of that class. +class SecTrustProxyAPIDelegate: PigeonApiDelegateSecTrust { + func evaluateWithError( + pigeonApi: PigeonApiSecTrust, trust: SecTrustWrapper, + completion: @escaping (Result) -> Void + ) { + /// `SecTrustEvaluateWithError` should not be called on main thread, so this calls the method on a background thread. + DispatchQueue.global().async { + var error: CFError? + let result = self.secTrustEvaluateWithError(trust.value, &error) + + DispatchQueue.main.async { + if let error = error { + completion( + Result.failure( + PigeonError( + code: CFErrorGetDomain(error) as String, + message: CFErrorCopyDescription(error) as String, details: nil))) + } else { + completion(Result.success(result)) + } + } + } + } + + func copyExceptions(pigeonApi: PigeonApiSecTrust, trust: SecTrustWrapper) throws + -> FlutterStandardTypedData? + { + let data = secTrustCopyExceptions(trust.value) + if let data = data { + return FlutterStandardTypedData(bytes: data as Data) + } + + return nil + } + + func setExceptions( + pigeonApi: PigeonApiSecTrust, trust: SecTrustWrapper, exceptions: FlutterStandardTypedData? + ) throws -> Bool { + let data: CFData? = exceptions != nil ? exceptions!.data as CFData : nil + return secTrustSetExceptions(trust.value, data) + } + + func getTrustResult(pigeonApi: PigeonApiSecTrust, trust: SecTrustWrapper) throws + -> GetTrustResultResponse + { + var result = SecTrustResultType.invalid + let status = secTrustGetTrustResult(trust.value, &result) + return GetTrustResultResponse(result: result, resultCode: status) + } + + func copyCertificateChain(pigeonApi: PigeonApiSecTrust, trust: SecTrustWrapper) throws + -> [SecCertificateWrapper]? + { + if #available(iOS 15.0, macOS 12.0, *) { + let array = secTrustCopyCertificateChain(trust.value) as Array? + if let array = array { + var certificateList: [SecCertificateWrapper] = [] + for certificate in array { + certificateList.append(SecCertificateWrapper(value: certificate as! SecCertificate)) + } + return certificateList + } + } else { + let count = secTrustGetCertificateCount(trust.value) + if count > 0 { + var certificateList: [SecCertificateWrapper] = [] + for index in 0..? + ) -> Bool { + return SecTrustEvaluateWithError(trust, error) + } + + // Overridable for testing. + internal func secTrustCopyExceptions(_ trust: SecTrust) -> CFData? { + return SecTrustCopyExceptions(trust) + } + + // Overridable for testing. + internal func secTrustSetExceptions(_ trust: SecTrust, _ exceptions: CFData?) -> Bool { + return SecTrustSetExceptions(trust, exceptions) + } + + // Overridable for testing. + internal func secTrustGetTrustResult( + _ trust: SecTrust, _ result: UnsafeMutablePointer + ) -> OSStatus { + return SecTrustGetTrustResult(trust, result) + } + + // Overridable for testing. + @available(iOS 15.0, macOS 12.0, *) + internal func secTrustCopyCertificateChain(_ trust: SecTrust) -> CFArray? { + return SecTrustCopyCertificateChain(trust) + } + + // Overridable for testing. + internal func secTrustGetCertificateCount(_ trust: SecTrust) -> CFIndex { + return SecTrustGetCertificateCount(trust) + } + + // Overridable for testing. + internal func secTrustGetCertificateAtIndex(_ trust: SecTrust, _ ix: CFIndex) -> SecCertificate? { + return SecTrustGetCertificateAtIndex(trust, ix) + } +} diff --git a/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/SecWrappers.swift b/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/SecWrappers.swift new file mode 100644 index 000000000000..9dfd19b0dccd --- /dev/null +++ b/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/SecWrappers.swift @@ -0,0 +1,31 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import Security + +/// Wrapper for `SecTrust`. +/// +/// Corefoundation types don't support being casted in Swift and will always succeed +/// by default. This wrapper is used to make the class compatible with generated pigeon +/// code. All instances of `SecTrust`should be replaced with this. +class SecTrustWrapper { + let value: SecTrust + + init(value: SecTrust) { + self.value = value + } +} + +/// Wrapper for `SecCertificate`. +/// +/// Corefoundation types don't support being casted in Swift and will always succeed +/// by default. This wrapper is used to make the class compatible with generated pigeon +/// code. All instances of `SecCertificate`should be replaced with this. +class SecCertificateWrapper { + let value: SecCertificate + + init(value: SecCertificate) { + self.value = value + } +} diff --git a/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/URLProtectionSpaceProxyAPIDelegate.swift b/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/URLProtectionSpaceProxyAPIDelegate.swift index d7c59c67f287..03e5dadcced8 100644 --- a/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/URLProtectionSpaceProxyAPIDelegate.swift +++ b/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/URLProtectionSpaceProxyAPIDelegate.swift @@ -32,4 +32,14 @@ class URLProtectionSpaceProxyAPIDelegate: PigeonApiDelegateURLProtectionSpace { ) throws -> String? { return pigeonInstance.authenticationMethod } + + func getServerTrust(pigeonApi: PigeonApiURLProtectionSpace, pigeonInstance: URLProtectionSpace) + throws -> SecTrustWrapper? + { + if let serverTrust = pigeonInstance.serverTrust { + return SecTrustWrapper(value: serverTrust) + } + + return nil + } } diff --git a/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/WebKitLibrary.g.swift b/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/WebKitLibrary.g.swift index 177b66a2e6c6..9d35176ec173 100644 --- a/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/WebKitLibrary.g.swift +++ b/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/WebKitLibrary.g.swift @@ -1,7 +1,7 @@ // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// Autogenerated from Pigeon (v24.2.1), do not edit directly. +// Autogenerated from Pigeon (v25.2.0), do not edit directly. // See also: https://pub.dev/packages/pigeon import Foundation @@ -492,6 +492,17 @@ protocol WebKitLibraryPigeonProxyApiDelegate { /// `WKWebpagePreferences` to the Dart `InstanceManager` and make calls to Dart. func pigeonApiWKWebpagePreferences(_ registrar: WebKitLibraryPigeonProxyApiRegistrar) -> PigeonApiWKWebpagePreferences + /// An implementation of [PigeonApiGetTrustResultResponse] used to add a new Dart instance of + /// `GetTrustResultResponse` to the Dart `InstanceManager` and make calls to Dart. + func pigeonApiGetTrustResultResponse(_ registrar: WebKitLibraryPigeonProxyApiRegistrar) + -> PigeonApiGetTrustResultResponse + /// An implementation of [PigeonApiSecTrust] used to add a new Dart instance of + /// `SecTrust` to the Dart `InstanceManager` and make calls to Dart. + func pigeonApiSecTrust(_ registrar: WebKitLibraryPigeonProxyApiRegistrar) -> PigeonApiSecTrust + /// An implementation of [PigeonApiSecCertificate] used to add a new Dart instance of + /// `SecCertificate` to the Dart `InstanceManager` and make calls to Dart. + func pigeonApiSecCertificate(_ registrar: WebKitLibraryPigeonProxyApiRegistrar) + -> PigeonApiSecCertificate } extension WebKitLibraryPigeonProxyApiDelegate { @@ -591,6 +602,10 @@ open class WebKitLibraryPigeonProxyApiRegistrar { binaryMessenger: binaryMessenger, api: apiDelegate.pigeonApiURL(self)) PigeonApiWKWebpagePreferences.setUpMessageHandlers( binaryMessenger: binaryMessenger, api: apiDelegate.pigeonApiWKWebpagePreferences(self)) + PigeonApiSecTrust.setUpMessageHandlers( + binaryMessenger: binaryMessenger, api: apiDelegate.pigeonApiSecTrust(self)) + PigeonApiSecCertificate.setUpMessageHandlers( + binaryMessenger: binaryMessenger, api: apiDelegate.pigeonApiSecCertificate(self)) } func tearDown() { WebKitLibraryPigeonInstanceManagerApi.setUpMessageHandlers( @@ -620,6 +635,8 @@ open class WebKitLibraryPigeonProxyApiRegistrar { binaryMessenger: binaryMessenger, api: nil) PigeonApiURL.setUpMessageHandlers(binaryMessenger: binaryMessenger, api: nil) PigeonApiWKWebpagePreferences.setUpMessageHandlers(binaryMessenger: binaryMessenger, api: nil) + PigeonApiSecTrust.setUpMessageHandlers(binaryMessenger: binaryMessenger, api: nil) + PigeonApiSecCertificate.setUpMessageHandlers(binaryMessenger: binaryMessenger, api: nil) } } private class WebKitLibraryPigeonInternalProxyApiCodecReaderWriter: FlutterStandardReaderWriter { @@ -666,7 +683,7 @@ private class WebKitLibraryPigeonInternalProxyApiCodecReaderWriter: FlutterStand || value is NavigationActionPolicy || value is NavigationResponsePolicy || value is HttpCookiePropertyKey || value is NavigationType || value is PermissionDecision || value is MediaCaptureType || value is UrlSessionAuthChallengeDisposition - || value is UrlCredentialPersistence + || value is UrlCredentialPersistence || value is DartSecTrustResultType { super.writeValue(value) return @@ -1030,6 +1047,40 @@ private class WebKitLibraryPigeonInternalProxyApiCodecReaderWriter: FlutterStand return } + if let instance = value as? GetTrustResultResponse { + pigeonRegistrar.apiDelegate.pigeonApiGetTrustResultResponse(pigeonRegistrar) + .pigeonNewInstance( + pigeonInstance: instance + ) { _ in } + super.writeByte(128) + super.writeValue( + pigeonRegistrar.instanceManager.identifierWithStrongReference( + forInstance: instance as AnyObject)!) + return + } + + if let instance = value as? SecTrustWrapper { + pigeonRegistrar.apiDelegate.pigeonApiSecTrust(pigeonRegistrar).pigeonNewInstance( + pigeonInstance: instance + ) { _ in } + super.writeByte(128) + super.writeValue( + pigeonRegistrar.instanceManager.identifierWithStrongReference( + forInstance: instance as AnyObject)!) + return + } + + if let instance = value as? SecCertificateWrapper { + pigeonRegistrar.apiDelegate.pigeonApiSecCertificate(pigeonRegistrar).pigeonNewInstance( + pigeonInstance: instance + ) { _ in } + super.writeByte(128) + super.writeValue( + pigeonRegistrar.instanceManager.identifierWithStrongReference( + forInstance: instance as AnyObject)!) + return + } + if let instance = value as? NSObject { pigeonRegistrar.apiDelegate.pigeonApiNSObject(pigeonRegistrar).pigeonNewInstance( pigeonInstance: instance @@ -1335,6 +1386,31 @@ enum UrlCredentialPersistence: Int { case synchronizable = 3 } +/// Trust evaluation result codes. +/// +/// See https://developer.apple.com/documentation/security/sectrustresulttype?language=objc. +enum DartSecTrustResultType: Int { + /// The user did not specify a trust setting. + case unspecified = 0 + /// The user granted permission to trust the certificate for the purposes + /// designated in the specified policies. + case proceed = 1 + /// The user specified that the certificate should not be trusted. + case deny = 2 + /// Trust is denied, but recovery may be possible. + case recoverableTrustFailure = 3 + /// Trust is denied and no simple fix is available. + case fatalTrustFailure = 4 + /// A value that indicates a failure other than trust evaluation. + case otherError = 5 + /// An indication of an invalid setting or result. + case invalid = 6 + /// User confirmation is required before proceeding. + case confirm = 7 + /// The type is not recognized by this wrapper. + case unknown = 8 +} + private class WebKitLibraryPigeonCodecReader: FlutterStandardReader { override func readValue(ofType type: UInt8) -> Any? { switch type { @@ -1422,6 +1498,12 @@ private class WebKitLibraryPigeonCodecReader: FlutterStandardReader { return UrlCredentialPersistence(rawValue: enumResultAsInt) } return nil + case 143: + let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?) + if let enumResultAsInt = enumResultAsInt { + return DartSecTrustResultType(rawValue: enumResultAsInt) + } + return nil default: return super.readValue(ofType: type) } @@ -1472,6 +1554,9 @@ private class WebKitLibraryPigeonCodecWriter: FlutterStandardWriter { } else if let value = value as? UrlCredentialPersistence { super.writeByte(142) super.writeValue(value.rawValue) + } else if let value = value as? DartSecTrustResultType { + super.writeByte(143) + super.writeValue(value.rawValue) } else { super.writeValue(value) } @@ -6581,6 +6666,9 @@ protocol PigeonApiDelegateURLProtectionSpace { func authenticationMethod( pigeonApi: PigeonApiURLProtectionSpace, pigeonInstance: URLProtectionSpace ) throws -> String? + /// A representation of the server’s SSL transaction state. + func getServerTrust(pigeonApi: PigeonApiURLProtectionSpace, pigeonInstance: URLProtectionSpace) + throws -> SecTrustWrapper? } protocol PigeonApiProtocolURLProtectionSpace { @@ -6621,6 +6709,8 @@ final class PigeonApiURLProtectionSpace: PigeonApiProtocolURLProtectionSpace { let realmArg = try! pigeonDelegate.realm(pigeonApi: self, pigeonInstance: pigeonInstance) let authenticationMethodArg = try! pigeonDelegate.authenticationMethod( pigeonApi: self, pigeonInstance: pigeonInstance) + let getServerTrustArg = try! pigeonDelegate.getServerTrust( + pigeonApi: self, pigeonInstance: pigeonInstance) let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec let channelName: String = @@ -6628,7 +6718,10 @@ final class PigeonApiURLProtectionSpace: PigeonApiProtocolURLProtectionSpace { let channel = FlutterBasicMessageChannel( name: channelName, binaryMessenger: binaryMessenger, codec: codec) channel.sendMessage( - [pigeonIdentifierArg, hostArg, portArg, realmArg, authenticationMethodArg] as [Any?] + [ + pigeonIdentifierArg, hostArg, portArg, realmArg, authenticationMethodArg, + getServerTrustArg, + ] as [Any?] ) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) @@ -6943,3 +7036,338 @@ final class PigeonApiWKWebpagePreferences: PigeonApiProtocolWKWebpagePreferences } } } +protocol PigeonApiDelegateGetTrustResultResponse { + /// The result code from the most recent trust evaluation. + func result(pigeonApi: PigeonApiGetTrustResultResponse, pigeonInstance: GetTrustResultResponse) + throws -> DartSecTrustResultType + /// A result code. + /// + /// See https://developer.apple.com/documentation/security/security-framework-result-codes?language=objc. + func resultCode( + pigeonApi: PigeonApiGetTrustResultResponse, pigeonInstance: GetTrustResultResponse + ) throws -> Int64 +} + +protocol PigeonApiProtocolGetTrustResultResponse { +} + +final class PigeonApiGetTrustResultResponse: PigeonApiProtocolGetTrustResultResponse { + unowned let pigeonRegistrar: WebKitLibraryPigeonProxyApiRegistrar + let pigeonDelegate: PigeonApiDelegateGetTrustResultResponse + ///An implementation of [NSObject] used to access callback methods + var pigeonApiNSObject: PigeonApiNSObject { + return pigeonRegistrar.apiDelegate.pigeonApiNSObject(pigeonRegistrar) + } + + init( + pigeonRegistrar: WebKitLibraryPigeonProxyApiRegistrar, + delegate: PigeonApiDelegateGetTrustResultResponse + ) { + self.pigeonRegistrar = pigeonRegistrar + self.pigeonDelegate = delegate + } + ///Creates a Dart instance of GetTrustResultResponse and attaches it to [pigeonInstance]. + func pigeonNewInstance( + pigeonInstance: GetTrustResultResponse, + completion: @escaping (Result) -> Void + ) { + if pigeonRegistrar.ignoreCallsToDart { + completion( + .failure( + PigeonError( + code: "ignore-calls-error", + message: "Calls to Dart are being ignored.", details: ""))) + } else if pigeonRegistrar.instanceManager.containsInstance(pigeonInstance as AnyObject) { + completion(.success(())) + } else { + let pigeonIdentifierArg = pigeonRegistrar.instanceManager.addHostCreatedInstance( + pigeonInstance as AnyObject) + let resultArg = try! pigeonDelegate.result(pigeonApi: self, pigeonInstance: pigeonInstance) + let resultCodeArg = try! pigeonDelegate.resultCode( + pigeonApi: self, pigeonInstance: pigeonInstance) + let binaryMessenger = pigeonRegistrar.binaryMessenger + let codec = pigeonRegistrar.codec + let channelName: String = + "dev.flutter.pigeon.webview_flutter_wkwebview.GetTrustResultResponse.pigeon_newInstance" + let channel = FlutterBasicMessageChannel( + name: channelName, binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage([pigeonIdentifierArg, resultArg, resultCodeArg] as [Any?]) { response in + guard let listResponse = response as? [Any?] else { + completion(.failure(createConnectionError(withChannelName: channelName))) + return + } + if listResponse.count > 1 { + let code: String = listResponse[0] as! String + let message: String? = nilOrValue(listResponse[1]) + let details: String? = nilOrValue(listResponse[2]) + completion(.failure(PigeonError(code: code, message: message, details: details))) + } else { + completion(.success(())) + } + } + } + } +} +protocol PigeonApiDelegateSecTrust { + /// Evaluates trust for the specified certificate and policies. + func evaluateWithError( + pigeonApi: PigeonApiSecTrust, trust: SecTrustWrapper, + completion: @escaping (Result) -> Void) + /// Returns an opaque cookie containing exceptions to trust policies that will + /// allow future evaluations of the current certificate to succeed. + func copyExceptions(pigeonApi: PigeonApiSecTrust, trust: SecTrustWrapper) throws + -> FlutterStandardTypedData? + /// Sets a list of exceptions that should be ignored when the certificate is + /// evaluated. + func setExceptions( + pigeonApi: PigeonApiSecTrust, trust: SecTrustWrapper, exceptions: FlutterStandardTypedData? + ) throws -> Bool + /// Returns the result code from the most recent trust evaluation. + func getTrustResult(pigeonApi: PigeonApiSecTrust, trust: SecTrustWrapper) throws + -> GetTrustResultResponse + /// Certificates used to evaluate trust. + func copyCertificateChain(pigeonApi: PigeonApiSecTrust, trust: SecTrustWrapper) throws + -> [SecCertificateWrapper]? +} + +protocol PigeonApiProtocolSecTrust { +} + +final class PigeonApiSecTrust: PigeonApiProtocolSecTrust { + unowned let pigeonRegistrar: WebKitLibraryPigeonProxyApiRegistrar + let pigeonDelegate: PigeonApiDelegateSecTrust + ///An implementation of [NSObject] used to access callback methods + var pigeonApiNSObject: PigeonApiNSObject { + return pigeonRegistrar.apiDelegate.pigeonApiNSObject(pigeonRegistrar) + } + + init(pigeonRegistrar: WebKitLibraryPigeonProxyApiRegistrar, delegate: PigeonApiDelegateSecTrust) { + self.pigeonRegistrar = pigeonRegistrar + self.pigeonDelegate = delegate + } + static func setUpMessageHandlers(binaryMessenger: FlutterBinaryMessenger, api: PigeonApiSecTrust?) + { + let codec: FlutterStandardMessageCodec = + api != nil + ? FlutterStandardMessageCodec( + readerWriter: WebKitLibraryPigeonInternalProxyApiCodecReaderWriter( + pigeonRegistrar: api!.pigeonRegistrar)) + : FlutterStandardMessageCodec.sharedInstance() + let evaluateWithErrorChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.webview_flutter_wkwebview.SecTrust.evaluateWithError", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + evaluateWithErrorChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let trustArg = args[0] as! SecTrustWrapper + api.pigeonDelegate.evaluateWithError(pigeonApi: api, trust: trustArg) { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + evaluateWithErrorChannel.setMessageHandler(nil) + } + let copyExceptionsChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.webview_flutter_wkwebview.SecTrust.copyExceptions", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + copyExceptionsChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let trustArg = args[0] as! SecTrustWrapper + do { + let result = try api.pigeonDelegate.copyExceptions(pigeonApi: api, trust: trustArg) + reply(wrapResult(result)) + } catch { + reply(wrapError(error)) + } + } + } else { + copyExceptionsChannel.setMessageHandler(nil) + } + let setExceptionsChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.webview_flutter_wkwebview.SecTrust.setExceptions", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + setExceptionsChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let trustArg = args[0] as! SecTrustWrapper + let exceptionsArg: FlutterStandardTypedData? = nilOrValue(args[1]) + do { + let result = try api.pigeonDelegate.setExceptions( + pigeonApi: api, trust: trustArg, exceptions: exceptionsArg) + reply(wrapResult(result)) + } catch { + reply(wrapError(error)) + } + } + } else { + setExceptionsChannel.setMessageHandler(nil) + } + let getTrustResultChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.webview_flutter_wkwebview.SecTrust.getTrustResult", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + getTrustResultChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let trustArg = args[0] as! SecTrustWrapper + do { + let result = try api.pigeonDelegate.getTrustResult(pigeonApi: api, trust: trustArg) + reply(wrapResult(result)) + } catch { + reply(wrapError(error)) + } + } + } else { + getTrustResultChannel.setMessageHandler(nil) + } + let copyCertificateChainChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.webview_flutter_wkwebview.SecTrust.copyCertificateChain", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + copyCertificateChainChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let trustArg = args[0] as! SecTrustWrapper + do { + let result = try api.pigeonDelegate.copyCertificateChain(pigeonApi: api, trust: trustArg) + reply(wrapResult(result)) + } catch { + reply(wrapError(error)) + } + } + } else { + copyCertificateChainChannel.setMessageHandler(nil) + } + } + + ///Creates a Dart instance of SecTrust and attaches it to [pigeonInstance]. + func pigeonNewInstance( + pigeonInstance: SecTrustWrapper, completion: @escaping (Result) -> Void + ) { + if pigeonRegistrar.ignoreCallsToDart { + completion( + .failure( + PigeonError( + code: "ignore-calls-error", + message: "Calls to Dart are being ignored.", details: ""))) + } else if pigeonRegistrar.instanceManager.containsInstance(pigeonInstance as AnyObject) { + completion(.success(())) + } else { + let pigeonIdentifierArg = pigeonRegistrar.instanceManager.addHostCreatedInstance( + pigeonInstance as AnyObject) + let binaryMessenger = pigeonRegistrar.binaryMessenger + let codec = pigeonRegistrar.codec + let channelName: String = + "dev.flutter.pigeon.webview_flutter_wkwebview.SecTrust.pigeon_newInstance" + let channel = FlutterBasicMessageChannel( + name: channelName, binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage([pigeonIdentifierArg] as [Any?]) { response in + guard let listResponse = response as? [Any?] else { + completion(.failure(createConnectionError(withChannelName: channelName))) + return + } + if listResponse.count > 1 { + let code: String = listResponse[0] as! String + let message: String? = nilOrValue(listResponse[1]) + let details: String? = nilOrValue(listResponse[2]) + completion(.failure(PigeonError(code: code, message: message, details: details))) + } else { + completion(.success(())) + } + } + } + } +} +protocol PigeonApiDelegateSecCertificate { + /// Returns a DER representation of a certificate given a certificate object. + func copyData(pigeonApi: PigeonApiSecCertificate, certificate: SecCertificateWrapper) throws + -> FlutterStandardTypedData +} + +protocol PigeonApiProtocolSecCertificate { +} + +final class PigeonApiSecCertificate: PigeonApiProtocolSecCertificate { + unowned let pigeonRegistrar: WebKitLibraryPigeonProxyApiRegistrar + let pigeonDelegate: PigeonApiDelegateSecCertificate + ///An implementation of [NSObject] used to access callback methods + var pigeonApiNSObject: PigeonApiNSObject { + return pigeonRegistrar.apiDelegate.pigeonApiNSObject(pigeonRegistrar) + } + + init( + pigeonRegistrar: WebKitLibraryPigeonProxyApiRegistrar, delegate: PigeonApiDelegateSecCertificate + ) { + self.pigeonRegistrar = pigeonRegistrar + self.pigeonDelegate = delegate + } + static func setUpMessageHandlers( + binaryMessenger: FlutterBinaryMessenger, api: PigeonApiSecCertificate? + ) { + let codec: FlutterStandardMessageCodec = + api != nil + ? FlutterStandardMessageCodec( + readerWriter: WebKitLibraryPigeonInternalProxyApiCodecReaderWriter( + pigeonRegistrar: api!.pigeonRegistrar)) + : FlutterStandardMessageCodec.sharedInstance() + let copyDataChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.webview_flutter_wkwebview.SecCertificate.copyData", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + copyDataChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let certificateArg = args[0] as! SecCertificateWrapper + do { + let result = try api.pigeonDelegate.copyData(pigeonApi: api, certificate: certificateArg) + reply(wrapResult(result)) + } catch { + reply(wrapError(error)) + } + } + } else { + copyDataChannel.setMessageHandler(nil) + } + } + + ///Creates a Dart instance of SecCertificate and attaches it to [pigeonInstance]. + func pigeonNewInstance( + pigeonInstance: SecCertificateWrapper, completion: @escaping (Result) -> Void + ) { + if pigeonRegistrar.ignoreCallsToDart { + completion( + .failure( + PigeonError( + code: "ignore-calls-error", + message: "Calls to Dart are being ignored.", details: ""))) + } else if pigeonRegistrar.instanceManager.containsInstance(pigeonInstance as AnyObject) { + completion(.success(())) + } else { + let pigeonIdentifierArg = pigeonRegistrar.instanceManager.addHostCreatedInstance( + pigeonInstance as AnyObject) + let binaryMessenger = pigeonRegistrar.binaryMessenger + let codec = pigeonRegistrar.codec + let channelName: String = + "dev.flutter.pigeon.webview_flutter_wkwebview.SecCertificate.pigeon_newInstance" + let channel = FlutterBasicMessageChannel( + name: channelName, binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage([pigeonIdentifierArg] as [Any?]) { response in + guard let listResponse = response as? [Any?] else { + completion(.failure(createConnectionError(withChannelName: channelName))) + return + } + if listResponse.count > 1 { + let code: String = listResponse[0] as! String + let message: String? = nilOrValue(listResponse[1]) + let details: String? = nilOrValue(listResponse[2]) + completion(.failure(PigeonError(code: code, message: message, details: details))) + } else { + completion(.success(())) + } + } + } + } +} diff --git a/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/WebViewProxyAPIDelegate.swift b/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/WebViewProxyAPIDelegate.swift index 8159a8a69abe..ca46bbb223f4 100644 --- a/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/WebViewProxyAPIDelegate.swift +++ b/packages/webview_flutter/webview_flutter_wkwebview/darwin/webview_flutter_wkwebview/Sources/webview_flutter_wkwebview/WebViewProxyAPIDelegate.swift @@ -207,18 +207,16 @@ class WebViewProxyAPIDelegate: PigeonApiDelegateWKWebView, PigeonApiDelegateUIVi throws { let registrar = pigeonApi.pigeonRegistrar as! ProxyAPIRegistrar - let assetFilePath = registrar.assetManager.lookupKeyForAsset(key) - - let url = registrar.bundle.url( - forResource: (assetFilePath as NSString).deletingPathExtension, - withExtension: (assetFilePath as NSString).pathExtension) + let url = registrar.assetManager.urlForAsset(key) if let url = url { pigeonInstance.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent()) } else { + let assetFilePath = registrar.assetManager.lookupKeyForAsset(key) throw PigeonError( code: "FWFURLParsingError", - message: "Failed to find asset with filepath: `\(assetFilePath)`.", details: nil) + message: "Failed to find asset with filepath: `\(String(describing: assetFilePath))`.", + details: nil) } } diff --git a/packages/webview_flutter/webview_flutter_wkwebview/example/assets/test_cert.der b/packages/webview_flutter/webview_flutter_wkwebview/example/assets/test_cert.der new file mode 100644 index 0000000000000000000000000000000000000000..87401bc4ad343f5b076cb9dbb9e8bc85f8cdd32f GIT binary patch literal 829 zcmXqLVzxABVp3ed%*4pVBvSO?;8q^(PSrEr&thl2yxo{1^O3=TmyJ`a&70H%Q^B!(JS28X1;DWWPyB1&kQD*coa6;In z^?W)x4=rxJU63f^w^RS~#lM|F44?mre$T6Tw%k4V+}3@^jaP~-ewV{^=!8butAz=S!^0P+R-SycTQA#EWJ}S4wF31iT6Q1%H|c9Kas4=|5jZ{fZR_$| z3ugYD@XqID0b`1q;)L?Y2P=9Cr8uW7Z`$p0%Fui%_qO%_<3BysC>8n^&uq3&IeSmv zU(euGfA{;IF?@P0!h^la?u_Qq*7&t-3o@CQ85tNCD;mff$O7X>mXAe@MMNrLsu$lD zjyoIJ=Pk(IGHHgcQ3@Y&AOceXFc29TW=o~#@96q4r6@)|UuK0;W1}38YwLpdcW0T* zE|ZmMIlf4uaOUaf!h0JY2H3b-?&0zBZ1FGAsG4M;@nFr`PL>`!}W^v$^&l5jX-jo33e`>ZcB(%qe+l6RJ|uapuIR~9|q*Szm#vfk8M zjrw main() async { expect(content.contains('flutter_test_header'), isTrue); }); + testWidgets('loadFlutterAsset successfully loads an HTML asset', + (WidgetTester tester) async { + final Completer pageFinished = Completer(); + + final PlatformWebViewController controller = PlatformWebViewController( + const PlatformWebViewControllerCreationParams(), + ); + final PlatformNavigationDelegate delegate = PlatformNavigationDelegate( + const PlatformNavigationDelegateCreationParams(), + ); + unawaited(delegate.setOnPageFinished((_) => pageFinished.complete())); + unawaited(controller.setPlatformNavigationDelegate(delegate)); + + await expectLater( + controller.loadFlutterAsset('assets/www/index.html'), + completes, + ); + + await tester.pumpWidget(Builder( + builder: (BuildContext context) { + return PlatformWebViewWidget( + PlatformWebViewWidgetCreationParams(controller: controller), + ).build(context); + }, + )); + + // Verify page also loads. + await pageFinished.future; + }); + testWidgets('JavascriptChannel', (WidgetTester tester) async { final Completer pageFinished = Completer(); final PlatformWebViewController controller = PlatformWebViewController( diff --git a/packages/webview_flutter/webview_flutter_wkwebview/example/ios/Runner.xcodeproj/project.pbxproj b/packages/webview_flutter/webview_flutter_wkwebview/example/ios/Runner.xcodeproj/project.pbxproj index 8d55bed26057..7b9f2bef87ef 100644 --- a/packages/webview_flutter/webview_flutter_wkwebview/example/ios/Runner.xcodeproj/project.pbxproj +++ b/packages/webview_flutter/webview_flutter_wkwebview/example/ios/Runner.xcodeproj/project.pbxproj @@ -40,7 +40,10 @@ 8F1488FE2D2DE27000191744 /* HTTPCookieProxyAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F1488C82D2DE27000191744 /* HTTPCookieProxyAPITests.swift */; }; 8F1488FF2D2DE27000191744 /* NavigationActionProxyAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F1488CB2D2DE27000191744 /* NavigationActionProxyAPITests.swift */; }; 8F1489012D2DE91C00191744 /* AuthenticationChallengeResponseProxyAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F1489002D2DE91C00191744 /* AuthenticationChallengeResponseProxyAPITests.swift */; }; - 8FC45F712D5C0C1E004E03E8 /* WebpagePreferencesProxyAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8FC45F702D5C0C1E004E03E8 /* WebpagePreferencesProxyAPITests.swift */; }; + 8FEC64852DA2C6DC00C48569 /* GetTrustResultResponseProxyAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8FEC64812DA2C6DC00C48569 /* GetTrustResultResponseProxyAPITests.swift */; }; + 8FEC64862DA2C6DC00C48569 /* WebpagePreferencesProxyAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8FEC64842DA2C6DC00C48569 /* WebpagePreferencesProxyAPITests.swift */; }; + 8FEC64872DA2C6DC00C48569 /* SecCertificateProxyAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8FEC64822DA2C6DC00C48569 /* SecCertificateProxyAPITests.swift */; }; + 8FEC64882DA2C6DC00C48569 /* SecTrustProxyAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8FEC64832DA2C6DC00C48569 /* SecTrustProxyAPITests.swift */; }; 904EA421B6925EC8D52ABE1B /* libPods-RunnerTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 573E8F1472CA1578A7CBDB63 /* libPods-RunnerTests.a */; }; 978B8F6F1D3862AE00F588F7 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */; }; 97C146F31CF9000F007C117D /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 97C146F21CF9000F007C117D /* main.m */; }; @@ -126,7 +129,10 @@ 8F1488E12D2DE27000191744 /* WebViewProxyAPITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = WebViewProxyAPITests.swift; path = ../../darwin/Tests/WebViewProxyAPITests.swift; sourceTree = SOURCE_ROOT; }; 8F1489002D2DE91C00191744 /* AuthenticationChallengeResponseProxyAPITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = AuthenticationChallengeResponseProxyAPITests.swift; path = ../../darwin/Tests/AuthenticationChallengeResponseProxyAPITests.swift; sourceTree = SOURCE_ROOT; }; 8F66D9D72D1362BE000835F9 /* RunnerTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "RunnerTests-Bridging-Header.h"; sourceTree = ""; }; - 8FC45F702D5C0C1E004E03E8 /* WebpagePreferencesProxyAPITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WebpagePreferencesProxyAPITests.swift; sourceTree = ""; }; + 8FEC64812DA2C6DC00C48569 /* GetTrustResultResponseProxyAPITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = GetTrustResultResponseProxyAPITests.swift; path = ../../darwin/Tests/GetTrustResultResponseProxyAPITests.swift; sourceTree = SOURCE_ROOT; }; + 8FEC64822DA2C6DC00C48569 /* SecCertificateProxyAPITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = SecCertificateProxyAPITests.swift; path = ../../darwin/Tests/SecCertificateProxyAPITests.swift; sourceTree = SOURCE_ROOT; }; + 8FEC64832DA2C6DC00C48569 /* SecTrustProxyAPITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = SecTrustProxyAPITests.swift; path = ../../darwin/Tests/SecTrustProxyAPITests.swift; sourceTree = SOURCE_ROOT; }; + 8FEC64842DA2C6DC00C48569 /* WebpagePreferencesProxyAPITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = WebpagePreferencesProxyAPITests.swift; path = ../../darwin/Tests/WebpagePreferencesProxyAPITests.swift; sourceTree = SOURCE_ROOT; }; 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; }; @@ -172,7 +178,10 @@ 68BDCAEA23C3F7CB00D9C032 /* RunnerTests */ = { isa = PBXGroup; children = ( - 8FC45F702D5C0C1E004E03E8 /* WebpagePreferencesProxyAPITests.swift */, + 8FEC64812DA2C6DC00C48569 /* GetTrustResultResponseProxyAPITests.swift */, + 8FEC64822DA2C6DC00C48569 /* SecCertificateProxyAPITests.swift */, + 8FEC64832DA2C6DC00C48569 /* SecTrustProxyAPITests.swift */, + 8FEC64842DA2C6DC00C48569 /* WebpagePreferencesProxyAPITests.swift */, 8F1489002D2DE91C00191744 /* AuthenticationChallengeResponseProxyAPITests.swift */, 8F1488C52D2DE27000191744 /* ErrorProxyAPITests.swift */, 8F1488C62D2DE27000191744 /* FrameInfoProxyAPITests.swift */, @@ -542,7 +551,6 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 8FC45F712D5C0C1E004E03E8 /* WebpagePreferencesProxyAPITests.swift in Sources */, 8F1488E22D2DE27000191744 /* ScriptMessageHandlerProxyAPITests.swift in Sources */, 8F1488E32D2DE27000191744 /* TestProxyApiRegistrar.swift in Sources */, 8F1488E42D2DE27000191744 /* URLRequestProxyAPITests.swift in Sources */, @@ -558,6 +566,10 @@ 8F1488ED2D2DE27000191744 /* ErrorProxyAPITests.swift in Sources */, 8F1488EE2D2DE27000191744 /* NSObjectProxyAPITests.swift in Sources */, 8F1488EF2D2DE27000191744 /* NavigationResponseProxyAPITests.swift in Sources */, + 8FEC64852DA2C6DC00C48569 /* GetTrustResultResponseProxyAPITests.swift in Sources */, + 8FEC64862DA2C6DC00C48569 /* WebpagePreferencesProxyAPITests.swift in Sources */, + 8FEC64872DA2C6DC00C48569 /* SecCertificateProxyAPITests.swift in Sources */, + 8FEC64882DA2C6DC00C48569 /* SecTrustProxyAPITests.swift in Sources */, 8F1488F02D2DE27000191744 /* UserScriptProxyAPITests.swift in Sources */, 8F1488F12D2DE27000191744 /* URLProtectionSpaceProxyAPITests.swift in Sources */, 8F1488F22D2DE27000191744 /* WebViewConfigurationProxyAPITests.swift in Sources */, diff --git a/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/WebpagePreferencesProxyAPITests.swift b/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/WebpagePreferencesProxyAPITests.swift deleted file mode 100644 index aa11b48ad1ec..000000000000 --- a/packages/webview_flutter/webview_flutter_wkwebview/example/ios/RunnerTests/WebpagePreferencesProxyAPITests.swift +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import WebKit -import XCTest - -@testable import webview_flutter_wkwebview - -class WebpagePreferencesProxyAPITests: XCTestCase { - @available(iOS 14.0, macOS 11.0, *) - @MainActor func testSetAllowsContentJavaScript() { - let registrar = TestProxyApiRegistrar() - let api = registrar.apiDelegate.pigeonApiWKWebpagePreferences(registrar) - - let instance = WKWebpagePreferences() - let allow = true - try? api.pigeonDelegate.setAllowsContentJavaScript( - pigeonApi: api, pigeonInstance: instance, allow: allow) - - XCTAssertEqual(instance.allowsContentJavaScript, allow) - } -} diff --git a/packages/webview_flutter/webview_flutter_wkwebview/example/macos/Runner.xcodeproj/project.pbxproj b/packages/webview_flutter/webview_flutter_wkwebview/example/macos/Runner.xcodeproj/project.pbxproj index 4fb9e94bb55c..ddb499e5f26e 100644 --- a/packages/webview_flutter/webview_flutter_wkwebview/example/macos/Runner.xcodeproj/project.pbxproj +++ b/packages/webview_flutter/webview_flutter_wkwebview/example/macos/Runner.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 60; + objectVersion = 54; objects = { /* Begin PBXAggregateTarget section */ @@ -28,7 +28,10 @@ 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; 6FBECA2F94D9B352000B75D7 /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 418FB4EA49104BADE288A967 /* Pods_RunnerTests.framework */; }; 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; - 8FC45F732D5C0C37004E03E8 /* WebpagePreferencesProxyAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8FC45F722D5C0C37004E03E8 /* WebpagePreferencesProxyAPITests.swift */; }; + 8FEC64952DA303E200C48569 /* SecCertificateProxyAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8FEC64922DA303E200C48569 /* SecCertificateProxyAPITests.swift */; }; + 8FEC64962DA303E200C48569 /* WebpagePreferencesProxyAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8FEC64942DA303E200C48569 /* WebpagePreferencesProxyAPITests.swift */; }; + 8FEC64972DA303E200C48569 /* SecTrustProxyAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8FEC64932DA303E200C48569 /* SecTrustProxyAPITests.swift */; }; + 8FEC64982DA303E200C48569 /* GetTrustResultResponseProxyAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8FEC64912DA303E200C48569 /* GetTrustResultResponseProxyAPITests.swift */; }; 8FF1FEA22D37201300A5E400 /* NSObjectProxyAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8FF1FE8E2D37201300A5E400 /* NSObjectProxyAPITests.swift */; }; 8FF1FEA32D37201300A5E400 /* ScrollViewProxyAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8FF1FE932D37201300A5E400 /* ScrollViewProxyAPITests.swift */; }; 8FF1FEA42D37201300A5E400 /* URLAuthenticationChallengeProxyAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8FF1FE992D37201300A5E400 /* URLAuthenticationChallengeProxyAPITests.swift */; }; @@ -113,7 +116,10 @@ 69E635CFAEEB8242654D4BBC /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; 7D83F970E1160B09690C7723 /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; - 8FC45F722D5C0C37004E03E8 /* WebpagePreferencesProxyAPITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WebpagePreferencesProxyAPITests.swift; sourceTree = ""; }; + 8FEC64912DA303E200C48569 /* GetTrustResultResponseProxyAPITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = GetTrustResultResponseProxyAPITests.swift; path = ../../darwin/Tests/GetTrustResultResponseProxyAPITests.swift; sourceTree = SOURCE_ROOT; }; + 8FEC64922DA303E200C48569 /* SecCertificateProxyAPITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = SecCertificateProxyAPITests.swift; path = ../../darwin/Tests/SecCertificateProxyAPITests.swift; sourceTree = SOURCE_ROOT; }; + 8FEC64932DA303E200C48569 /* SecTrustProxyAPITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = SecTrustProxyAPITests.swift; path = ../../darwin/Tests/SecTrustProxyAPITests.swift; sourceTree = SOURCE_ROOT; }; + 8FEC64942DA303E200C48569 /* WebpagePreferencesProxyAPITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = WebpagePreferencesProxyAPITests.swift; path = ../../darwin/Tests/WebpagePreferencesProxyAPITests.swift; sourceTree = SOURCE_ROOT; }; 8FF1FE842D37201300A5E400 /* AuthenticationChallengeResponseProxyAPITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = AuthenticationChallengeResponseProxyAPITests.swift; path = ../../darwin/Tests/AuthenticationChallengeResponseProxyAPITests.swift; sourceTree = SOURCE_ROOT; }; 8FF1FE852D37201300A5E400 /* ErrorProxyAPITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = ErrorProxyAPITests.swift; path = ../../darwin/Tests/ErrorProxyAPITests.swift; sourceTree = SOURCE_ROOT; }; 8FF1FE862D37201300A5E400 /* FrameInfoProxyAPITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = FrameInfoProxyAPITests.swift; path = ../../darwin/Tests/FrameInfoProxyAPITests.swift; sourceTree = SOURCE_ROOT; }; @@ -176,7 +182,10 @@ 331C80D6294CF71000263BE5 /* RunnerTests */ = { isa = PBXGroup; children = ( - 8FC45F722D5C0C37004E03E8 /* WebpagePreferencesProxyAPITests.swift */, + 8FEC64912DA303E200C48569 /* GetTrustResultResponseProxyAPITests.swift */, + 8FEC64922DA303E200C48569 /* SecCertificateProxyAPITests.swift */, + 8FEC64932DA303E200C48569 /* SecTrustProxyAPITests.swift */, + 8FEC64942DA303E200C48569 /* WebpagePreferencesProxyAPITests.swift */, 8FF1FE842D37201300A5E400 /* AuthenticationChallengeResponseProxyAPITests.swift */, 8FF1FE852D37201300A5E400 /* ErrorProxyAPITests.swift */, 8FF1FE862D37201300A5E400 /* FrameInfoProxyAPITests.swift */, @@ -528,7 +537,6 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 8FC45F732D5C0C37004E03E8 /* WebpagePreferencesProxyAPITests.swift in Sources */, 8FF1FEA22D37201300A5E400 /* NSObjectProxyAPITests.swift in Sources */, 8FF1FEA32D37201300A5E400 /* ScrollViewProxyAPITests.swift in Sources */, 8FF1FEA42D37201300A5E400 /* URLAuthenticationChallengeProxyAPITests.swift in Sources */, @@ -539,6 +547,10 @@ 8FF1FEA92D37201300A5E400 /* TestProxyApiRegistrar.swift in Sources */, 8FF1FEAA2D37201300A5E400 /* HTTPURLResponseProxyAPITests.swift in Sources */, 8FF1FEAB2D37201300A5E400 /* AuthenticationChallengeResponseProxyAPITests.swift in Sources */, + 8FEC64952DA303E200C48569 /* SecCertificateProxyAPITests.swift in Sources */, + 8FEC64962DA303E200C48569 /* WebpagePreferencesProxyAPITests.swift in Sources */, + 8FEC64972DA303E200C48569 /* SecTrustProxyAPITests.swift in Sources */, + 8FEC64982DA303E200C48569 /* GetTrustResultResponseProxyAPITests.swift in Sources */, 8FF1FEAC2D37201300A5E400 /* UIViewProxyAPITests.swift in Sources */, 8FF1FEAD2D37201300A5E400 /* WebViewConfigurationProxyAPITests.swift in Sources */, 8FF1FEAE2D37201300A5E400 /* NavigationActionProxyAPITests.swift in Sources */, diff --git a/packages/webview_flutter/webview_flutter_wkwebview/example/macos/RunnerTests/WebpagePreferencesProxyAPITests.swift b/packages/webview_flutter/webview_flutter_wkwebview/example/macos/RunnerTests/WebpagePreferencesProxyAPITests.swift deleted file mode 100644 index aa11b48ad1ec..000000000000 --- a/packages/webview_flutter/webview_flutter_wkwebview/example/macos/RunnerTests/WebpagePreferencesProxyAPITests.swift +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import WebKit -import XCTest - -@testable import webview_flutter_wkwebview - -class WebpagePreferencesProxyAPITests: XCTestCase { - @available(iOS 14.0, macOS 11.0, *) - @MainActor func testSetAllowsContentJavaScript() { - let registrar = TestProxyApiRegistrar() - let api = registrar.apiDelegate.pigeonApiWKWebpagePreferences(registrar) - - let instance = WKWebpagePreferences() - let allow = true - try? api.pigeonDelegate.setAllowsContentJavaScript( - pigeonApi: api, pigeonInstance: instance, allow: allow) - - XCTAssertEqual(instance.allowsContentJavaScript, allow) - } -} diff --git a/packages/webview_flutter/webview_flutter_wkwebview/example/pubspec.yaml b/packages/webview_flutter/webview_flutter_wkwebview/example/pubspec.yaml index 051e60afa666..f8ed12551d5b 100644 --- a/packages/webview_flutter/webview_flutter_wkwebview/example/pubspec.yaml +++ b/packages/webview_flutter/webview_flutter_wkwebview/example/pubspec.yaml @@ -32,3 +32,5 @@ flutter: - assets/sample_video.mp4 - assets/www/index.html - assets/www/styles/style.css + # Test certificate used to create a test native `SecTrust`. + - assets/test_cert.der diff --git a/packages/webview_flutter/webview_flutter_wkwebview/lib/src/common/web_kit.g.dart b/packages/webview_flutter/webview_flutter_wkwebview/lib/src/common/web_kit.g.dart index ee91ba63f41f..c94b4adb44bc 100644 --- a/packages/webview_flutter/webview_flutter_wkwebview/lib/src/common/web_kit.g.dart +++ b/packages/webview_flutter/webview_flutter_wkwebview/lib/src/common/web_kit.g.dart @@ -1,7 +1,7 @@ // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// Autogenerated from Pigeon (v24.2.1), do not edit directly. +// Autogenerated from Pigeon (v25.2.0), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import, no_leading_underscores_for_local_identifiers @@ -199,6 +199,12 @@ class PigeonInstanceManager { URL.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); WKWebpagePreferences.pigeon_setUpMessageHandlers( pigeon_instanceManager: instanceManager); + GetTrustResultResponse.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + SecTrust.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + SecCertificate.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); return instanceManager; } @@ -788,6 +794,39 @@ enum UrlCredentialPersistence { synchronizable, } +/// Trust evaluation result codes. +/// +/// See https://developer.apple.com/documentation/security/sectrustresulttype?language=objc. +enum DartSecTrustResultType { + /// The user did not specify a trust setting. + unspecified, + + /// The user granted permission to trust the certificate for the purposes + /// designated in the specified policies. + proceed, + + /// The user specified that the certificate should not be trusted. + deny, + + /// Trust is denied, but recovery may be possible. + recoverableTrustFailure, + + /// Trust is denied and no simple fix is available. + fatalTrustFailure, + + /// A value that indicates a failure other than trust evaluation. + otherError, + + /// An indication of an invalid setting or result. + invalid, + + /// User confirmation is required before proceeding. + confirm, + + /// The type is not recognized by this wrapper. + unknown, +} + class _PigeonCodec extends StandardMessageCodec { const _PigeonCodec(); @override @@ -837,6 +876,9 @@ class _PigeonCodec extends StandardMessageCodec { } else if (value is UrlCredentialPersistence) { buffer.putUint8(142); writeValue(buffer, value.index); + } else if (value is DartSecTrustResultType) { + buffer.putUint8(143); + writeValue(buffer, value.index); } else { super.writeValue(buffer, value); } @@ -889,6 +931,9 @@ class _PigeonCodec extends StandardMessageCodec { case 142: final int? value = readValue(buffer) as int?; return value == null ? null : UrlCredentialPersistence.values[value]; + case 143: + final int? value = readValue(buffer) as int?; + return value == null ? null : DartSecTrustResultType.values[value]; default: return super.readValueOfType(type, buffer); } @@ -7533,6 +7578,7 @@ class URLProtectionSpace extends NSObject { required this.port, this.realm, this.authenticationMethod, + this.getServerTrust, super.observeValue, }) : super.pigeon_detached(); @@ -7548,6 +7594,9 @@ class URLProtectionSpace extends NSObject { /// The authentication method used by the receiver. final String? authenticationMethod; + /// A representation of the server’s SSL transaction state. + final SecTrust? getServerTrust; + static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, @@ -7557,6 +7606,7 @@ class URLProtectionSpace extends NSObject { int port, String? realm, String? authenticationMethod, + SecTrust? getServerTrust, )? pigeon_newInstance, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = @@ -7588,11 +7638,12 @@ class URLProtectionSpace extends NSObject { 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.URLProtectionSpace.pigeon_newInstance was null, expected non-null int.'); final String? arg_realm = (args[3] as String?); final String? arg_authenticationMethod = (args[4] as String?); + final SecTrust? arg_getServerTrust = (args[5] as SecTrust?); try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( pigeon_newInstance?.call(arg_host!, arg_port!, arg_realm, - arg_authenticationMethod) ?? + arg_authenticationMethod, arg_getServerTrust) ?? URLProtectionSpace.pigeon_detached( pigeon_binaryMessenger: pigeon_binaryMessenger, pigeon_instanceManager: pigeon_instanceManager, @@ -7600,6 +7651,7 @@ class URLProtectionSpace extends NSObject { port: arg_port!, realm: arg_realm, authenticationMethod: arg_authenticationMethod, + getServerTrust: arg_getServerTrust, ), arg_pigeon_instanceIdentifier!, ); @@ -7624,6 +7676,7 @@ class URLProtectionSpace extends NSObject { port: port, realm: realm, authenticationMethod: authenticationMethod, + getServerTrust: getServerTrust, observeValue: observeValue, ); } @@ -7964,3 +8017,489 @@ class WKWebpagePreferences extends NSObject { ); } } + +/// Data class used to respond to `SecTrust.getTrustResult`. +/// +/// The native method needs to return two values, so this custom class is +/// created to support this. +class GetTrustResultResponse extends NSObject { + /// Constructs [GetTrustResultResponse] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + GetTrustResultResponse.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.result, + required this.resultCode, + super.observeValue, + }) : super.pigeon_detached(); + + /// The result code from the most recent trust evaluation. + final DartSecTrustResultType result; + + /// A result code. + /// + /// See https://developer.apple.com/documentation/security/security-framework-result-codes?language=objc. + final int resultCode; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + GetTrustResultResponse Function( + DartSecTrustResultType result, + int resultCode, + )? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.webview_flutter_wkwebview.GetTrustResultResponse.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.GetTrustResultResponse.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.GetTrustResultResponse.pigeon_newInstance was null, expected non-null int.'); + final DartSecTrustResultType? arg_result = + (args[1] as DartSecTrustResultType?); + assert(arg_result != null, + 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.GetTrustResultResponse.pigeon_newInstance was null, expected non-null DartSecTrustResultType.'); + final int? arg_resultCode = (args[2] as int?); + assert(arg_resultCode != null, + 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.GetTrustResultResponse.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call(arg_result!, arg_resultCode!) ?? + GetTrustResultResponse.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + result: arg_result!, + resultCode: arg_resultCode!, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } + + @override + GetTrustResultResponse pigeon_copy() { + return GetTrustResultResponse.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + result: result, + resultCode: resultCode, + observeValue: observeValue, + ); + } +} + +/// An object used to evaluate trust. +/// +/// See https://developer.apple.com/documentation/security/sectrust. +class SecTrust extends NSObject { + /// Constructs [SecTrust] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + SecTrust.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + super.observeValue, + }) : super.pigeon_detached(); + + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecSecTrust = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + SecTrust Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.webview_flutter_wkwebview.SecTrust.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.SecTrust.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.SecTrust.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + SecTrust.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } + + /// Evaluates trust for the specified certificate and policies. + static Future evaluateWithError( + SecTrust trust, { + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_wkwebview.SecTrust.evaluateWithError'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([trust]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as bool?)!; + } + } + + /// Returns an opaque cookie containing exceptions to trust policies that will + /// allow future evaluations of the current certificate to succeed. + static Future copyExceptions( + SecTrust trust, { + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_wkwebview.SecTrust.copyExceptions'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([trust]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return (pigeonVar_replyList[0] as Uint8List?); + } + } + + /// Sets a list of exceptions that should be ignored when the certificate is + /// evaluated. + static Future setExceptions( + SecTrust trust, + Uint8List? exceptions, { + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_wkwebview.SecTrust.setExceptions'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([trust, exceptions]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as bool?)!; + } + } + + /// Returns the result code from the most recent trust evaluation. + static Future getTrustResult( + SecTrust trust, { + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_wkwebview.SecTrust.getTrustResult'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([trust]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as GetTrustResultResponse?)!; + } + } + + /// Certificates used to evaluate trust. + static Future?> copyCertificateChain( + SecTrust trust, { + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_wkwebview.SecTrust.copyCertificateChain'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([trust]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return (pigeonVar_replyList[0] as List?)?.cast(); + } + } + + @override + SecTrust pigeon_copy() { + return SecTrust.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + observeValue: observeValue, + ); + } +} + +/// An abstract Core Foundation-type object representing an X.509 certificate. +/// +/// See https://developer.apple.com/documentation/security/seccertificate. +class SecCertificate extends NSObject { + /// Constructs [SecCertificate] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + SecCertificate.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + super.observeValue, + }) : super.pigeon_detached(); + + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecSecCertificate = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + SecCertificate Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.webview_flutter_wkwebview.SecCertificate.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.SecCertificate.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_wkwebview.SecCertificate.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + SecCertificate.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } + + /// Returns a DER representation of a certificate given a certificate object. + static Future copyData( + SecCertificate certificate, { + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_wkwebview.SecCertificate.copyData'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([certificate]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as Uint8List?)!; + } + } + + @override + SecCertificate pigeon_copy() { + return SecCertificate.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + observeValue: observeValue, + ); + } +} diff --git a/packages/webview_flutter/webview_flutter_wkwebview/pigeons/web_kit.dart b/packages/webview_flutter/webview_flutter_wkwebview/pigeons/web_kit.dart index 20b74cc72ade..3349c34105a6 100644 --- a/packages/webview_flutter/webview_flutter_wkwebview/pigeons/web_kit.dart +++ b/packages/webview_flutter/webview_flutter_wkwebview/pigeons/web_kit.dart @@ -340,6 +340,39 @@ enum UrlCredentialPersistence { synchronizable, } +/// Trust evaluation result codes. +/// +/// See https://developer.apple.com/documentation/security/sectrustresulttype?language=objc. +enum DartSecTrustResultType { + /// The user did not specify a trust setting. + unspecified, + + /// The user granted permission to trust the certificate for the purposes + /// designated in the specified policies. + proceed, + + /// The user specified that the certificate should not be trusted. + deny, + + /// Trust is denied, but recovery may be possible. + recoverableTrustFailure, + + /// Trust is denied and no simple fix is available. + fatalTrustFailure, + + /// A value that indicates a failure other than trust evaluation. + otherError, + + /// An indication of an invalid setting or result. + invalid, + + /// User confirmation is required before proceeding. + confirm, + + /// The type is not recognized by this wrapper. + unknown, +} + /// A URL load request that is independent of protocol or URL scheme. /// /// See https://developer.apple.com/documentation/foundation/urlrequest. @@ -1095,6 +1128,9 @@ abstract class URLProtectionSpace extends NSObject { /// The authentication method used by the receiver. late String? authenticationMethod; + + /// A representation of the server’s SSL transaction state. + late SecTrust? getServerTrust; } /// A challenge from a server requiring authentication from the client. @@ -1132,3 +1168,57 @@ abstract class WKWebpagePreferences extends NSObject { /// allowed to run. void setAllowsContentJavaScript(bool allow); } + +/// Data class used to respond to `SecTrust.getTrustResult`. +/// +/// The native method needs to return two values, so this custom class is +/// created to support this. +@ProxyApi() +abstract class GetTrustResultResponse extends NSObject { + /// The result code from the most recent trust evaluation. + late DartSecTrustResultType result; + + /// A result code. + /// + /// See https://developer.apple.com/documentation/security/security-framework-result-codes?language=objc. + late int resultCode; +} + +/// An object used to evaluate trust. +/// +/// See https://developer.apple.com/documentation/security/sectrust. +@ProxyApi(swiftOptions: SwiftProxyApiOptions(name: 'SecTrustWrapper')) +abstract class SecTrust extends NSObject { + /// Evaluates trust for the specified certificate and policies. + @static + @async + bool evaluateWithError(SecTrust trust); + + /// Returns an opaque cookie containing exceptions to trust policies that will + /// allow future evaluations of the current certificate to succeed. + @static + Uint8List? copyExceptions(SecTrust trust); + + /// Sets a list of exceptions that should be ignored when the certificate is + /// evaluated. + @static + bool setExceptions(SecTrust trust, Uint8List? exceptions); + + /// Returns the result code from the most recent trust evaluation. + @static + GetTrustResultResponse getTrustResult(SecTrust trust); + + /// Certificates used to evaluate trust. + @static + List? copyCertificateChain(SecTrust trust); +} + +/// An abstract Core Foundation-type object representing an X.509 certificate. +/// +/// See https://developer.apple.com/documentation/security/seccertificate. +@ProxyApi(swiftOptions: SwiftProxyApiOptions(name: 'SecCertificateWrapper')) +abstract class SecCertificate extends NSObject { + /// Returns a DER representation of a certificate given a certificate object. + @static + Uint8List copyData(SecCertificate certificate); +} diff --git a/packages/webview_flutter/webview_flutter_wkwebview/pubspec.yaml b/packages/webview_flutter/webview_flutter_wkwebview/pubspec.yaml index 67f2f644cd6e..73efba1dc8bb 100644 --- a/packages/webview_flutter/webview_flutter_wkwebview/pubspec.yaml +++ b/packages/webview_flutter/webview_flutter_wkwebview/pubspec.yaml @@ -2,7 +2,7 @@ name: webview_flutter_wkwebview description: A Flutter plugin that provides a WebView widget based on Apple's WKWebView control. repository: https://github.com/flutter/packages/tree/main/packages/webview_flutter/webview_flutter_wkwebview issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+webview%22 -version: 3.18.5 +version: 3.18.6 environment: sdk: ^3.5.0 @@ -32,7 +32,7 @@ dev_dependencies: flutter_test: sdk: flutter mockito: ^5.4.4 - pigeon: ^24.2.1 + pigeon: ^25.2.0 topics: - html From 7d14f4690732994d1ec8e8c2648ec108b9ff3972 Mon Sep 17 00:00:00 2001 From: Maurice Parrish <10687576+bparrishMines@users.noreply.github.com> Date: Mon, 14 Apr 2025 12:01:07 -0600 Subject: [PATCH 08/10] [webview_flutter_android] Adds internal wrapper methods for native `WebViewClient`. (#8964) This adds the SSL classes for https://github.com/flutter/packages/pull/7893 and a few extra `WebViewClient` methods. ## Pre-Review Checklist [^1]: Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling. --- .../webview_flutter_android/CHANGELOG.md | 4 + .../android/build.gradle | 1 + .../webviewflutter/AndroidWebkitLibrary.g.kt | 2180 ++++++++++++---- .../ClientCertRequestProxyApi.java | 40 + .../webviewflutter/MessageProxyApi.java | 25 + .../webviewflutter/ProxyApiRegistrar.java | 49 + .../SslCertificateDNameProxyApi.java | 43 + .../SslCertificateProxyApi.java | 79 + .../SslErrorHandlerProxyApi.java | 29 + .../webviewflutter/SslErrorProxyApi.java | 86 + .../webviewflutter/WebViewClientProxyApi.java | 115 + .../ClientCertRequestProxyApiTest.java | 53 + .../plugins/webviewflutter/MessageTest.java | 23 + .../SslCertificateDNameProxyApiTest.java | 62 + .../SslCertificateProxyApiTest.java | 71 + .../SslErrorHandlerProxyApiTest.java | 33 + .../webviewflutter/SslErrorProxyApiTest.java | 60 + .../WebViewClientCompatTest.java | 110 + .../webviewflutter/WebViewClientTest.java | 103 + .../example/android/app/build.gradle | 11 +- .../lib/src/android_proxy.dart | 48 +- .../lib/src/android_webkit.g.dart | 2280 +++++++++++++++-- .../lib/src/android_webview_controller.dart | 24 +- .../src/legacy/webview_android_widget.dart | 63 +- .../pigeons/android_webkit.dart | 230 +- .../webview_flutter_android/pubspec.yaml | 4 +- .../android_navigation_delegate_test.dart | 16 +- ...ndroid_navigation_delegate_test.mocks.dart | 117 +- .../test/android_webview_controller_test.dart | 73 +- ...android_webview_controller_test.mocks.dart | 1959 +++++--------- ...oid_webview_cookie_manager_test.mocks.dart | 393 +-- ...iew_android_cookie_manager_test.mocks.dart | 58 +- .../legacy/webview_android_widget_test.dart | 25 + .../webview_android_widget_test.mocks.dart | 799 ++---- 34 files changed, 6253 insertions(+), 3013 deletions(-) create mode 100644 packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/ClientCertRequestProxyApi.java create mode 100644 packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/MessageProxyApi.java create mode 100644 packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/SslCertificateDNameProxyApi.java create mode 100644 packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/SslCertificateProxyApi.java create mode 100644 packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/SslErrorHandlerProxyApi.java create mode 100644 packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/SslErrorProxyApi.java create mode 100644 packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/ClientCertRequestProxyApiTest.java create mode 100644 packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/MessageTest.java create mode 100644 packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/SslCertificateDNameProxyApiTest.java create mode 100644 packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/SslCertificateProxyApiTest.java create mode 100644 packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/SslErrorHandlerProxyApiTest.java create mode 100644 packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/SslErrorProxyApiTest.java diff --git a/packages/webview_flutter/webview_flutter_android/CHANGELOG.md b/packages/webview_flutter/webview_flutter_android/CHANGELOG.md index 4e600c635ad7..4b90957df142 100644 --- a/packages/webview_flutter/webview_flutter_android/CHANGELOG.md +++ b/packages/webview_flutter/webview_flutter_android/CHANGELOG.md @@ -1,3 +1,7 @@ +## 4.3.5 + +* Adds internal wrapper methods for native `WebViewClient`. + ## 4.3.4 * Bumps gradle from 8.0.0 to 8.9.0. diff --git a/packages/webview_flutter/webview_flutter_android/android/build.gradle b/packages/webview_flutter/webview_flutter_android/android/build.gradle index 050e9b6d8872..6c4148fb681e 100644 --- a/packages/webview_flutter/webview_flutter_android/android/build.gradle +++ b/packages/webview_flutter/webview_flutter_android/android/build.gradle @@ -52,6 +52,7 @@ android { implementation 'androidx.annotation:annotation:1.9.1' implementation 'androidx.webkit:webkit:1.12.1' testImplementation 'junit:junit:4.13.2' + testImplementation 'org.mockito:mockito-core:5.16.1' testImplementation 'org.mockito:mockito-inline:5.1.0' testImplementation 'androidx.test:core:1.4.0' } diff --git a/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/AndroidWebkitLibrary.g.kt b/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/AndroidWebkitLibrary.g.kt index 92cbf74aaa17..a347b77fa978 100644 --- a/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/AndroidWebkitLibrary.g.kt +++ b/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/AndroidWebkitLibrary.g.kt @@ -1,7 +1,7 @@ // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// Autogenerated from Pigeon (v22.5.0), do not edit directly. +// Autogenerated from Pigeon (v25.3.0), do not edit directly. // See also: https://pub.dev/packages/pigeon @file:Suppress("UNCHECKED_CAST", "ArrayInDataClass", "SyntheticAccessor") @@ -501,6 +501,58 @@ abstract class AndroidWebkitLibraryPigeonProxyApiRegistrar(val binaryMessenger: */ abstract fun getPigeonApiHttpAuthHandler(): PigeonApiHttpAuthHandler + /** + * An implementation of [PigeonApiAndroidMessage] used to add a new Dart instance of + * `AndroidMessage` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiAndroidMessage(): PigeonApiAndroidMessage + + /** + * An implementation of [PigeonApiClientCertRequest] used to add a new Dart instance of + * `ClientCertRequest` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiClientCertRequest(): PigeonApiClientCertRequest + + /** + * An implementation of [PigeonApiPrivateKey] used to add a new Dart instance of `PrivateKey` to + * the Dart `InstanceManager`. + */ + open fun getPigeonApiPrivateKey(): PigeonApiPrivateKey { + return PigeonApiPrivateKey(this) + } + + /** + * An implementation of [PigeonApiX509Certificate] used to add a new Dart instance of + * `X509Certificate` to the Dart `InstanceManager`. + */ + open fun getPigeonApiX509Certificate(): PigeonApiX509Certificate { + return PigeonApiX509Certificate(this) + } + + /** + * An implementation of [PigeonApiSslErrorHandler] used to add a new Dart instance of + * `SslErrorHandler` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiSslErrorHandler(): PigeonApiSslErrorHandler + + /** + * An implementation of [PigeonApiSslError] used to add a new Dart instance of `SslError` to the + * Dart `InstanceManager`. + */ + abstract fun getPigeonApiSslError(): PigeonApiSslError + + /** + * An implementation of [PigeonApiSslCertificateDName] used to add a new Dart instance of + * `SslCertificateDName` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiSslCertificateDName(): PigeonApiSslCertificateDName + + /** + * An implementation of [PigeonApiSslCertificate] used to add a new Dart instance of + * `SslCertificate` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiSslCertificate(): PigeonApiSslCertificate + fun setUp() { AndroidWebkitLibraryPigeonInstanceManagerApi.setUpMessageHandlers( binaryMessenger, instanceManager) @@ -523,6 +575,14 @@ abstract class AndroidWebkitLibraryPigeonProxyApiRegistrar(val binaryMessenger: PigeonApiGeolocationPermissionsCallback.setUpMessageHandlers( binaryMessenger, getPigeonApiGeolocationPermissionsCallback()) PigeonApiHttpAuthHandler.setUpMessageHandlers(binaryMessenger, getPigeonApiHttpAuthHandler()) + PigeonApiAndroidMessage.setUpMessageHandlers(binaryMessenger, getPigeonApiAndroidMessage()) + PigeonApiClientCertRequest.setUpMessageHandlers( + binaryMessenger, getPigeonApiClientCertRequest()) + PigeonApiSslErrorHandler.setUpMessageHandlers(binaryMessenger, getPigeonApiSslErrorHandler()) + PigeonApiSslError.setUpMessageHandlers(binaryMessenger, getPigeonApiSslError()) + PigeonApiSslCertificateDName.setUpMessageHandlers( + binaryMessenger, getPigeonApiSslCertificateDName()) + PigeonApiSslCertificate.setUpMessageHandlers(binaryMessenger, getPigeonApiSslCertificate()) } fun tearDown() { @@ -541,6 +601,12 @@ abstract class AndroidWebkitLibraryPigeonProxyApiRegistrar(val binaryMessenger: PigeonApiView.setUpMessageHandlers(binaryMessenger, null) PigeonApiGeolocationPermissionsCallback.setUpMessageHandlers(binaryMessenger, null) PigeonApiHttpAuthHandler.setUpMessageHandlers(binaryMessenger, null) + PigeonApiAndroidMessage.setUpMessageHandlers(binaryMessenger, null) + PigeonApiClientCertRequest.setUpMessageHandlers(binaryMessenger, null) + PigeonApiSslErrorHandler.setUpMessageHandlers(binaryMessenger, null) + PigeonApiSslError.setUpMessageHandlers(binaryMessenger, null) + PigeonApiSslCertificateDName.setUpMessageHandlers(binaryMessenger, null) + PigeonApiSslCertificate.setUpMessageHandlers(binaryMessenger, null) } } @@ -550,7 +616,12 @@ private class AndroidWebkitLibraryPigeonProxyApiBaseCodec( override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { return when (type) { 128.toByte() -> { - return registrar.instanceManager.getInstance(readValue(buffer) as Long) + val identifier: Long = readValue(buffer) as Long + val instance: Any? = registrar.instanceManager.getInstance(identifier) + if (instance == null) { + Log.e("PigeonProxyApiBaseCodec", "Failed to find instance with identifier: $identifier") + } + return instance } else -> super.readValueOfType(type, buffer) } @@ -571,6 +642,7 @@ private class AndroidWebkitLibraryPigeonProxyApiBaseCodec( value is String || value is FileChooserMode || value is ConsoleMessageLevel || + value is SslErrorType || value == null) { super.writeValue(stream, value) return @@ -619,6 +691,22 @@ private class AndroidWebkitLibraryPigeonProxyApiBaseCodec( registrar.getPigeonApiGeolocationPermissionsCallback().pigeon_newInstance(value) {} } else if (value is android.webkit.HttpAuthHandler) { registrar.getPigeonApiHttpAuthHandler().pigeon_newInstance(value) {} + } else if (value is android.os.Message) { + registrar.getPigeonApiAndroidMessage().pigeon_newInstance(value) {} + } else if (value is android.webkit.ClientCertRequest) { + registrar.getPigeonApiClientCertRequest().pigeon_newInstance(value) {} + } else if (value is java.security.PrivateKey) { + registrar.getPigeonApiPrivateKey().pigeon_newInstance(value) {} + } else if (value is java.security.cert.X509Certificate) { + registrar.getPigeonApiX509Certificate().pigeon_newInstance(value) {} + } else if (value is android.webkit.SslErrorHandler) { + registrar.getPigeonApiSslErrorHandler().pigeon_newInstance(value) {} + } else if (value is android.net.http.SslError) { + registrar.getPigeonApiSslError().pigeon_newInstance(value) {} + } else if (value is android.net.http.SslCertificate.DName) { + registrar.getPigeonApiSslCertificateDName().pigeon_newInstance(value) {} + } else if (value is android.net.http.SslCertificate) { + registrar.getPigeonApiSslCertificate().pigeon_newInstance(value) {} } when { @@ -726,6 +814,34 @@ enum class ConsoleMessageLevel(val raw: Int) { } } +/** + * Type of error for a SslCertificate. + * + * See https://developer.android.com/reference/android/net/http/SslError#SSL_DATE_INVALID. + */ +enum class SslErrorType(val raw: Int) { + /** The date of the certificate is invalid. */ + DATE_INVALID(0), + /** The certificate has expired. */ + EXPIRED(1), + /** Hostname mismatch. */ + ID_MISMATCH(2), + /** A generic error occurred. */ + INVALID(3), + /** The certificate is not yet valid. */ + NOT_YET_VALID(4), + /** The certificate authority is not trusted. */ + UNTRUSTED(5), + /** The type is not recognized by this wrapper. */ + UNKNOWN(6); + + companion object { + fun ofRaw(raw: Int): SslErrorType? { + return values().firstOrNull { it.raw == raw } + } + } +} + private open class AndroidWebkitLibraryPigeonCodec : StandardMessageCodec() { override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { return when (type) { @@ -735,6 +851,9 @@ private open class AndroidWebkitLibraryPigeonCodec : StandardMessageCodec() { 130.toByte() -> { return (readValue(buffer) as Long?)?.let { ConsoleMessageLevel.ofRaw(it.toInt()) } } + 131.toByte() -> { + return (readValue(buffer) as Long?)?.let { SslErrorType.ofRaw(it.toInt()) } + } else -> super.readValueOfType(type, buffer) } } @@ -749,6 +868,10 @@ private open class AndroidWebkitLibraryPigeonCodec : StandardMessageCodec() { stream.write(130) writeValue(stream, value.raw) } + is SslErrorType -> { + stream.write(131) + writeValue(stream, value.raw) + } else -> super.writeValue(stream, value) } } @@ -793,46 +916,44 @@ abstract class PigeonApiWebResourceRequest( callback( Result.failure( AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) - return - } - if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { - Result.success(Unit) - return - } - val pigeon_identifierArg = - pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) - val urlArg = url(pigeon_instanceArg) - val isForMainFrameArg = isForMainFrame(pigeon_instanceArg) - val isRedirectArg = isRedirect(pigeon_instanceArg) - val hasGestureArg = hasGesture(pigeon_instanceArg) - val methodArg = method(pigeon_instanceArg) - val requestHeadersArg = requestHeaders(pigeon_instanceArg) - val binaryMessenger = pigeonRegistrar.binaryMessenger - val codec = pigeonRegistrar.codec - val channelName = - "dev.flutter.pigeon.webview_flutter_android.WebResourceRequest.pigeon_newInstance" - val channel = BasicMessageChannel(binaryMessenger, channelName, codec) - channel.send( - listOf( - pigeon_identifierArg, - urlArg, - isForMainFrameArg, - isRedirectArg, - hasGestureArg, - methodArg, - requestHeadersArg)) { - if (it is List<*>) { - if (it.size > 1) { - callback( - Result.failure( - AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val urlArg = url(pigeon_instanceArg) + val isForMainFrameArg = isForMainFrame(pigeon_instanceArg) + val isRedirectArg = isRedirect(pigeon_instanceArg) + val hasGestureArg = hasGesture(pigeon_instanceArg) + val methodArg = method(pigeon_instanceArg) + val requestHeadersArg = requestHeaders(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.webview_flutter_android.WebResourceRequest.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send( + listOf( + pigeon_identifierArg, + urlArg, + isForMainFrameArg, + isRedirectArg, + hasGestureArg, + methodArg, + requestHeadersArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } } else { - callback(Result.success(Unit)) + callback(Result.failure(createConnectionError(channelName))) } - } else { - callback(Result.failure(createConnectionError(channelName))) } - } + } } } /** @@ -857,31 +978,29 @@ abstract class PigeonApiWebResourceResponse( callback( Result.failure( AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) - return - } - if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { - Result.success(Unit) - return - } - val pigeon_identifierArg = - pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) - val statusCodeArg = statusCode(pigeon_instanceArg) - val binaryMessenger = pigeonRegistrar.binaryMessenger - val codec = pigeonRegistrar.codec - val channelName = - "dev.flutter.pigeon.webview_flutter_android.WebResourceResponse.pigeon_newInstance" - val channel = BasicMessageChannel(binaryMessenger, channelName, codec) - channel.send(listOf(pigeon_identifierArg, statusCodeArg)) { - if (it is List<*>) { - if (it.size > 1) { - callback( - Result.failure( - AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val statusCodeArg = statusCode(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.webview_flutter_android.WebResourceResponse.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, statusCodeArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } } else { - callback(Result.success(Unit)) + callback(Result.failure(createConnectionError(channelName))) } - } else { - callback(Result.failure(createConnectionError(channelName))) } } } @@ -914,32 +1033,30 @@ abstract class PigeonApiWebResourceError( callback( Result.failure( AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) - return - } - if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { - Result.success(Unit) - return - } - val pigeon_identifierArg = - pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) - val errorCodeArg = errorCode(pigeon_instanceArg) - val descriptionArg = description(pigeon_instanceArg) - val binaryMessenger = pigeonRegistrar.binaryMessenger - val codec = pigeonRegistrar.codec - val channelName = - "dev.flutter.pigeon.webview_flutter_android.WebResourceError.pigeon_newInstance" - val channel = BasicMessageChannel(binaryMessenger, channelName, codec) - channel.send(listOf(pigeon_identifierArg, errorCodeArg, descriptionArg)) { - if (it is List<*>) { - if (it.size > 1) { - callback( - Result.failure( - AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val errorCodeArg = errorCode(pigeon_instanceArg) + val descriptionArg = description(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.webview_flutter_android.WebResourceError.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, errorCodeArg, descriptionArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } } else { - callback(Result.success(Unit)) + callback(Result.failure(createConnectionError(channelName))) } - } else { - callback(Result.failure(createConnectionError(channelName))) } } } @@ -969,32 +1086,30 @@ abstract class PigeonApiWebResourceErrorCompat( callback( Result.failure( AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) - return - } - if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { - Result.success(Unit) - return - } - val pigeon_identifierArg = - pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) - val errorCodeArg = errorCode(pigeon_instanceArg) - val descriptionArg = description(pigeon_instanceArg) - val binaryMessenger = pigeonRegistrar.binaryMessenger - val codec = pigeonRegistrar.codec - val channelName = - "dev.flutter.pigeon.webview_flutter_android.WebResourceErrorCompat.pigeon_newInstance" - val channel = BasicMessageChannel(binaryMessenger, channelName, codec) - channel.send(listOf(pigeon_identifierArg, errorCodeArg, descriptionArg)) { - if (it is List<*>) { - if (it.size > 1) { - callback( - Result.failure( - AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val errorCodeArg = errorCode(pigeon_instanceArg) + val descriptionArg = description(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.webview_flutter_android.WebResourceErrorCompat.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, errorCodeArg, descriptionArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } } else { - callback(Result.success(Unit)) + callback(Result.failure(createConnectionError(channelName))) } - } else { - callback(Result.failure(createConnectionError(channelName))) } } } @@ -1019,31 +1134,29 @@ abstract class PigeonApiWebViewPoint( callback( Result.failure( AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) - return - } - if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { - Result.success(Unit) - return - } - val pigeon_identifierArg = - pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) - val xArg = x(pigeon_instanceArg) - val yArg = y(pigeon_instanceArg) - val binaryMessenger = pigeonRegistrar.binaryMessenger - val codec = pigeonRegistrar.codec - val channelName = "dev.flutter.pigeon.webview_flutter_android.WebViewPoint.pigeon_newInstance" - val channel = BasicMessageChannel(binaryMessenger, channelName, codec) - channel.send(listOf(pigeon_identifierArg, xArg, yArg)) { - if (it is List<*>) { - if (it.size > 1) { - callback( - Result.failure( - AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val xArg = x(pigeon_instanceArg) + val yArg = y(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.webview_flutter_android.WebViewPoint.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, xArg, yArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } } else { - callback(Result.success(Unit)) + callback(Result.failure(createConnectionError(channelName))) } - } else { - callback(Result.failure(createConnectionError(channelName))) } } } @@ -1075,33 +1188,32 @@ abstract class PigeonApiConsoleMessage( callback( Result.failure( AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) - return - } - if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { - Result.success(Unit) - return - } - val pigeon_identifierArg = - pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) - val lineNumberArg = lineNumber(pigeon_instanceArg) - val messageArg = message(pigeon_instanceArg) - val levelArg = level(pigeon_instanceArg) - val sourceIdArg = sourceId(pigeon_instanceArg) - val binaryMessenger = pigeonRegistrar.binaryMessenger - val codec = pigeonRegistrar.codec - val channelName = "dev.flutter.pigeon.webview_flutter_android.ConsoleMessage.pigeon_newInstance" - val channel = BasicMessageChannel(binaryMessenger, channelName, codec) - channel.send(listOf(pigeon_identifierArg, lineNumberArg, messageArg, levelArg, sourceIdArg)) { - if (it is List<*>) { - if (it.size > 1) { - callback( - Result.failure( - AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val lineNumberArg = lineNumber(pigeon_instanceArg) + val messageArg = message(pigeon_instanceArg) + val levelArg = level(pigeon_instanceArg) + val sourceIdArg = sourceId(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.webview_flutter_android.ConsoleMessage.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, lineNumberArg, messageArg, levelArg, sourceIdArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } } else { - callback(Result.success(Unit)) + callback(Result.failure(createConnectionError(channelName))) } - } else { - callback(Result.failure(createConnectionError(channelName))) } } } @@ -1248,29 +1360,28 @@ abstract class PigeonApiCookieManager( callback( Result.failure( AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) - return - } - if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { - Result.success(Unit) - return - } - val pigeon_identifierArg = - pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) - val binaryMessenger = pigeonRegistrar.binaryMessenger - val codec = pigeonRegistrar.codec - val channelName = "dev.flutter.pigeon.webview_flutter_android.CookieManager.pigeon_newInstance" - val channel = BasicMessageChannel(binaryMessenger, channelName, codec) - channel.send(listOf(pigeon_identifierArg)) { - if (it is List<*>) { - if (it.size > 1) { - callback( - Result.failure( - AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.webview_flutter_android.CookieManager.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } } else { - callback(Result.success(Unit)) + callback(Result.failure(createConnectionError(channelName))) } - } else { - callback(Result.failure(createConnectionError(channelName))) } } } @@ -1960,29 +2071,27 @@ abstract class PigeonApiWebView( callback( Result.failure( AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) - return - } - if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { - Result.success(Unit) - return - } - val pigeon_identifierArg = - pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) - val binaryMessenger = pigeonRegistrar.binaryMessenger - val codec = pigeonRegistrar.codec - val channelName = "dev.flutter.pigeon.webview_flutter_android.WebView.pigeon_newInstance" - val channel = BasicMessageChannel(binaryMessenger, channelName, codec) - channel.send(listOf(pigeon_identifierArg)) { - if (it is List<*>) { - if (it.size > 1) { - callback( - Result.failure( - AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.webview_flutter_android.WebView.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } } else { - callback(Result.success(Unit)) + callback(Result.failure(createConnectionError(channelName))) } - } else { - callback(Result.failure(createConnectionError(channelName))) } } } @@ -2515,29 +2624,27 @@ abstract class PigeonApiWebSettings( callback( Result.failure( AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) - return - } - if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { - Result.success(Unit) - return - } - val pigeon_identifierArg = - pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) - val binaryMessenger = pigeonRegistrar.binaryMessenger - val codec = pigeonRegistrar.codec - val channelName = "dev.flutter.pigeon.webview_flutter_android.WebSettings.pigeon_newInstance" - val channel = BasicMessageChannel(binaryMessenger, channelName, codec) - channel.send(listOf(pigeon_identifierArg)) { - if (it is List<*>) { - if (it.size > 1) { - callback( - Result.failure( - AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.webview_flutter_android.WebSettings.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } } else { - callback(Result.success(Unit)) + callback(Result.failure(createConnectionError(channelName))) } - } else { - callback(Result.failure(createConnectionError(channelName))) } } } @@ -2593,14 +2700,16 @@ abstract class PigeonApiJavaScriptChannel( callback( Result.failure( AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) - return - } - if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { - Result.success(Unit) - return + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + callback( + Result.failure( + AndroidWebKitError( + "new-instance-error", + "Attempting to create a new Dart instance of JavaScriptChannel, but the class has a nonnull callback method.", + ""))) } - throw IllegalStateException( - "Attempting to create a new Dart instance of JavaScriptChannel, but the class has a nonnull callback method.") } /** Handles callbacks messages from JavaScript. */ @@ -2729,29 +2838,28 @@ abstract class PigeonApiWebViewClient( callback( Result.failure( AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) - return - } - if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { - Result.success(Unit) - return - } - val pigeon_identifierArg = - pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) - val binaryMessenger = pigeonRegistrar.binaryMessenger - val codec = pigeonRegistrar.codec - val channelName = "dev.flutter.pigeon.webview_flutter_android.WebViewClient.pigeon_newInstance" - val channel = BasicMessageChannel(binaryMessenger, channelName, codec) - channel.send(listOf(pigeon_identifierArg)) { - if (it is List<*>) { - if (it.size > 1) { - callback( - Result.failure( - AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.webview_flutter_android.WebViewClient.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } } else { - callback(Result.success(Unit)) + callback(Result.failure(createConnectionError(channelName))) } - } else { - callback(Result.failure(createConnectionError(channelName))) } } } @@ -3098,37 +3206,278 @@ abstract class PigeonApiWebViewClient( } } } -} -/** - * Handles notifications that a file should be downloaded. - * - * See https://developer.android.com/reference/android/webkit/DownloadListener. - */ -@Suppress("UNCHECKED_CAST") -abstract class PigeonApiDownloadListener( - open val pigeonRegistrar: AndroidWebkitLibraryPigeonProxyApiRegistrar -) { - abstract fun pigeon_defaultConstructor(): android.webkit.DownloadListener - companion object { - @Suppress("LocalVariableName") - fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiDownloadListener?) { - val codec = api?.pigeonRegistrar?.codec ?: AndroidWebkitLibraryPigeonCodec() - run { - val channel = - BasicMessageChannel( - binaryMessenger, - "dev.flutter.pigeon.webview_flutter_android.DownloadListener.pigeon_defaultConstructor", - codec) - if (api != null) { - channel.setMessageHandler { message, reply -> - val args = message as List - val pigeon_identifierArg = args[0] as Long - val wrapped: List = - try { - api.pigeonRegistrar.instanceManager.addDartCreatedInstance( - api.pigeon_defaultConstructor(), pigeon_identifierArg) - listOf(null) + /** + * Ask the host application if the browser should resend data as the requested page was a result + * of a POST. + */ + fun onFormResubmission( + pigeon_instanceArg: android.webkit.WebViewClient, + viewArg: android.webkit.WebView, + dontResendArg: android.os.Message, + resendArg: android.os.Message, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + return + } + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.webview_flutter_android.WebViewClient.onFormResubmission" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_instanceArg, viewArg, dontResendArg, resendArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + + /** + * Notify the host application that the WebView will load the resource specified by the given url. + */ + fun onLoadResource( + pigeon_instanceArg: android.webkit.WebViewClient, + viewArg: android.webkit.WebView, + urlArg: String, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + return + } + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.webview_flutter_android.WebViewClient.onLoadResource" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_instanceArg, viewArg, urlArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + + /** + * Notify the host application that WebView content left over from previous page navigations will + * no longer be drawn. + */ + fun onPageCommitVisible( + pigeon_instanceArg: android.webkit.WebViewClient, + viewArg: android.webkit.WebView, + urlArg: String, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + return + } + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageCommitVisible" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_instanceArg, viewArg, urlArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + + /** Notify the host application to handle a SSL client certificate request. */ + fun onReceivedClientCertRequest( + pigeon_instanceArg: android.webkit.WebViewClient, + viewArg: android.webkit.WebView, + requestArg: android.webkit.ClientCertRequest, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + return + } + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedClientCertRequest" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_instanceArg, viewArg, requestArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + + /** + * Notify the host application that a request to automatically log in the user has been processed. + */ + fun onReceivedLoginRequest( + pigeon_instanceArg: android.webkit.WebViewClient, + viewArg: android.webkit.WebView, + realmArg: String, + accountArg: String?, + argsArg: String, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + return + } + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedLoginRequest" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_instanceArg, viewArg, realmArg, accountArg, argsArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + + /** Notifies the host application that an SSL error occurred while loading a resource. */ + fun onReceivedSslError( + pigeon_instanceArg: android.webkit.WebViewClient, + viewArg: android.webkit.WebView, + handlerArg: android.webkit.SslErrorHandler, + errorArg: android.net.http.SslError, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + return + } + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedSslError" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_instanceArg, viewArg, handlerArg, errorArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + + /** Notify the host application that the scale applied to the WebView has changed. */ + fun onScaleChanged( + pigeon_instanceArg: android.webkit.WebViewClient, + viewArg: android.webkit.WebView, + oldScaleArg: Double, + newScaleArg: Double, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + return + } + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.webview_flutter_android.WebViewClient.onScaleChanged" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_instanceArg, viewArg, oldScaleArg, newScaleArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } +} +/** + * Handles notifications that a file should be downloaded. + * + * See https://developer.android.com/reference/android/webkit/DownloadListener. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiDownloadListener( + open val pigeonRegistrar: AndroidWebkitLibraryPigeonProxyApiRegistrar +) { + abstract fun pigeon_defaultConstructor(): android.webkit.DownloadListener + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiDownloadListener?) { + val codec = api?.pigeonRegistrar?.codec ?: AndroidWebkitLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.webview_flutter_android.DownloadListener.pigeon_defaultConstructor", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.pigeon_defaultConstructor(), pigeon_identifierArg) + listOf(null) } catch (exception: Throwable) { wrapError(exception) } @@ -3151,14 +3500,16 @@ abstract class PigeonApiDownloadListener( callback( Result.failure( AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) - return - } - if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { - Result.success(Unit) - return + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + callback( + Result.failure( + AndroidWebKitError( + "new-instance-error", + "Attempting to create a new Dart instance of DownloadListener, but the class has a nonnull callback method.", + ""))) } - throw IllegalStateException( - "Attempting to create a new Dart instance of DownloadListener, but the class has a nonnull callback method.") } /** Notify the host application that a file should be downloaded. */ @@ -3485,31 +3836,15 @@ abstract class PigeonApiWebChromeClient( callback( Result.failure( AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) - return - } - if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { - Result.success(Unit) - return - } - val pigeon_identifierArg = - pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) - val binaryMessenger = pigeonRegistrar.binaryMessenger - val codec = pigeonRegistrar.codec - val channelName = - "dev.flutter.pigeon.webview_flutter_android.WebChromeClient.pigeon_newInstance" - val channel = BasicMessageChannel(binaryMessenger, channelName, codec) - channel.send(listOf(pigeon_identifierArg)) { - if (it is List<*>) { - if (it.size > 1) { - callback( - Result.failure( - AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) - } else { - callback(Result.success(Unit)) - } - } else { - callback(Result.failure(createConnectionError(channelName))) - } + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + callback( + Result.failure( + AndroidWebKitError( + "new-instance-error", + "Attempting to create a new Dart instance of WebChromeClient, but the class has a nonnull callback method.", + ""))) } } @@ -4033,30 +4368,28 @@ abstract class PigeonApiFlutterAssetManager( callback( Result.failure( AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) - return - } - if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { - Result.success(Unit) - return - } - val pigeon_identifierArg = - pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) - val binaryMessenger = pigeonRegistrar.binaryMessenger - val codec = pigeonRegistrar.codec - val channelName = - "dev.flutter.pigeon.webview_flutter_android.FlutterAssetManager.pigeon_newInstance" - val channel = BasicMessageChannel(binaryMessenger, channelName, codec) - channel.send(listOf(pigeon_identifierArg)) { - if (it is List<*>) { - if (it.size > 1) { - callback( - Result.failure( - AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.webview_flutter_android.FlutterAssetManager.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } } else { - callback(Result.success(Unit)) + callback(Result.failure(createConnectionError(channelName))) } - } else { - callback(Result.failure(createConnectionError(channelName))) } } } @@ -4139,29 +4472,27 @@ abstract class PigeonApiWebStorage( callback( Result.failure( AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) - return - } - if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { - Result.success(Unit) - return - } - val pigeon_identifierArg = - pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) - val binaryMessenger = pigeonRegistrar.binaryMessenger - val codec = pigeonRegistrar.codec - val channelName = "dev.flutter.pigeon.webview_flutter_android.WebStorage.pigeon_newInstance" - val channel = BasicMessageChannel(binaryMessenger, channelName, codec) - channel.send(listOf(pigeon_identifierArg)) { - if (it is List<*>) { - if (it.size > 1) { - callback( - Result.failure( - AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.webview_flutter_android.WebStorage.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } } else { - callback(Result.success(Unit)) + callback(Result.failure(createConnectionError(channelName))) } - } else { - callback(Result.failure(createConnectionError(channelName))) } } } @@ -4205,38 +4536,40 @@ abstract class PigeonApiFileChooserParams( callback( Result.failure( AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) - return - } - if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { - Result.success(Unit) - return - } - val pigeon_identifierArg = - pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) - val isCaptureEnabledArg = isCaptureEnabled(pigeon_instanceArg) - val acceptTypesArg = acceptTypes(pigeon_instanceArg) - val modeArg = mode(pigeon_instanceArg) - val filenameHintArg = filenameHint(pigeon_instanceArg) - val binaryMessenger = pigeonRegistrar.binaryMessenger - val codec = pigeonRegistrar.codec - val channelName = - "dev.flutter.pigeon.webview_flutter_android.FileChooserParams.pigeon_newInstance" - val channel = BasicMessageChannel(binaryMessenger, channelName, codec) - channel.send( - listOf( - pigeon_identifierArg, isCaptureEnabledArg, acceptTypesArg, modeArg, filenameHintArg)) { - if (it is List<*>) { - if (it.size > 1) { - callback( - Result.failure( - AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val isCaptureEnabledArg = isCaptureEnabled(pigeon_instanceArg) + val acceptTypesArg = acceptTypes(pigeon_instanceArg) + val modeArg = mode(pigeon_instanceArg) + val filenameHintArg = filenameHint(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.webview_flutter_android.FileChooserParams.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send( + listOf( + pigeon_identifierArg, + isCaptureEnabledArg, + acceptTypesArg, + modeArg, + filenameHintArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } } else { - callback(Result.success(Unit)) + callback(Result.failure(createConnectionError(channelName))) } - } else { - callback(Result.failure(createConnectionError(channelName))) } - } + } } } /** @@ -4321,31 +4654,29 @@ abstract class PigeonApiPermissionRequest( callback( Result.failure( AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) - return - } - if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { - Result.success(Unit) - return - } - val pigeon_identifierArg = - pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) - val resourcesArg = resources(pigeon_instanceArg) - val binaryMessenger = pigeonRegistrar.binaryMessenger - val codec = pigeonRegistrar.codec - val channelName = - "dev.flutter.pigeon.webview_flutter_android.PermissionRequest.pigeon_newInstance" - val channel = BasicMessageChannel(binaryMessenger, channelName, codec) - channel.send(listOf(pigeon_identifierArg, resourcesArg)) { - if (it is List<*>) { - if (it.size > 1) { - callback( - Result.failure( - AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val resourcesArg = resources(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.webview_flutter_android.PermissionRequest.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, resourcesArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } } else { - callback(Result.success(Unit)) + callback(Result.failure(createConnectionError(channelName))) } - } else { - callback(Result.failure(createConnectionError(channelName))) } } } @@ -4405,30 +4736,28 @@ abstract class PigeonApiCustomViewCallback( callback( Result.failure( AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) - return - } - if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { - Result.success(Unit) - return - } - val pigeon_identifierArg = - pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) - val binaryMessenger = pigeonRegistrar.binaryMessenger - val codec = pigeonRegistrar.codec - val channelName = - "dev.flutter.pigeon.webview_flutter_android.CustomViewCallback.pigeon_newInstance" - val channel = BasicMessageChannel(binaryMessenger, channelName, codec) - channel.send(listOf(pigeon_identifierArg)) { - if (it is List<*>) { - if (it.size > 1) { - callback( - Result.failure( - AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.webview_flutter_android.CustomViewCallback.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } } else { - callback(Result.success(Unit)) + callback(Result.failure(createConnectionError(channelName))) } - } else { - callback(Result.failure(createConnectionError(channelName))) } } } @@ -4533,29 +4862,27 @@ abstract class PigeonApiView( callback( Result.failure( AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) - return - } - if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { - Result.success(Unit) - return - } - val pigeon_identifierArg = - pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) - val binaryMessenger = pigeonRegistrar.binaryMessenger - val codec = pigeonRegistrar.codec - val channelName = "dev.flutter.pigeon.webview_flutter_android.View.pigeon_newInstance" - val channel = BasicMessageChannel(binaryMessenger, channelName, codec) - channel.send(listOf(pigeon_identifierArg)) { - if (it is List<*>) { - if (it.size > 1) { - callback( - Result.failure( - AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.webview_flutter_android.View.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } } else { - callback(Result.success(Unit)) + callback(Result.failure(createConnectionError(channelName))) } - } else { - callback(Result.failure(createConnectionError(channelName))) } } } @@ -4627,30 +4954,28 @@ abstract class PigeonApiGeolocationPermissionsCallback( callback( Result.failure( AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) - return - } - if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { - Result.success(Unit) - return - } - val pigeon_identifierArg = - pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) - val binaryMessenger = pigeonRegistrar.binaryMessenger - val codec = pigeonRegistrar.codec - val channelName = - "dev.flutter.pigeon.webview_flutter_android.GeolocationPermissionsCallback.pigeon_newInstance" - val channel = BasicMessageChannel(binaryMessenger, channelName, codec) - channel.send(listOf(pigeon_identifierArg)) { - if (it is List<*>) { - if (it.size > 1) { - callback( - Result.failure( - AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.webview_flutter_android.GeolocationPermissionsCallback.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } } else { - callback(Result.success(Unit)) + callback(Result.failure(createConnectionError(channelName))) } - } else { - callback(Result.failure(createConnectionError(channelName))) } } } @@ -4767,30 +5092,903 @@ abstract class PigeonApiHttpAuthHandler( callback( Result.failure( AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) - return + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.webview_flutter_android.HttpAuthHandler.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } } - if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { - Result.success(Unit) - return + } +} +/** + * Defines a message containing a description and arbitrary data object that can be sent to a + * `Handler`. + * + * See https://developer.android.com/reference/android/os/Message. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiAndroidMessage( + open val pigeonRegistrar: AndroidWebkitLibraryPigeonProxyApiRegistrar +) { + /** + * Sends this message to the Android native `Handler` specified by getTarget(). + * + * Throws a null pointer exception if this field has not been set. + */ + abstract fun sendToTarget(pigeon_instance: android.os.Message) + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiAndroidMessage?) { + val codec = api?.pigeonRegistrar?.codec ?: AndroidWebkitLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.webview_flutter_android.AndroidMessage.sendToTarget", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as android.os.Message + val wrapped: List = + try { + api.sendToTarget(pigeon_instanceArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } } - val pigeon_identifierArg = - pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) - val binaryMessenger = pigeonRegistrar.binaryMessenger - val codec = pigeonRegistrar.codec - val channelName = - "dev.flutter.pigeon.webview_flutter_android.HttpAuthHandler.pigeon_newInstance" - val channel = BasicMessageChannel(binaryMessenger, channelName, codec) - channel.send(listOf(pigeon_identifierArg)) { - if (it is List<*>) { - if (it.size > 1) { - callback( - Result.failure( - AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of AndroidMessage and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance(pigeon_instanceArg: android.os.Message, callback: (Result) -> Unit) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.webview_flutter_android.AndroidMessage.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } } else { - callback(Result.success(Unit)) + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * Defines a message containing a description and arbitrary data object that can be sent to a + * `Handler`. + * + * See https://developer.android.com/reference/android/webkit/ClientCertRequest. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiClientCertRequest( + open val pigeonRegistrar: AndroidWebkitLibraryPigeonProxyApiRegistrar +) { + /** Cancel this request. */ + abstract fun cancel(pigeon_instance: android.webkit.ClientCertRequest) + + /** Ignore the request for now. */ + abstract fun ignore(pigeon_instance: android.webkit.ClientCertRequest) + + /** Proceed with the specified private key and client certificate chain. */ + abstract fun proceed( + pigeon_instance: android.webkit.ClientCertRequest, + privateKey: java.security.PrivateKey, + chain: List + ) + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiClientCertRequest?) { + val codec = api?.pigeonRegistrar?.codec ?: AndroidWebkitLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.webview_flutter_android.ClientCertRequest.cancel", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as android.webkit.ClientCertRequest + val wrapped: List = + try { + api.cancel(pigeon_instanceArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.webview_flutter_android.ClientCertRequest.ignore", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as android.webkit.ClientCertRequest + val wrapped: List = + try { + api.ignore(pigeon_instanceArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.webview_flutter_android.ClientCertRequest.proceed", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as android.webkit.ClientCertRequest + val privateKeyArg = args[1] as java.security.PrivateKey + val chainArg = args[2] as List + val wrapped: List = + try { + api.proceed(pigeon_instanceArg, privateKeyArg, chainArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of ClientCertRequest and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: android.webkit.ClientCertRequest, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.webview_flutter_android.ClientCertRequest.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * A private key. + * + * The purpose of this interface is to group (and provide type safety for) all private key + * interfaces. + * + * See https://developer.android.com/reference/java/security/PrivateKey. + */ +@Suppress("UNCHECKED_CAST") +open class PigeonApiPrivateKey( + open val pigeonRegistrar: AndroidWebkitLibraryPigeonProxyApiRegistrar +) { + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of PrivateKey and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: java.security.PrivateKey, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.webview_flutter_android.PrivateKey.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * Abstract class for X.509 certificates. + * + * This provides a standard way to access all the attributes of an X.509 certificate. + * + * See https://developer.android.com/reference/java/security/cert/X509Certificate. + */ +@Suppress("UNCHECKED_CAST") +open class PigeonApiX509Certificate( + open val pigeonRegistrar: AndroidWebkitLibraryPigeonProxyApiRegistrar +) { + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of X509Certificate and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: java.security.cert.X509Certificate, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.webview_flutter_android.X509Certificate.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * Represents a request for handling an SSL error. + * + * See https://developer.android.com/reference/android/webkit/SslErrorHandler. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiSslErrorHandler( + open val pigeonRegistrar: AndroidWebkitLibraryPigeonProxyApiRegistrar +) { + /** + * Instructs the WebView that encountered the SSL certificate error to terminate communication + * with the server. + */ + abstract fun cancel(pigeon_instance: android.webkit.SslErrorHandler) + + /** + * Instructs the WebView that encountered the SSL certificate error to ignore the error and + * continue communicating with the server. + */ + abstract fun proceed(pigeon_instance: android.webkit.SslErrorHandler) + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiSslErrorHandler?) { + val codec = api?.pigeonRegistrar?.codec ?: AndroidWebkitLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.webview_flutter_android.SslErrorHandler.cancel", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as android.webkit.SslErrorHandler + val wrapped: List = + try { + api.cancel(pigeon_instanceArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.webview_flutter_android.SslErrorHandler.proceed", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as android.webkit.SslErrorHandler + val wrapped: List = + try { + api.proceed(pigeon_instanceArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of SslErrorHandler and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: android.webkit.SslErrorHandler, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.webview_flutter_android.SslErrorHandler.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * This class represents a set of one or more SSL errors and the associated SSL certificate. + * + * See https://developer.android.com/reference/android/net/http/SslError. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiSslError( + open val pigeonRegistrar: AndroidWebkitLibraryPigeonProxyApiRegistrar +) { + /** Gets the SSL certificate associated with this object. */ + abstract fun certificate( + pigeon_instance: android.net.http.SslError + ): android.net.http.SslCertificate + + /** Gets the URL associated with this object. */ + abstract fun url(pigeon_instance: android.net.http.SslError): String + + /** Gets the most severe SSL error in this object's set of errors. */ + abstract fun getPrimaryError(pigeon_instance: android.net.http.SslError): SslErrorType + + /** Determines whether this object includes the supplied error. */ + abstract fun hasError(pigeon_instance: android.net.http.SslError, error: SslErrorType): Boolean + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiSslError?) { + val codec = api?.pigeonRegistrar?.codec ?: AndroidWebkitLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.webview_flutter_android.SslError.getPrimaryError", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as android.net.http.SslError + val wrapped: List = + try { + listOf(api.getPrimaryError(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.webview_flutter_android.SslError.hasError", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as android.net.http.SslError + val errorArg = args[1] as SslErrorType + val wrapped: List = + try { + listOf(api.hasError(pigeon_instanceArg, errorArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of SslError and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: android.net.http.SslError, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val certificateArg = certificate(pigeon_instanceArg) + val urlArg = url(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.webview_flutter_android.SslError.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, certificateArg, urlArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * A distinguished name helper class. + * + * A 3-tuple of: the most specific common name (CN) the most specific organization (O) the most + * specific organizational unit (OU) + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiSslCertificateDName( + open val pigeonRegistrar: AndroidWebkitLibraryPigeonProxyApiRegistrar +) { + /** The most specific Common-name (CN) component of this name. */ + abstract fun getCName(pigeon_instance: android.net.http.SslCertificate.DName): String + + /** The distinguished name (normally includes CN, O, and OU names). */ + abstract fun getDName(pigeon_instance: android.net.http.SslCertificate.DName): String + + /** The most specific Organization (O) component of this name. */ + abstract fun getOName(pigeon_instance: android.net.http.SslCertificate.DName): String + + /** The most specific Organizational Unit (OU) component of this name. */ + abstract fun getUName(pigeon_instance: android.net.http.SslCertificate.DName): String + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiSslCertificateDName?) { + val codec = api?.pigeonRegistrar?.codec ?: AndroidWebkitLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.webview_flutter_android.SslCertificateDName.getCName", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as android.net.http.SslCertificate.DName + val wrapped: List = + try { + listOf(api.getCName(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.webview_flutter_android.SslCertificateDName.getDName", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as android.net.http.SslCertificate.DName + val wrapped: List = + try { + listOf(api.getDName(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.webview_flutter_android.SslCertificateDName.getOName", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as android.net.http.SslCertificate.DName + val wrapped: List = + try { + listOf(api.getOName(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.webview_flutter_android.SslCertificateDName.getUName", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as android.net.http.SslCertificate.DName + val wrapped: List = + try { + listOf(api.getUName(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of SslCertificateDName and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: android.net.http.SslCertificate.DName, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.webview_flutter_android.SslCertificateDName.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * SSL certificate info (certificate details) class. + * + * See https://developer.android.com/reference/android/net/http/SslCertificate. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiSslCertificate( + open val pigeonRegistrar: AndroidWebkitLibraryPigeonProxyApiRegistrar +) { + /** Issued-by distinguished name or null if none has been set. */ + abstract fun getIssuedBy( + pigeon_instance: android.net.http.SslCertificate + ): android.net.http.SslCertificate.DName? + + /** Issued-to distinguished name or null if none has been set. */ + abstract fun getIssuedTo( + pigeon_instance: android.net.http.SslCertificate + ): android.net.http.SslCertificate.DName? + + /** Not-after date from the certificate validity period or null if none has been set. */ + abstract fun getValidNotAfterMsSinceEpoch(pigeon_instance: android.net.http.SslCertificate): Long? + + /** Not-before date from the certificate validity period or null if none has been set. */ + abstract fun getValidNotBeforeMsSinceEpoch( + pigeon_instance: android.net.http.SslCertificate + ): Long? + + /** + * The X509Certificate used to create this SslCertificate or null if no certificate was provided. + * + * Always returns null on Android versions below Q. + */ + abstract fun getX509Certificate( + pigeon_instance: android.net.http.SslCertificate + ): java.security.cert.X509Certificate? + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiSslCertificate?) { + val codec = api?.pigeonRegistrar?.codec ?: AndroidWebkitLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.webview_flutter_android.SslCertificate.getIssuedBy", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as android.net.http.SslCertificate + val wrapped: List = + try { + listOf(api.getIssuedBy(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.webview_flutter_android.SslCertificate.getIssuedTo", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as android.net.http.SslCertificate + val wrapped: List = + try { + listOf(api.getIssuedTo(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.webview_flutter_android.SslCertificate.getValidNotAfterMsSinceEpoch", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as android.net.http.SslCertificate + val wrapped: List = + try { + listOf(api.getValidNotAfterMsSinceEpoch(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.webview_flutter_android.SslCertificate.getValidNotBeforeMsSinceEpoch", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as android.net.http.SslCertificate + val wrapped: List = + try { + listOf(api.getValidNotBeforeMsSinceEpoch(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.webview_flutter_android.SslCertificate.getX509Certificate", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as android.net.http.SslCertificate + val wrapped: List = + try { + listOf(api.getX509Certificate(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of SslCertificate and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: android.net.http.SslCertificate, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + AndroidWebKitError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.webview_flutter_android.SslCertificate.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + AndroidWebKitError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) } - } else { - callback(Result.failure(createConnectionError(channelName))) } } } diff --git a/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/ClientCertRequestProxyApi.java b/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/ClientCertRequestProxyApi.java new file mode 100644 index 000000000000..54bedf8d8ec8 --- /dev/null +++ b/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/ClientCertRequestProxyApi.java @@ -0,0 +1,40 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.webviewflutter; + +import android.webkit.ClientCertRequest; +import androidx.annotation.NonNull; +import java.security.PrivateKey; +import java.security.cert.X509Certificate; +import java.util.List; + +/** + * ProxyApi implementation for {@link ClientCertRequest}. This class may handle instantiating native + * object instances that are attached to a Dart instance or handle method calls on the associated + * native class or an instance of that class. + */ +class ClientCertRequestProxyApi extends PigeonApiClientCertRequest { + ClientCertRequestProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @Override + public void cancel(@NonNull ClientCertRequest pigeon_instance) { + pigeon_instance.cancel(); + } + + @Override + public void ignore(@NonNull ClientCertRequest pigeon_instance) { + pigeon_instance.ignore(); + } + + @Override + public void proceed( + @NonNull ClientCertRequest pigeon_instance, + @NonNull PrivateKey privateKey, + @NonNull List chain) { + pigeon_instance.proceed(privateKey, chain.toArray(new X509Certificate[0])); + } +} diff --git a/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/MessageProxyApi.java b/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/MessageProxyApi.java new file mode 100644 index 000000000000..e0cb6f572939 --- /dev/null +++ b/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/MessageProxyApi.java @@ -0,0 +1,25 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.webviewflutter; + +import android.os.Message; +import androidx.annotation.NonNull; + +/** + * Proxy API implementation for `Message`. + * + *

This class may handle instantiating and adding native object instances that are attached to a + * Dart instance or handle method calls on the associated native class or an instance of the class. + */ +public class MessageProxyApi extends PigeonApiAndroidMessage { + public MessageProxyApi(@NonNull AndroidWebkitLibraryPigeonProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @Override + public void sendToTarget(@NonNull Message pigeon_instance) { + pigeon_instance.sendToTarget(); + } +} diff --git a/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/ProxyApiRegistrar.java b/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/ProxyApiRegistrar.java index bc86c51dd28c..c4d8d556746f 100644 --- a/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/ProxyApiRegistrar.java +++ b/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/ProxyApiRegistrar.java @@ -56,6 +56,19 @@ void logError(String tag, Throwable exception) { + Log.getStackTraceString(exception)); } + /** Creates an exception when the `unknown` enum value is passed to a host method. */ + @NonNull + IllegalArgumentException createUnknownEnumException(@NonNull Object enumValue) { + return new IllegalArgumentException(enumValue + " doesn't represent a native value."); + } + + /** Creates the error message when a method is called on an unsupported version. */ + @NonNull + String createUnsupportedVersionMessage( + @NonNull String method, @NonNull String versionRequirements) { + return method + " requires " + versionRequirements + "."; + } + @NonNull @Override public PigeonApiWebResourceRequest getPigeonApiWebResourceRequest() { @@ -183,6 +196,42 @@ public PigeonApiHttpAuthHandler getPigeonApiHttpAuthHandler() { return new HttpAuthHandlerProxyApi(this); } + @NonNull + @Override + public PigeonApiClientCertRequest getPigeonApiClientCertRequest() { + return new ClientCertRequestProxyApi(this); + } + + @NonNull + @Override + public PigeonApiSslErrorHandler getPigeonApiSslErrorHandler() { + return new SslErrorHandlerProxyApi(this); + } + + @NonNull + @Override + public PigeonApiSslError getPigeonApiSslError() { + return new SslErrorProxyApi(this); + } + + @NonNull + @Override + public PigeonApiSslCertificateDName getPigeonApiSslCertificateDName() { + return new SslCertificateDNameProxyApi(this); + } + + @NonNull + @Override + public PigeonApiSslCertificate getPigeonApiSslCertificate() { + return new SslCertificateProxyApi(this); + } + + @NonNull + @Override + public PigeonApiAndroidMessage getPigeonApiAndroidMessage() { + return new MessageProxyApi(this); + } + @NonNull public Context getContext() { return context; diff --git a/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/SslCertificateDNameProxyApi.java b/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/SslCertificateDNameProxyApi.java new file mode 100644 index 000000000000..d26b06564081 --- /dev/null +++ b/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/SslCertificateDNameProxyApi.java @@ -0,0 +1,43 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.webviewflutter; + +import android.net.http.SslCertificate; +import androidx.annotation.NonNull; + +/** + * ProxyApi implementation for {@link SslCertificate.DName}. This class may handle instantiating + * native object instances that are attached to a Dart instance or handle method calls on the + * associated native class or an instance of that class. + */ +class SslCertificateDNameProxyApi extends PigeonApiSslCertificateDName { + SslCertificateDNameProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public String getCName(@NonNull SslCertificate.DName pigeon_instance) { + return pigeon_instance.getCName(); + } + + @NonNull + @Override + public String getDName(@NonNull SslCertificate.DName pigeon_instance) { + return pigeon_instance.getDName(); + } + + @NonNull + @Override + public String getOName(@NonNull SslCertificate.DName pigeon_instance) { + return pigeon_instance.getOName(); + } + + @NonNull + @Override + public String getUName(@NonNull SslCertificate.DName pigeon_instance) { + return pigeon_instance.getUName(); + } +} diff --git a/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/SslCertificateProxyApi.java b/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/SslCertificateProxyApi.java new file mode 100644 index 000000000000..8286961f06a1 --- /dev/null +++ b/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/SslCertificateProxyApi.java @@ -0,0 +1,79 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.webviewflutter; + +import android.net.http.SslCertificate; +import android.os.Build; +import android.util.Log; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import java.util.Date; + +/** + * ProxyApi implementation for {@link SslCertificate}. This class may handle instantiating native + * object instances that are attached to a Dart instance or handle method calls on the associated + * native class or an instance of that class. + */ +class SslCertificateProxyApi extends PigeonApiSslCertificate { + SslCertificateProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public ProxyApiRegistrar getPigeonRegistrar() { + return (ProxyApiRegistrar) super.getPigeonRegistrar(); + } + + @Nullable + @Override + public android.net.http.SslCertificate.DName getIssuedBy( + @NonNull SslCertificate pigeon_instance) { + return pigeon_instance.getIssuedBy(); + } + + @Nullable + @Override + public android.net.http.SslCertificate.DName getIssuedTo( + @NonNull SslCertificate pigeon_instance) { + return pigeon_instance.getIssuedTo(); + } + + @Nullable + @Override + public Long getValidNotAfterMsSinceEpoch(@NonNull SslCertificate pigeon_instance) { + final Date date = pigeon_instance.getValidNotAfterDate(); + if (date != null) { + return date.getTime(); + } + return null; + } + + @Nullable + @Override + public Long getValidNotBeforeMsSinceEpoch(@NonNull SslCertificate pigeon_instance) { + final Date date = pigeon_instance.getValidNotBeforeDate(); + if (date != null) { + return date.getTime(); + } + return null; + } + + @Nullable + @Override + public java.security.cert.X509Certificate getX509Certificate( + @NonNull SslCertificate pigeon_instance) { + if (getPigeonRegistrar().sdkIsAtLeast(Build.VERSION_CODES.Q)) { + return pigeon_instance.getX509Certificate(); + } else { + Log.d( + "SslCertificateProxyApi", + getPigeonRegistrar() + .createUnsupportedVersionMessage( + "SslCertificate.getX509Certificate", "Build.VERSION_CODES.Q")); + return null; + } + } +} diff --git a/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/SslErrorHandlerProxyApi.java b/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/SslErrorHandlerProxyApi.java new file mode 100644 index 000000000000..8fec9f1a4eaf --- /dev/null +++ b/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/SslErrorHandlerProxyApi.java @@ -0,0 +1,29 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.webviewflutter; + +import android.webkit.SslErrorHandler; +import androidx.annotation.NonNull; + +/** + * ProxyApi implementation for {@link SslErrorHandler}. This class may handle instantiating native + * object instances that are attached to a Dart instance or handle method calls on the associated + * native class or an instance of that class. + */ +class SslErrorHandlerProxyApi extends PigeonApiSslErrorHandler { + SslErrorHandlerProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @Override + public void cancel(@NonNull SslErrorHandler pigeon_instance) { + pigeon_instance.cancel(); + } + + @Override + public void proceed(@NonNull SslErrorHandler pigeon_instance) { + pigeon_instance.proceed(); + } +} diff --git a/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/SslErrorProxyApi.java b/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/SslErrorProxyApi.java new file mode 100644 index 000000000000..1f26c110b84e --- /dev/null +++ b/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/SslErrorProxyApi.java @@ -0,0 +1,86 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.webviewflutter; + +import android.net.http.SslError; +import androidx.annotation.NonNull; + +/** + * ProxyApi implementation for {@link SslError}. This class may handle instantiating native object + * instances that are attached to a Dart instance or handle method calls on the associated native + * class or an instance of that class. + */ +class SslErrorProxyApi extends PigeonApiSslError { + SslErrorProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public ProxyApiRegistrar getPigeonRegistrar() { + return (ProxyApiRegistrar) super.getPigeonRegistrar(); + } + + @NonNull + @Override + public android.net.http.SslCertificate certificate(@NonNull SslError pigeon_instance) { + return pigeon_instance.getCertificate(); + } + + @NonNull + @Override + public String url(@NonNull SslError pigeon_instance) { + return pigeon_instance.getUrl(); + } + + @NonNull + @Override + public SslErrorType getPrimaryError(@NonNull SslError pigeon_instance) { + switch (pigeon_instance.getPrimaryError()) { + case SslError.SSL_DATE_INVALID: + return SslErrorType.DATE_INVALID; + case SslError.SSL_EXPIRED: + return SslErrorType.EXPIRED; + case SslError.SSL_IDMISMATCH: + return SslErrorType.ID_MISMATCH; + case SslError.SSL_INVALID: + return SslErrorType.INVALID; + case SslError.SSL_NOTYETVALID: + return SslErrorType.NOT_YET_VALID; + case SslError.SSL_UNTRUSTED: + return SslErrorType.UNTRUSTED; + default: + return SslErrorType.UNKNOWN; + } + } + + @Override + public boolean hasError(@NonNull SslError pigeon_instance, @NonNull SslErrorType error) { + int nativeError = -1; + switch (error) { + case DATE_INVALID: + nativeError = SslError.SSL_DATE_INVALID; + break; + case EXPIRED: + nativeError = SslError.SSL_EXPIRED; + break; + case ID_MISMATCH: + nativeError = SslError.SSL_IDMISMATCH; + break; + case INVALID: + nativeError = SslError.SSL_INVALID; + break; + case NOT_YET_VALID: + nativeError = SslError.SSL_NOTYETVALID; + break; + case UNTRUSTED: + nativeError = SslError.SSL_UNTRUSTED; + break; + case UNKNOWN: + throw getPigeonRegistrar().createUnknownEnumException(error); + } + return pigeon_instance.hasError(nativeError); + } +} diff --git a/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebViewClientProxyApi.java b/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebViewClientProxyApi.java index ca456528a919..d5fd065ac86b 100644 --- a/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebViewClientProxyApi.java +++ b/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebViewClientProxyApi.java @@ -14,6 +14,7 @@ import android.webkit.WebView; import android.webkit.WebViewClient; import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.webkit.WebResourceErrorCompat; import androidx.webkit.WebViewClientCompat; @@ -125,6 +126,63 @@ public void onReceivedHttpAuthRequest( () -> api.onReceivedHttpAuthRequest(this, view, handler, host, realm, reply -> null)); } + @Override + public void onFormResubmission( + @NonNull android.webkit.WebView view, + @NonNull android.os.Message dontResend, + @NonNull android.os.Message resend) { + api.getPigeonRegistrar() + .runOnMainThread( + () -> api.onFormResubmission(this, view, dontResend, resend, reply -> null)); + } + + @Override + public void onLoadResource(@NonNull android.webkit.WebView view, @NonNull String url) { + api.getPigeonRegistrar() + .runOnMainThread(() -> api.onLoadResource(this, view, url, reply -> null)); + } + + @Override + public void onPageCommitVisible(@NonNull android.webkit.WebView view, @NonNull String url) { + api.getPigeonRegistrar() + .runOnMainThread(() -> api.onPageCommitVisible(this, view, url, reply -> null)); + } + + @Override + public void onReceivedClientCertRequest( + @NonNull android.webkit.WebView view, @NonNull android.webkit.ClientCertRequest request) { + api.getPigeonRegistrar() + .runOnMainThread( + () -> api.onReceivedClientCertRequest(this, view, request, reply -> null)); + } + + @Override + public void onReceivedLoginRequest( + @NonNull android.webkit.WebView view, + @NonNull String realm, + @Nullable String account, + @NonNull String args) { + api.getPigeonRegistrar() + .runOnMainThread( + () -> api.onReceivedLoginRequest(this, view, realm, account, args, reply -> null)); + } + + @Override + public void onReceivedSslError( + @NonNull android.webkit.WebView view, + @NonNull android.webkit.SslErrorHandler handler, + @NonNull android.net.http.SslError error) { + api.getPigeonRegistrar() + .runOnMainThread(() -> api.onReceivedSslError(this, view, handler, error, reply -> null)); + } + + @Override + public void onScaleChanged( + @NonNull android.webkit.WebView view, float oldScale, float newScale) { + api.getPigeonRegistrar() + .runOnMainThread(() -> api.onScaleChanged(this, view, oldScale, newScale, reply -> null)); + } + @Override public void onUnhandledKeyEvent(@NonNull WebView view, @NonNull KeyEvent event) { // Deliberately empty. Occasionally the webview will mark events as having failed to be @@ -236,6 +294,63 @@ public void onReceivedHttpAuthRequest( () -> api.onReceivedHttpAuthRequest(this, view, handler, host, realm, reply -> null)); } + @Override + public void onFormResubmission( + @NonNull android.webkit.WebView view, + @NonNull android.os.Message dontResend, + @NonNull android.os.Message resend) { + api.getPigeonRegistrar() + .runOnMainThread( + () -> api.onFormResubmission(this, view, dontResend, resend, reply -> null)); + } + + @Override + public void onLoadResource(@NonNull android.webkit.WebView view, @NonNull String url) { + api.getPigeonRegistrar() + .runOnMainThread(() -> api.onLoadResource(this, view, url, reply -> null)); + } + + @Override + public void onPageCommitVisible(@NonNull android.webkit.WebView view, @NonNull String url) { + api.getPigeonRegistrar() + .runOnMainThread(() -> api.onPageCommitVisible(this, view, url, reply -> null)); + } + + @Override + public void onReceivedClientCertRequest( + @NonNull android.webkit.WebView view, @NonNull android.webkit.ClientCertRequest request) { + api.getPigeonRegistrar() + .runOnMainThread( + () -> api.onReceivedClientCertRequest(this, view, request, reply -> null)); + } + + @Override + public void onReceivedLoginRequest( + @NonNull android.webkit.WebView view, + @NonNull String realm, + @Nullable String account, + @NonNull String args) { + api.getPigeonRegistrar() + .runOnMainThread( + () -> api.onReceivedLoginRequest(this, view, realm, account, args, reply -> null)); + } + + @Override + public void onReceivedSslError( + @NonNull android.webkit.WebView view, + @NonNull android.webkit.SslErrorHandler handler, + @NonNull android.net.http.SslError error) { + api.getPigeonRegistrar() + .runOnMainThread(() -> api.onReceivedSslError(this, view, handler, error, reply -> null)); + } + + @Override + public void onScaleChanged( + @NonNull android.webkit.WebView view, float oldScale, float newScale) { + api.getPigeonRegistrar() + .runOnMainThread(() -> api.onScaleChanged(this, view, oldScale, newScale, reply -> null)); + } + @Override public void onUnhandledKeyEvent(@NonNull WebView view, @NonNull KeyEvent event) { // Deliberately empty. Occasionally the webview will mark events as having failed to be diff --git a/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/ClientCertRequestProxyApiTest.java b/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/ClientCertRequestProxyApiTest.java new file mode 100644 index 000000000000..37a816539fd7 --- /dev/null +++ b/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/ClientCertRequestProxyApiTest.java @@ -0,0 +1,53 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.webviewflutter; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import android.webkit.ClientCertRequest; +import java.security.PrivateKey; +import java.security.cert.X509Certificate; +import java.util.Collections; +import java.util.List; +import org.junit.Test; + +public class ClientCertRequestProxyApiTest { + @Test + public void cancel() { + final PigeonApiClientCertRequest api = + new TestProxyApiRegistrar().getPigeonApiClientCertRequest(); + + final ClientCertRequest instance = mock(ClientCertRequest.class); + api.cancel(instance); + + verify(instance).cancel(); + } + + @Test + public void ignore() { + final PigeonApiClientCertRequest api = + new TestProxyApiRegistrar().getPigeonApiClientCertRequest(); + + final ClientCertRequest instance = mock(ClientCertRequest.class); + api.ignore(instance); + + verify(instance).ignore(); + } + + @Test + public void proceed() { + final PigeonApiClientCertRequest api = + new TestProxyApiRegistrar().getPigeonApiClientCertRequest(); + + final ClientCertRequest instance = mock(ClientCertRequest.class); + final java.security.PrivateKey privateKey = mock(PrivateKey.class); + final X509Certificate cert = mock(X509Certificate.class); + final List chain = Collections.singletonList(cert); + api.proceed(instance, privateKey, chain); + + verify(instance).proceed(privateKey, new X509Certificate[] {cert}); + } +} diff --git a/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/MessageTest.java b/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/MessageTest.java new file mode 100644 index 000000000000..295f052e1bcb --- /dev/null +++ b/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/MessageTest.java @@ -0,0 +1,23 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.webviewflutter; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import android.os.Message; +import org.junit.Test; + +public class MessageTest { + @Test + public void sendToTarget() { + final PigeonApiAndroidMessage api = new TestProxyApiRegistrar().getPigeonApiAndroidMessage(); + + final Message instance = mock(Message.class); + api.sendToTarget(instance); + + verify(instance).sendToTarget(); + } +} diff --git a/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/SslCertificateDNameProxyApiTest.java b/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/SslCertificateDNameProxyApiTest.java new file mode 100644 index 000000000000..51477e7765ee --- /dev/null +++ b/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/SslCertificateDNameProxyApiTest.java @@ -0,0 +1,62 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.webviewflutter; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import android.net.http.SslCertificate; +import org.junit.Test; + +public class SslCertificateDNameProxyApiTest { + @Test + public void getCName() { + final PigeonApiSslCertificateDName api = + new TestProxyApiRegistrar().getPigeonApiSslCertificateDName(); + + final SslCertificate.DName instance = mock(SslCertificate.DName.class); + final String value = "myString"; + when(instance.getCName()).thenReturn(value); + + assertEquals(value, api.getCName(instance)); + } + + @Test + public void getDName() { + final PigeonApiSslCertificateDName api = + new TestProxyApiRegistrar().getPigeonApiSslCertificateDName(); + + final SslCertificate.DName instance = mock(SslCertificate.DName.class); + final String value = "myString"; + when(instance.getDName()).thenReturn(value); + + assertEquals(value, api.getDName(instance)); + } + + @Test + public void getOName() { + final PigeonApiSslCertificateDName api = + new TestProxyApiRegistrar().getPigeonApiSslCertificateDName(); + + final SslCertificate.DName instance = mock(SslCertificate.DName.class); + final String value = "myString"; + when(instance.getOName()).thenReturn(value); + + assertEquals(value, api.getOName(instance)); + } + + @Test + public void getUName() { + final PigeonApiSslCertificateDName api = + new TestProxyApiRegistrar().getPigeonApiSslCertificateDName(); + + final SslCertificate.DName instance = mock(SslCertificate.DName.class); + final String value = "myString"; + when(instance.getUName()).thenReturn(value); + + assertEquals(value, api.getUName(instance)); + } +} diff --git a/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/SslCertificateProxyApiTest.java b/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/SslCertificateProxyApiTest.java new file mode 100644 index 000000000000..0b9f8999a2d4 --- /dev/null +++ b/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/SslCertificateProxyApiTest.java @@ -0,0 +1,71 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.webviewflutter; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import android.net.http.SslCertificate; +import java.security.cert.X509Certificate; +import java.util.Date; +import org.junit.Test; + +public class SslCertificateProxyApiTest { + @Test + public void getIssuedBy() { + final PigeonApiSslCertificate api = new TestProxyApiRegistrar().getPigeonApiSslCertificate(); + + final SslCertificate instance = mock(SslCertificate.class); + final android.net.http.SslCertificate.DName value = mock(SslCertificate.DName.class); + when(instance.getIssuedBy()).thenReturn(value); + + assertEquals(value, api.getIssuedBy(instance)); + } + + @Test + public void getIssuedTo() { + final PigeonApiSslCertificate api = new TestProxyApiRegistrar().getPigeonApiSslCertificate(); + + final SslCertificate instance = mock(SslCertificate.class); + final android.net.http.SslCertificate.DName value = mock(SslCertificate.DName.class); + when(instance.getIssuedTo()).thenReturn(value); + + assertEquals(value, api.getIssuedTo(instance)); + } + + @Test + public void getValidNotAfterMsSinceEpoch() { + final PigeonApiSslCertificate api = new TestProxyApiRegistrar().getPigeonApiSslCertificate(); + + final SslCertificate instance = mock(SslCertificate.class); + final Date value = new Date(1000); + when(instance.getValidNotAfterDate()).thenReturn(value); + + assertEquals(value.getTime(), (long) api.getValidNotAfterMsSinceEpoch(instance)); + } + + @Test + public void getValidNotBeforeMsSinceEpoch() { + final PigeonApiSslCertificate api = new TestProxyApiRegistrar().getPigeonApiSslCertificate(); + + final SslCertificate instance = mock(SslCertificate.class); + final Date value = new Date(1000); + when(instance.getValidNotBeforeDate()).thenReturn(value); + + assertEquals(value.getTime(), (long) api.getValidNotBeforeMsSinceEpoch(instance)); + } + + @Test + public void getX509Certificate() { + final PigeonApiSslCertificate api = new TestProxyApiRegistrar().getPigeonApiSslCertificate(); + + final SslCertificate instance = mock(SslCertificate.class); + final java.security.cert.X509Certificate value = mock(X509Certificate.class); + when(instance.getX509Certificate()).thenReturn(value); + + assertEquals(value, api.getX509Certificate(instance)); + } +} diff --git a/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/SslErrorHandlerProxyApiTest.java b/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/SslErrorHandlerProxyApiTest.java new file mode 100644 index 000000000000..f308a9682eca --- /dev/null +++ b/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/SslErrorHandlerProxyApiTest.java @@ -0,0 +1,33 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.webviewflutter; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import android.webkit.SslErrorHandler; +import org.junit.Test; + +public class SslErrorHandlerProxyApiTest { + @Test + public void cancel() { + final PigeonApiSslErrorHandler api = new TestProxyApiRegistrar().getPigeonApiSslErrorHandler(); + + final SslErrorHandler instance = mock(SslErrorHandler.class); + api.cancel(instance); + + verify(instance).cancel(); + } + + @Test + public void proceed() { + final PigeonApiSslErrorHandler api = new TestProxyApiRegistrar().getPigeonApiSslErrorHandler(); + + final SslErrorHandler instance = mock(SslErrorHandler.class); + api.proceed(instance); + + verify(instance).proceed(); + } +} diff --git a/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/SslErrorProxyApiTest.java b/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/SslErrorProxyApiTest.java new file mode 100644 index 000000000000..6ce875461320 --- /dev/null +++ b/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/SslErrorProxyApiTest.java @@ -0,0 +1,60 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.webviewflutter; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import android.net.http.SslCertificate; +import android.net.http.SslError; +import org.junit.Test; + +public class SslErrorProxyApiTest { + @Test + public void certificate() { + final PigeonApiSslError api = new TestProxyApiRegistrar().getPigeonApiSslError(); + + final SslError instance = mock(SslError.class); + final android.net.http.SslCertificate value = mock(SslCertificate.class); + when(instance.getCertificate()).thenReturn(value); + + assertEquals(value, api.certificate(instance)); + } + + @Test + public void url() { + final PigeonApiSslError api = new TestProxyApiRegistrar().getPigeonApiSslError(); + + final SslError instance = mock(SslError.class); + final String value = "myString"; + when(instance.getUrl()).thenReturn(value); + + assertEquals(value, api.url(instance)); + } + + @Test + public void getPrimaryError() { + final PigeonApiSslError api = new TestProxyApiRegistrar().getPigeonApiSslError(); + + final SslError instance = mock(SslError.class); + final SslErrorType value = io.flutter.plugins.webviewflutter.SslErrorType.DATE_INVALID; + when(instance.getPrimaryError()).thenReturn(SslError.SSL_DATE_INVALID); + + assertEquals(value, api.getPrimaryError(instance)); + } + + @Test + public void hasError() { + final PigeonApiSslError api = new TestProxyApiRegistrar().getPigeonApiSslError(); + + final SslError instance = mock(SslError.class); + final SslErrorType error = io.flutter.plugins.webviewflutter.SslErrorType.DATE_INVALID; + final Boolean value = true; + when(instance.hasError(SslError.SSL_DATE_INVALID)).thenReturn(value); + + assertEquals(value, api.hasError(instance, error)); + } +} diff --git a/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebViewClientCompatTest.java b/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebViewClientCompatTest.java index 6c9bf1c7effa..07c1bd41f00d 100644 --- a/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebViewClientCompatTest.java +++ b/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebViewClientCompatTest.java @@ -12,7 +12,11 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import android.net.http.SslError; +import android.os.Message; +import android.webkit.ClientCertRequest; import android.webkit.HttpAuthHandler; +import android.webkit.SslErrorHandler; import android.webkit.WebResourceRequest; import android.webkit.WebView; import org.junit.Test; @@ -158,4 +162,110 @@ public void onReceivedHttpError() { .onReceivedHttpAuthRequest( eq(instance), eq(webView), eq(handler), eq(host), eq(realm), any()); } + + @Test + public void onFormResubmission() { + final WebViewClientProxyApi mockApi = mock(WebViewClientProxyApi.class); + when(mockApi.getPigeonRegistrar()).thenReturn(new TestProxyApiRegistrar()); + + final WebViewClientProxyApi.WebViewClientImpl instance = + new WebViewClientProxyApi.WebViewClientImpl(mockApi); + final android.webkit.WebView view = mock(WebView.class); + final android.os.Message dontResend = mock(Message.class); + final android.os.Message resend = mock(Message.class); + instance.onFormResubmission(view, dontResend, resend); + + verify(mockApi).onFormResubmission(eq(instance), eq(view), eq(dontResend), eq(resend), any()); + } + + @Test + public void onLoadResource() { + final WebViewClientProxyApi mockApi = mock(WebViewClientProxyApi.class); + when(mockApi.getPigeonRegistrar()).thenReturn(new TestProxyApiRegistrar()); + + final WebViewClientProxyApi.WebViewClientImpl instance = + new WebViewClientProxyApi.WebViewClientImpl(mockApi); + final android.webkit.WebView view = mock(WebView.class); + final String url = "myString"; + instance.onLoadResource(view, url); + + verify(mockApi).onLoadResource(eq(instance), eq(view), eq(url), any()); + } + + @Test + public void onPageCommitVisible() { + final WebViewClientProxyApi mockApi = mock(WebViewClientProxyApi.class); + when(mockApi.getPigeonRegistrar()).thenReturn(new TestProxyApiRegistrar()); + + final WebViewClientProxyApi.WebViewClientImpl instance = + new WebViewClientProxyApi.WebViewClientImpl(mockApi); + final android.webkit.WebView view = mock(WebView.class); + final String url = "myString"; + instance.onPageCommitVisible(view, url); + + verify(mockApi).onPageCommitVisible(eq(instance), eq(view), eq(url), any()); + } + + @Test + public void onReceivedClientCertRequest() { + final WebViewClientProxyApi mockApi = mock(WebViewClientProxyApi.class); + when(mockApi.getPigeonRegistrar()).thenReturn(new TestProxyApiRegistrar()); + + final WebViewClientProxyApi.WebViewClientImpl instance = + new WebViewClientProxyApi.WebViewClientImpl(mockApi); + final android.webkit.WebView view = mock(WebView.class); + final android.webkit.ClientCertRequest request = mock(ClientCertRequest.class); + instance.onReceivedClientCertRequest(view, request); + + verify(mockApi).onReceivedClientCertRequest(eq(instance), eq(view), eq(request), any()); + } + + @Test + public void onReceivedLoginRequest() { + final WebViewClientProxyApi mockApi = mock(WebViewClientProxyApi.class); + when(mockApi.getPigeonRegistrar()).thenReturn(new TestProxyApiRegistrar()); + + final WebViewClientProxyApi.WebViewClientImpl instance = + new WebViewClientProxyApi.WebViewClientImpl(mockApi); + final android.webkit.WebView view = mock(WebView.class); + final String realm = "myString"; + final String account = "myString1"; + final String args = "myString2"; + instance.onReceivedLoginRequest(view, realm, account, args); + + verify(mockApi) + .onReceivedLoginRequest(eq(instance), eq(view), eq(realm), eq(account), eq(args), any()); + } + + @Test + public void onReceivedSslError() { + final WebViewClientProxyApi mockApi = mock(WebViewClientProxyApi.class); + when(mockApi.getPigeonRegistrar()).thenReturn(new TestProxyApiRegistrar()); + + final WebViewClientProxyApi.WebViewClientImpl instance = + new WebViewClientProxyApi.WebViewClientImpl(mockApi); + final android.webkit.WebView view = mock(WebView.class); + final android.webkit.SslErrorHandler handler = mock(SslErrorHandler.class); + final android.net.http.SslError error = mock(SslError.class); + instance.onReceivedSslError(view, handler, error); + + verify(mockApi).onReceivedSslError(eq(instance), eq(view), eq(handler), eq(error), any()); + } + + @Test + public void onScaleChanged() { + final WebViewClientProxyApi mockApi = mock(WebViewClientProxyApi.class); + when(mockApi.getPigeonRegistrar()).thenReturn(new TestProxyApiRegistrar()); + + final WebViewClientProxyApi.WebViewClientImpl instance = + new WebViewClientProxyApi.WebViewClientImpl(mockApi); + final android.webkit.WebView view = mock(WebView.class); + final float oldScale = 1.0f; + final float newScale = 2.0f; + instance.onScaleChanged(view, oldScale, newScale); + + verify(mockApi) + .onScaleChanged( + eq(instance), eq(view), eq((double) oldScale), eq((double) newScale), any()); + } } diff --git a/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebViewClientTest.java b/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebViewClientTest.java index 015bf46705de..9f8bb4ea2957 100644 --- a/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebViewClientTest.java +++ b/packages/webview_flutter/webview_flutter_android/android/src/test/java/io/flutter/plugins/webviewflutter/WebViewClientTest.java @@ -12,7 +12,11 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import android.net.http.SslError; +import android.os.Message; +import android.webkit.ClientCertRequest; import android.webkit.HttpAuthHandler; +import android.webkit.SslErrorHandler; import android.webkit.WebResourceRequest; import android.webkit.WebView; import io.flutter.plugins.webviewflutter.WebViewClientProxyApi.WebViewClientImpl; @@ -148,4 +152,103 @@ public void onReceivedHttpError() { .onReceivedHttpAuthRequest( eq(instance), eq(webView), eq(handler), eq(host), eq(realm), any()); } + + @Test + public void onFormResubmission() { + final WebViewClientProxyApi mockApi = mock(WebViewClientProxyApi.class); + when(mockApi.getPigeonRegistrar()).thenReturn(new TestProxyApiRegistrar()); + + final WebViewClientImpl instance = new WebViewClientImpl(mockApi); + final android.webkit.WebView view = mock(WebView.class); + final android.os.Message dontResend = mock(Message.class); + final android.os.Message resend = mock(Message.class); + instance.onFormResubmission(view, dontResend, resend); + + verify(mockApi).onFormResubmission(eq(instance), eq(view), eq(dontResend), eq(resend), any()); + } + + @Test + public void onLoadResource() { + final WebViewClientProxyApi mockApi = mock(WebViewClientProxyApi.class); + when(mockApi.getPigeonRegistrar()).thenReturn(new TestProxyApiRegistrar()); + + final WebViewClientImpl instance = new WebViewClientImpl(mockApi); + final android.webkit.WebView view = mock(WebView.class); + final String url = "myString"; + instance.onLoadResource(view, url); + + verify(mockApi).onLoadResource(eq(instance), eq(view), eq(url), any()); + } + + @Test + public void onPageCommitVisible() { + final WebViewClientProxyApi mockApi = mock(WebViewClientProxyApi.class); + when(mockApi.getPigeonRegistrar()).thenReturn(new TestProxyApiRegistrar()); + + final WebViewClientImpl instance = new WebViewClientImpl(mockApi); + final android.webkit.WebView view = mock(WebView.class); + final String url = "myString"; + instance.onPageCommitVisible(view, url); + + verify(mockApi).onPageCommitVisible(eq(instance), eq(view), eq(url), any()); + } + + @Test + public void onReceivedClientCertRequest() { + final WebViewClientProxyApi mockApi = mock(WebViewClientProxyApi.class); + when(mockApi.getPigeonRegistrar()).thenReturn(new TestProxyApiRegistrar()); + + final WebViewClientImpl instance = new WebViewClientImpl(mockApi); + final android.webkit.WebView view = mock(WebView.class); + final android.webkit.ClientCertRequest request = mock(ClientCertRequest.class); + instance.onReceivedClientCertRequest(view, request); + + verify(mockApi).onReceivedClientCertRequest(eq(instance), eq(view), eq(request), any()); + } + + @Test + public void onReceivedLoginRequest() { + final WebViewClientProxyApi mockApi = mock(WebViewClientProxyApi.class); + when(mockApi.getPigeonRegistrar()).thenReturn(new TestProxyApiRegistrar()); + + final WebViewClientImpl instance = new WebViewClientImpl(mockApi); + final android.webkit.WebView view = mock(WebView.class); + final String realm = "myString"; + final String account = "myString1"; + final String args = "myString2"; + instance.onReceivedLoginRequest(view, realm, account, args); + + verify(mockApi) + .onReceivedLoginRequest(eq(instance), eq(view), eq(realm), eq(account), eq(args), any()); + } + + @Test + public void onReceivedSslError() { + final WebViewClientProxyApi mockApi = mock(WebViewClientProxyApi.class); + when(mockApi.getPigeonRegistrar()).thenReturn(new TestProxyApiRegistrar()); + + final WebViewClientImpl instance = new WebViewClientImpl(mockApi); + final android.webkit.WebView view = mock(WebView.class); + final android.webkit.SslErrorHandler handler = mock(SslErrorHandler.class); + final android.net.http.SslError error = mock(SslError.class); + instance.onReceivedSslError(view, handler, error); + + verify(mockApi).onReceivedSslError(eq(instance), eq(view), eq(handler), eq(error), any()); + } + + @Test + public void onScaleChanged() { + final WebViewClientProxyApi mockApi = mock(WebViewClientProxyApi.class); + when(mockApi.getPigeonRegistrar()).thenReturn(new TestProxyApiRegistrar()); + + final WebViewClientImpl instance = new WebViewClientImpl(mockApi); + final android.webkit.WebView view = mock(WebView.class); + final float oldScale = 1.0f; + final float newScale = 2.0f; + instance.onScaleChanged(view, oldScale, newScale); + + verify(mockApi) + .onScaleChanged( + eq(instance), eq(view), eq((double) oldScale), eq((double) newScale), any()); + } } diff --git a/packages/webview_flutter/webview_flutter_android/example/android/app/build.gradle b/packages/webview_flutter/webview_flutter_android/example/android/app/build.gradle index 78de78e10f92..c8bf2055a3dc 100644 --- a/packages/webview_flutter/webview_flutter_android/example/android/app/build.gradle +++ b/packages/webview_flutter/webview_flutter_android/example/android/app/build.gradle @@ -25,7 +25,7 @@ if (flutterVersionName == null) { android { namespace 'io.flutter.plugins.webviewflutterexample' compileSdk = flutter.compileSdkVersion - + ndkVersion = flutter.ndkVersion defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). @@ -37,6 +37,15 @@ android { testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } + compileOptions { + sourceCompatibility JavaVersion.VERSION_11 + targetCompatibility JavaVersion.VERSION_11 + } + + kotlinOptions { + jvmTarget = '11' + } + buildTypes { release { // TODO: Add your own signing config for the release build. diff --git a/packages/webview_flutter/webview_flutter_android/lib/src/android_proxy.dart b/packages/webview_flutter/webview_flutter_android/lib/src/android_proxy.dart index ccb9dc77f508..e32520c358bf 100644 --- a/packages/webview_flutter/webview_flutter_android/lib/src/android_proxy.dart +++ b/packages/webview_flutter/webview_flutter_android/lib/src/android_proxy.dart @@ -73,6 +73,46 @@ class AndroidWebViewProxy { void Function(WebViewClient, WebView, String, bool)? doUpdateVisitedHistory, void Function(WebViewClient, WebView, HttpAuthHandler, String, String)? onReceivedHttpAuthRequest, + void Function( + WebViewClient, + WebView, + AndroidMessage, + AndroidMessage, + )? onFormResubmission, + void Function( + WebViewClient, + WebView, + String, + )? onLoadResource, + void Function( + WebViewClient, + WebView, + String, + )? onPageCommitVisible, + void Function( + WebViewClient, + WebView, + ClientCertRequest, + )? onReceivedClientCertRequest, + void Function( + WebViewClient, + WebView, + String, + String?, + String, + )? onReceivedLoginRequest, + void Function( + WebViewClient, + WebView, + SslErrorHandler, + SslError, + )? onReceivedSslError, + void Function( + WebViewClient, + WebView, + double, + double, + )? onScaleChanged, }) newWebViewClient; /// Constructs [DownloadListener]. @@ -85,11 +125,11 @@ class AndroidWebViewProxy { /// Constructs [WebChromeClient]. final WebChromeClient Function({ void Function(WebChromeClient, WebView, int)? onProgressChanged, - Future> Function( + required Future> Function( WebChromeClient, WebView, FileChooserParams, - )? onShowFileChooser, + ) onShowFileChooser, void Function(WebChromeClient, PermissionRequest)? onPermissionRequest, void Function(WebChromeClient, View, CustomViewCallback)? onShowCustomView, void Function(WebChromeClient)? onHideCustomView, @@ -101,12 +141,12 @@ class AndroidWebViewProxy { void Function(WebChromeClient)? onGeolocationPermissionsHidePrompt, void Function(WebChromeClient, ConsoleMessage)? onConsoleMessage, Future Function(WebChromeClient, WebView, String, String)? onJsAlert, - Future Function( + required Future Function( WebChromeClient, WebView, String, String, - )? onJsConfirm, + ) onJsConfirm, Future Function( WebChromeClient, WebView, diff --git a/packages/webview_flutter/webview_flutter_android/lib/src/android_webkit.g.dart b/packages/webview_flutter/webview_flutter_android/lib/src/android_webkit.g.dart index 3ae3a187867c..f67bae562add 100644 --- a/packages/webview_flutter/webview_flutter_android/lib/src/android_webkit.g.dart +++ b/packages/webview_flutter/webview_flutter_android/lib/src/android_webkit.g.dart @@ -1,7 +1,7 @@ // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// Autogenerated from Pigeon (v22.5.0), do not edit directly. +// Autogenerated from Pigeon (v25.3.0), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import, no_leading_underscores_for_local_identifiers @@ -53,7 +53,6 @@ abstract class PigeonInternalProxyApiBaseClass { final BinaryMessenger? pigeon_binaryMessenger; /// Maintains instances stored to communicate with native language objects. - @protected final PigeonInstanceManager pigeon_instanceManager; /// Instantiates and returns a functionally identical object to oneself. @@ -179,6 +178,22 @@ class PigeonInstanceManager { pigeon_instanceManager: instanceManager); HttpAuthHandler.pigeon_setUpMessageHandlers( pigeon_instanceManager: instanceManager); + AndroidMessage.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + ClientCertRequest.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + PrivateKey.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + X509Certificate.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + SslErrorHandler.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + SslError.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + SslCertificateDName.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + SslCertificate.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); return instanceManager; } @@ -372,8 +387,10 @@ class _PigeonInternalInstanceManagerApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([identifier]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([identifier]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -399,8 +416,9 @@ class _PigeonInternalInstanceManagerApi { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); final List? pigeonVar_replyList = - await pigeonVar_channel.send(null) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -503,6 +521,32 @@ enum ConsoleMessageLevel { unknown, } +/// Type of error for a SslCertificate. +/// +/// See https://developer.android.com/reference/android/net/http/SslError#SSL_DATE_INVALID. +enum SslErrorType { + /// The date of the certificate is invalid. + dateInvalid, + + /// The certificate has expired. + expired, + + /// Hostname mismatch. + idMismatch, + + /// A generic error occurred. + invalid, + + /// The certificate is not yet valid. + notYetValid, + + /// The certificate authority is not trusted. + untrusted, + + /// The type is not recognized by this wrapper. + unknown, +} + class _PigeonCodec extends StandardMessageCodec { const _PigeonCodec(); @override @@ -516,6 +560,9 @@ class _PigeonCodec extends StandardMessageCodec { } else if (value is ConsoleMessageLevel) { buffer.putUint8(130); writeValue(buffer, value.index); + } else if (value is SslErrorType) { + buffer.putUint8(131); + writeValue(buffer, value.index); } else { super.writeValue(buffer, value); } @@ -530,6 +577,9 @@ class _PigeonCodec extends StandardMessageCodec { case 130: final int? value = readValue(buffer) as int?; return value == null ? null : ConsoleMessageLevel.values[value]; + case 131: + final int? value = readValue(buffer) as int?; + return value == null ? null : SslErrorType.values[value]; default: return super.readValueOfType(type, buffer); } @@ -1228,8 +1278,10 @@ class CookieManager extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([pigeonVar_instanceIdentifier]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([pigeonVar_instanceIdentifier]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1261,8 +1313,10 @@ class CookieManager extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, url, value]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, url, value]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1289,8 +1343,10 @@ class CookieManager extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1325,8 +1381,10 @@ class CookieManager extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, webView, accept]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, webView, accept]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1363,17 +1421,19 @@ class WebView extends View { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecWebView; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_android.WebView.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { - const String pigeonVar_channelName = - 'dev.flutter.pigeon.webview_flutter_android.WebView.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([pigeonVar_instanceIdentifier]) as List?; + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1555,9 +1615,10 @@ class WebView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, pigeonVar_instanceIdentifier]) - as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, pigeonVar_instanceIdentifier]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1590,8 +1651,10 @@ class WebView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, data, mimeType, encoding]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, data, mimeType, encoding]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1625,9 +1688,10 @@ class WebView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel.send( - [this, baseUrl, data, mimeType, encoding, historyUrl]) - as List?; + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([this, baseUrl, data, mimeType, encoding, historyUrl]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1657,8 +1721,10 @@ class WebView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, url, headers]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, url, headers]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1688,8 +1754,10 @@ class WebView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, url, data]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, url, data]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1716,8 +1784,10 @@ class WebView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1744,8 +1814,10 @@ class WebView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1777,8 +1849,10 @@ class WebView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1810,8 +1884,10 @@ class WebView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1838,8 +1914,10 @@ class WebView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1866,8 +1944,10 @@ class WebView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1894,8 +1974,10 @@ class WebView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, includeDiskFiles]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, includeDiskFiles]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1923,8 +2005,10 @@ class WebView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, javascriptString]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, javascriptString]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1951,8 +2035,10 @@ class WebView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1985,8 +2071,10 @@ class WebView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([enabled]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([enabled]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2014,8 +2102,10 @@ class WebView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, client]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this, client]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2042,8 +2132,10 @@ class WebView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, channel]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, channel]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2070,8 +2162,10 @@ class WebView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, name]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this, name]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2099,8 +2193,10 @@ class WebView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, listener]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, listener]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2127,8 +2223,10 @@ class WebView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, client]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this, client]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2155,8 +2253,10 @@ class WebView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, color]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this, color]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2183,8 +2283,10 @@ class WebView extends View { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2287,8 +2389,10 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, flag]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this, flag]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2315,8 +2419,10 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, flag]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this, flag]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2343,8 +2449,10 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, support]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, support]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2371,8 +2479,10 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, flag]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this, flag]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2399,8 +2509,10 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, userAgentString]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, userAgentString]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2427,8 +2539,10 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, require]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, require]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2456,8 +2570,10 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, support]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, support]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2485,8 +2601,10 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, overview]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, overview]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2514,8 +2632,10 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, use]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this, use]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2543,8 +2663,10 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, enabled]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, enabled]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2572,8 +2694,10 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, enabled]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, enabled]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2600,8 +2724,10 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, enabled]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, enabled]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2628,8 +2754,10 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, enabled]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, enabled]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2656,8 +2784,10 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, enabled]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, enabled]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2684,8 +2814,10 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, textZoom]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, textZoom]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2712,8 +2844,10 @@ class WebSettings extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2757,18 +2891,19 @@ class JavaScriptChannel extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecJavaScriptChannel; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_android.JavaScriptChannel.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([pigeonVar_instanceIdentifier, channelName]); () async { - const String pigeonVar_channelName = - 'dev.flutter.pigeon.webview_flutter_android.JavaScriptChannel.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([pigeonVar_instanceIdentifier, channelName]) - as List?; + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2902,23 +3037,32 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { this.urlLoading, this.doUpdateVisitedHistory, this.onReceivedHttpAuthRequest, + this.onFormResubmission, + this.onLoadResource, + this.onPageCommitVisible, + this.onReceivedClientCertRequest, + this.onReceivedLoginRequest, + this.onReceivedSslError, + this.onScaleChanged, }) { final int pigeonVar_instanceIdentifier = pigeon_instanceManager.addDartCreatedInstance(this); final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecWebViewClient; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { - const String pigeonVar_channelName = - 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([pigeonVar_instanceIdentifier]) as List?; + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2951,6 +3095,13 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { this.urlLoading, this.doUpdateVisitedHistory, this.onReceivedHttpAuthRequest, + this.onFormResubmission, + this.onLoadResource, + this.onPageCommitVisible, + this.onReceivedClientCertRequest, + this.onReceivedLoginRequest, + this.onReceivedSslError, + this.onScaleChanged, }); late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecWebViewClient = @@ -3218,6 +3369,192 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { String realm, )? onReceivedHttpAuthRequest; + /// Ask the host application if the browser should resend data as the + /// requested page was a result of a POST. + /// + /// For the associated Native object to be automatically garbage collected, + /// it is required that the implementation of this `Function` doesn't have a + /// strong reference to the encapsulating class instance. When this `Function` + /// references a non-local variable, it is strongly recommended to access it + /// with a `WeakReference`: + /// + /// ```dart + /// final WeakReference weakMyVariable = WeakReference(myVariable); + /// final WebViewClient instance = WebViewClient( + /// onFormResubmission: (WebViewClient pigeon_instance, ...) { + /// print(weakMyVariable?.target); + /// }, + /// ); + /// ``` + /// + /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to + /// release the associated Native object manually. + final void Function( + WebViewClient pigeon_instance, + WebView view, + AndroidMessage dontResend, + AndroidMessage resend, + )? onFormResubmission; + + /// Notify the host application that the WebView will load the resource + /// specified by the given url. + /// + /// For the associated Native object to be automatically garbage collected, + /// it is required that the implementation of this `Function` doesn't have a + /// strong reference to the encapsulating class instance. When this `Function` + /// references a non-local variable, it is strongly recommended to access it + /// with a `WeakReference`: + /// + /// ```dart + /// final WeakReference weakMyVariable = WeakReference(myVariable); + /// final WebViewClient instance = WebViewClient( + /// onLoadResource: (WebViewClient pigeon_instance, ...) { + /// print(weakMyVariable?.target); + /// }, + /// ); + /// ``` + /// + /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to + /// release the associated Native object manually. + final void Function( + WebViewClient pigeon_instance, + WebView view, + String url, + )? onLoadResource; + + /// Notify the host application that WebView content left over from previous + /// page navigations will no longer be drawn. + /// + /// For the associated Native object to be automatically garbage collected, + /// it is required that the implementation of this `Function` doesn't have a + /// strong reference to the encapsulating class instance. When this `Function` + /// references a non-local variable, it is strongly recommended to access it + /// with a `WeakReference`: + /// + /// ```dart + /// final WeakReference weakMyVariable = WeakReference(myVariable); + /// final WebViewClient instance = WebViewClient( + /// onPageCommitVisible: (WebViewClient pigeon_instance, ...) { + /// print(weakMyVariable?.target); + /// }, + /// ); + /// ``` + /// + /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to + /// release the associated Native object manually. + final void Function( + WebViewClient pigeon_instance, + WebView view, + String url, + )? onPageCommitVisible; + + /// Notify the host application to handle a SSL client certificate request. + /// + /// For the associated Native object to be automatically garbage collected, + /// it is required that the implementation of this `Function` doesn't have a + /// strong reference to the encapsulating class instance. When this `Function` + /// references a non-local variable, it is strongly recommended to access it + /// with a `WeakReference`: + /// + /// ```dart + /// final WeakReference weakMyVariable = WeakReference(myVariable); + /// final WebViewClient instance = WebViewClient( + /// onReceivedClientCertRequest: (WebViewClient pigeon_instance, ...) { + /// print(weakMyVariable?.target); + /// }, + /// ); + /// ``` + /// + /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to + /// release the associated Native object manually. + final void Function( + WebViewClient pigeon_instance, + WebView view, + ClientCertRequest request, + )? onReceivedClientCertRequest; + + /// Notify the host application that a request to automatically log in the + /// user has been processed. + /// + /// For the associated Native object to be automatically garbage collected, + /// it is required that the implementation of this `Function` doesn't have a + /// strong reference to the encapsulating class instance. When this `Function` + /// references a non-local variable, it is strongly recommended to access it + /// with a `WeakReference`: + /// + /// ```dart + /// final WeakReference weakMyVariable = WeakReference(myVariable); + /// final WebViewClient instance = WebViewClient( + /// onReceivedLoginRequest: (WebViewClient pigeon_instance, ...) { + /// print(weakMyVariable?.target); + /// }, + /// ); + /// ``` + /// + /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to + /// release the associated Native object manually. + final void Function( + WebViewClient pigeon_instance, + WebView view, + String realm, + String? account, + String args, + )? onReceivedLoginRequest; + + /// Notifies the host application that an SSL error occurred while loading a + /// resource. + /// + /// For the associated Native object to be automatically garbage collected, + /// it is required that the implementation of this `Function` doesn't have a + /// strong reference to the encapsulating class instance. When this `Function` + /// references a non-local variable, it is strongly recommended to access it + /// with a `WeakReference`: + /// + /// ```dart + /// final WeakReference weakMyVariable = WeakReference(myVariable); + /// final WebViewClient instance = WebViewClient( + /// onReceivedSslError: (WebViewClient pigeon_instance, ...) { + /// print(weakMyVariable?.target); + /// }, + /// ); + /// ``` + /// + /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to + /// release the associated Native object manually. + final void Function( + WebViewClient pigeon_instance, + WebView view, + SslErrorHandler handler, + SslError error, + )? onReceivedSslError; + + /// Notify the host application that the scale applied to the WebView has + /// changed. + /// + /// For the associated Native object to be automatically garbage collected, + /// it is required that the implementation of this `Function` doesn't have a + /// strong reference to the encapsulating class instance. When this `Function` + /// references a non-local variable, it is strongly recommended to access it + /// with a `WeakReference`: + /// + /// ```dart + /// final WeakReference weakMyVariable = WeakReference(myVariable); + /// final WebViewClient instance = WebViewClient( + /// onScaleChanged: (WebViewClient pigeon_instance, ...) { + /// print(weakMyVariable?.target); + /// }, + /// ); + /// ``` + /// + /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to + /// release the associated Native object manually. + final void Function( + WebViewClient pigeon_instance, + WebView view, + double oldScale, + double newScale, + )? onScaleChanged; + static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, @@ -3281,6 +3618,46 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { String host, String realm, )? onReceivedHttpAuthRequest, + void Function( + WebViewClient pigeon_instance, + WebView view, + AndroidMessage dontResend, + AndroidMessage resend, + )? onFormResubmission, + void Function( + WebViewClient pigeon_instance, + WebView view, + String url, + )? onLoadResource, + void Function( + WebViewClient pigeon_instance, + WebView view, + String url, + )? onPageCommitVisible, + void Function( + WebViewClient pigeon_instance, + WebView view, + ClientCertRequest request, + )? onReceivedClientCertRequest, + void Function( + WebViewClient pigeon_instance, + WebView view, + String realm, + String? account, + String args, + )? onReceivedLoginRequest, + void Function( + WebViewClient pigeon_instance, + WebView view, + SslErrorHandler handler, + SslError error, + )? onReceivedSslError, + void Function( + WebViewClient pigeon_instance, + WebView view, + double oldScale, + double newScale, + )? onScaleChanged, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _PigeonInternalProxyApiBaseCodec( @@ -3746,19 +4123,304 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { }); } } - } - /// Sets the required synchronous return value for the Java method, - /// `WebViewClient.shouldOverrideUrlLoading(...)`. - /// - /// The Java method, `WebViewClient.shouldOverrideUrlLoading(...)`, requires - /// a boolean to be returned and this method sets the returned value for all - /// calls to the Java method. - /// - /// Setting this to true causes the current [WebView] to abort loading any URL - /// received by [requestLoading] or [urlLoading], while setting this to false - /// causes the [WebView] to continue loading a URL as usual. - /// + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onFormResubmission', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onFormResubmission was null.'); + final List args = (message as List?)!; + final WebViewClient? arg_pigeon_instance = + (args[0] as WebViewClient?); + assert(arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onFormResubmission was null, expected non-null WebViewClient.'); + final WebView? arg_view = (args[1] as WebView?); + assert(arg_view != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onFormResubmission was null, expected non-null WebView.'); + final AndroidMessage? arg_dontResend = (args[2] as AndroidMessage?); + assert(arg_dontResend != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onFormResubmission was null, expected non-null AndroidMessage.'); + final AndroidMessage? arg_resend = (args[3] as AndroidMessage?); + assert(arg_resend != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onFormResubmission was null, expected non-null AndroidMessage.'); + try { + (onFormResubmission ?? arg_pigeon_instance!.onFormResubmission) + ?.call(arg_pigeon_instance!, arg_view!, arg_dontResend!, + arg_resend!); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onLoadResource', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onLoadResource was null.'); + final List args = (message as List?)!; + final WebViewClient? arg_pigeon_instance = + (args[0] as WebViewClient?); + assert(arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onLoadResource was null, expected non-null WebViewClient.'); + final WebView? arg_view = (args[1] as WebView?); + assert(arg_view != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onLoadResource was null, expected non-null WebView.'); + final String? arg_url = (args[2] as String?); + assert(arg_url != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onLoadResource was null, expected non-null String.'); + try { + (onLoadResource ?? arg_pigeon_instance!.onLoadResource) + ?.call(arg_pigeon_instance!, arg_view!, arg_url!); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageCommitVisible', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageCommitVisible was null.'); + final List args = (message as List?)!; + final WebViewClient? arg_pigeon_instance = + (args[0] as WebViewClient?); + assert(arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageCommitVisible was null, expected non-null WebViewClient.'); + final WebView? arg_view = (args[1] as WebView?); + assert(arg_view != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageCommitVisible was null, expected non-null WebView.'); + final String? arg_url = (args[2] as String?); + assert(arg_url != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onPageCommitVisible was null, expected non-null String.'); + try { + (onPageCommitVisible ?? arg_pigeon_instance!.onPageCommitVisible) + ?.call(arg_pigeon_instance!, arg_view!, arg_url!); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedClientCertRequest', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedClientCertRequest was null.'); + final List args = (message as List?)!; + final WebViewClient? arg_pigeon_instance = + (args[0] as WebViewClient?); + assert(arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedClientCertRequest was null, expected non-null WebViewClient.'); + final WebView? arg_view = (args[1] as WebView?); + assert(arg_view != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedClientCertRequest was null, expected non-null WebView.'); + final ClientCertRequest? arg_request = + (args[2] as ClientCertRequest?); + assert(arg_request != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedClientCertRequest was null, expected non-null ClientCertRequest.'); + try { + (onReceivedClientCertRequest ?? + arg_pigeon_instance!.onReceivedClientCertRequest) + ?.call(arg_pigeon_instance!, arg_view!, arg_request!); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedLoginRequest', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedLoginRequest was null.'); + final List args = (message as List?)!; + final WebViewClient? arg_pigeon_instance = + (args[0] as WebViewClient?); + assert(arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedLoginRequest was null, expected non-null WebViewClient.'); + final WebView? arg_view = (args[1] as WebView?); + assert(arg_view != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedLoginRequest was null, expected non-null WebView.'); + final String? arg_realm = (args[2] as String?); + assert(arg_realm != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedLoginRequest was null, expected non-null String.'); + final String? arg_account = (args[3] as String?); + final String? arg_args = (args[4] as String?); + assert(arg_args != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedLoginRequest was null, expected non-null String.'); + try { + (onReceivedLoginRequest ?? + arg_pigeon_instance!.onReceivedLoginRequest) + ?.call(arg_pigeon_instance!, arg_view!, arg_realm!, arg_account, + arg_args!); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedSslError', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedSslError was null.'); + final List args = (message as List?)!; + final WebViewClient? arg_pigeon_instance = + (args[0] as WebViewClient?); + assert(arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedSslError was null, expected non-null WebViewClient.'); + final WebView? arg_view = (args[1] as WebView?); + assert(arg_view != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedSslError was null, expected non-null WebView.'); + final SslErrorHandler? arg_handler = (args[2] as SslErrorHandler?); + assert(arg_handler != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedSslError was null, expected non-null SslErrorHandler.'); + final SslError? arg_error = (args[3] as SslError?); + assert(arg_error != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onReceivedSslError was null, expected non-null SslError.'); + try { + (onReceivedSslError ?? arg_pigeon_instance!.onReceivedSslError) + ?.call( + arg_pigeon_instance!, arg_view!, arg_handler!, arg_error!); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.webview_flutter_android.WebViewClient.onScaleChanged', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onScaleChanged was null.'); + final List args = (message as List?)!; + final WebViewClient? arg_pigeon_instance = + (args[0] as WebViewClient?); + assert(arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onScaleChanged was null, expected non-null WebViewClient.'); + final WebView? arg_view = (args[1] as WebView?); + assert(arg_view != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onScaleChanged was null, expected non-null WebView.'); + final double? arg_oldScale = (args[2] as double?); + assert(arg_oldScale != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onScaleChanged was null, expected non-null double.'); + final double? arg_newScale = (args[3] as double?); + assert(arg_newScale != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebViewClient.onScaleChanged was null, expected non-null double.'); + try { + (onScaleChanged ?? arg_pigeon_instance!.onScaleChanged)?.call( + arg_pigeon_instance!, arg_view!, arg_oldScale!, arg_newScale!); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } + + /// Sets the required synchronous return value for the Java method, + /// `WebViewClient.shouldOverrideUrlLoading(...)`. + /// + /// The Java method, `WebViewClient.shouldOverrideUrlLoading(...)`, requires + /// a boolean to be returned and this method sets the returned value for all + /// calls to the Java method. + /// + /// Setting this to true causes the current [WebView] to abort loading any URL + /// received by [requestLoading] or [urlLoading], while setting this to false + /// causes the [WebView] to continue loading a URL as usual. + /// /// Defaults to false. Future setSynchronousReturnValueForShouldOverrideUrlLoading( bool value) async { @@ -3773,8 +4435,10 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, value]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this, value]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -3803,6 +4467,13 @@ class WebViewClient extends PigeonInternalProxyApiBaseClass { urlLoading: urlLoading, doUpdateVisitedHistory: doUpdateVisitedHistory, onReceivedHttpAuthRequest: onReceivedHttpAuthRequest, + onFormResubmission: onFormResubmission, + onLoadResource: onLoadResource, + onPageCommitVisible: onPageCommitVisible, + onReceivedClientCertRequest: onReceivedClientCertRequest, + onReceivedLoginRequest: onReceivedLoginRequest, + onReceivedSslError: onReceivedSslError, + onScaleChanged: onScaleChanged, ); } } @@ -3821,17 +4492,19 @@ class DownloadListener extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecDownloadListener; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_android.DownloadListener.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { - const String pigeonVar_channelName = - 'dev.flutter.pigeon.webview_flutter_android.DownloadListener.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([pigeonVar_instanceIdentifier]) as List?; + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -3977,7 +4650,7 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { super.pigeon_binaryMessenger, super.pigeon_instanceManager, this.onProgressChanged, - this.onShowFileChooser, + required this.onShowFileChooser, this.onPermissionRequest, this.onShowCustomView, this.onHideCustomView, @@ -3985,7 +4658,7 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { this.onGeolocationPermissionsHidePrompt, this.onConsoleMessage, this.onJsAlert, - this.onJsConfirm, + required this.onJsConfirm, this.onJsPrompt, }) { final int pigeonVar_instanceIdentifier = @@ -3993,17 +4666,19 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecWebChromeClient; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([pigeonVar_instanceIdentifier]); () async { - const String pigeonVar_channelName = - 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([pigeonVar_instanceIdentifier]) as List?; + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -4027,7 +4702,7 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { super.pigeon_binaryMessenger, super.pigeon_instanceManager, this.onProgressChanged, - this.onShowFileChooser, + required this.onShowFileChooser, this.onPermissionRequest, this.onShowCustomView, this.onHideCustomView, @@ -4035,7 +4710,7 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { this.onGeolocationPermissionsHidePrompt, this.onConsoleMessage, this.onJsAlert, - this.onJsConfirm, + required this.onJsConfirm, this.onJsPrompt, }); @@ -4090,7 +4765,7 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { WebChromeClient pigeon_instance, WebView webView, FileChooserParams params, - )? onShowFileChooser; + ) onShowFileChooser; /// Notify the host application that web content is requesting permission to /// access the specified resources and the permission currently isn't granted @@ -4292,7 +4967,7 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { WebView webView, String url, String message, - )? onJsConfirm; + ) onJsConfirm; /// Notify the host application that the web page wants to display a /// JavaScript `prompt()` dialog. @@ -4326,7 +5001,6 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - WebChromeClient Function()? pigeon_newInstance, void Function( WebChromeClient pigeon_instance, WebView webView, @@ -4386,7 +5060,7 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { final BasicMessageChannel< Object?> pigeonVar_channel = BasicMessageChannel< Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.pigeon_newInstance', + 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onProgressChanged', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (pigeon_clearHandlers) { @@ -4394,45 +5068,7 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { } else { pigeonVar_channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.pigeon_newInstance was null.'); - final List args = (message as List?)!; - final int? arg_pigeon_instanceIdentifier = (args[0] as int?); - assert(arg_pigeon_instanceIdentifier != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.pigeon_newInstance was null, expected non-null int.'); - try { - (pigeon_instanceManager ?? PigeonInstanceManager.instance) - .addHostCreatedInstance( - pigeon_newInstance?.call() ?? - WebChromeClient.pigeon_detached( - pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, - ), - arg_pigeon_instanceIdentifier!, - ); - return wrapResponse(empty: true); - } on PlatformException catch (e) { - return wrapResponse(error: e); - } catch (e) { - return wrapResponse( - error: PlatformException(code: 'error', message: e.toString())); - } - }); - } - } - - { - final BasicMessageChannel< - Object?> pigeonVar_channel = BasicMessageChannel< - Object?>( - 'dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onProgressChanged', - pigeonChannelCodec, - binaryMessenger: binaryMessenger); - if (pigeon_clearHandlers) { - pigeonVar_channel.setMessageHandler(null); - } else { - pigeonVar_channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onProgressChanged was null.'); + 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onProgressChanged was null.'); final List args = (message as List?)!; final WebChromeClient? arg_pigeon_instance = (args[0] as WebChromeClient?); @@ -4483,9 +5119,9 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { assert(arg_params != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onShowFileChooser was null, expected non-null FileChooserParams.'); try { - final List? output = await (onShowFileChooser ?? + final List output = await (onShowFileChooser ?? arg_pigeon_instance!.onShowFileChooser) - ?.call(arg_pigeon_instance!, arg_webView!, arg_params!); + .call(arg_pigeon_instance!, arg_webView!, arg_params!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -4781,8 +5417,8 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { assert(arg_message != null, 'Argument for dev.flutter.pigeon.webview_flutter_android.WebChromeClient.onJsConfirm was null, expected non-null String.'); try { - final bool? output = - await (onJsConfirm ?? arg_pigeon_instance!.onJsConfirm)?.call( + final bool output = + await (onJsConfirm ?? arg_pigeon_instance!.onJsConfirm).call( arg_pigeon_instance!, arg_webView!, arg_url!, arg_message!); return wrapResponse(result: output); } on PlatformException catch (e) { @@ -4872,8 +5508,10 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, value]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this, value]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -4912,8 +5550,10 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, value]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this, value]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -4952,8 +5592,10 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, value]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this, value]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -4992,8 +5634,10 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, value]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this, value]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5032,8 +5676,10 @@ class WebChromeClient extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, value]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this, value]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5155,8 +5801,10 @@ class FlutterAssetManager extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([pigeonVar_instanceIdentifier]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([pigeonVar_instanceIdentifier]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5187,8 +5835,10 @@ class FlutterAssetManager extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, path]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this, path]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5226,8 +5876,10 @@ class FlutterAssetManager extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, name]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this, name]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5341,8 +5993,10 @@ class WebStorage extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([pigeonVar_instanceIdentifier]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([pigeonVar_instanceIdentifier]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5371,8 +6025,10 @@ class WebStorage extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5598,8 +6254,10 @@ class PermissionRequest extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, resources]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, resources]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5626,8 +6284,10 @@ class PermissionRequest extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5732,8 +6392,10 @@ class CustomViewCallback extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5839,8 +6501,10 @@ class View extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, x, y]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this, x, y]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5870,8 +6534,10 @@ class View extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, x, y]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this, x, y]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5898,8 +6564,10 @@ class View extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -6012,8 +6680,10 @@ class GeolocationPermissionsCallback extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, origin, allow, retain]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, origin, allow, retain]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -6117,8 +6787,10 @@ class HttpAuthHandler extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -6150,8 +6822,10 @@ class HttpAuthHandler extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); final List? pigeonVar_replyList = - await pigeonVar_channel.send([this]) as List?; + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -6182,8 +6856,10 @@ class HttpAuthHandler extends PigeonInternalProxyApiBaseClass { pigeonChannelCodec, binaryMessenger: pigeonVar_binaryMessenger, ); - final List? pigeonVar_replyList = await pigeonVar_channel - .send([this, username, password]) as List?; + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, username, password]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -6205,3 +6881,1185 @@ class HttpAuthHandler extends PigeonInternalProxyApiBaseClass { ); } } + +/// Defines a message containing a description and arbitrary data object that +/// can be sent to a `Handler`. +/// +/// See https://developer.android.com/reference/android/os/Message. +class AndroidMessage extends PigeonInternalProxyApiBaseClass { + /// Constructs [AndroidMessage] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + AndroidMessage.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); + + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecAndroidMessage = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + AndroidMessage Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.webview_flutter_android.AndroidMessage.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.AndroidMessage.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.AndroidMessage.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + AndroidMessage.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } + + /// Sends this message to the Android native `Handler` specified by + /// getTarget(). + /// + /// Throws a null pointer exception if this field has not been set. + Future sendToTarget() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecAndroidMessage; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_android.AndroidMessage.sendToTarget'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + @override + AndroidMessage pigeon_copy() { + return AndroidMessage.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } +} + +/// Defines a message containing a description and arbitrary data object that +/// can be sent to a `Handler`. +/// +/// See https://developer.android.com/reference/android/webkit/ClientCertRequest. +class ClientCertRequest extends PigeonInternalProxyApiBaseClass { + /// Constructs [ClientCertRequest] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + ClientCertRequest.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); + + late final _PigeonInternalProxyApiBaseCodec + _pigeonVar_codecClientCertRequest = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + ClientCertRequest Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.webview_flutter_android.ClientCertRequest.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.ClientCertRequest.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.ClientCertRequest.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + ClientCertRequest.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } + + /// Cancel this request. + Future cancel() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecClientCertRequest; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_android.ClientCertRequest.cancel'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + /// Ignore the request for now. + Future ignore() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecClientCertRequest; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_android.ClientCertRequest.ignore'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + /// Proceed with the specified private key and client certificate chain. + Future proceed( + PrivateKey privateKey, + List chain, + ) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecClientCertRequest; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_android.ClientCertRequest.proceed'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, privateKey, chain]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + @override + ClientCertRequest pigeon_copy() { + return ClientCertRequest.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } +} + +/// A private key. +/// +/// The purpose of this interface is to group (and provide type safety for) all +/// private key interfaces. +/// +/// See https://developer.android.com/reference/java/security/PrivateKey. +class PrivateKey extends PigeonInternalProxyApiBaseClass { + /// Constructs [PrivateKey] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + PrivateKey.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + PrivateKey Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.webview_flutter_android.PrivateKey.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.PrivateKey.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.PrivateKey.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + PrivateKey.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } + + @override + PrivateKey pigeon_copy() { + return PrivateKey.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } +} + +/// Abstract class for X.509 certificates. +/// +/// This provides a standard way to access all the attributes of an X.509 +/// certificate. +/// +/// See https://developer.android.com/reference/java/security/cert/X509Certificate. +class X509Certificate extends PigeonInternalProxyApiBaseClass { + /// Constructs [X509Certificate] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + X509Certificate.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + X509Certificate Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.webview_flutter_android.X509Certificate.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.X509Certificate.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.X509Certificate.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + X509Certificate.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } + + @override + X509Certificate pigeon_copy() { + return X509Certificate.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } +} + +/// Represents a request for handling an SSL error. +/// +/// See https://developer.android.com/reference/android/webkit/SslErrorHandler. +class SslErrorHandler extends PigeonInternalProxyApiBaseClass { + /// Constructs [SslErrorHandler] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + SslErrorHandler.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); + + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecSslErrorHandler = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + SslErrorHandler Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.webview_flutter_android.SslErrorHandler.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.SslErrorHandler.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.SslErrorHandler.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + SslErrorHandler.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } + + /// Instructs the WebView that encountered the SSL certificate error to + /// terminate communication with the server. + Future cancel() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecSslErrorHandler; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_android.SslErrorHandler.cancel'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + /// Instructs the WebView that encountered the SSL certificate error to ignore + /// the error and continue communicating with the server. + Future proceed() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecSslErrorHandler; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_android.SslErrorHandler.proceed'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + @override + SslErrorHandler pigeon_copy() { + return SslErrorHandler.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } +} + +/// This class represents a set of one or more SSL errors and the associated SSL +/// certificate. +/// +/// See https://developer.android.com/reference/android/net/http/SslError. +class SslError extends PigeonInternalProxyApiBaseClass { + /// Constructs [SslError] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + SslError.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.certificate, + required this.url, + }); + + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecSslError = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + /// Gets the SSL certificate associated with this object. + final SslCertificate certificate; + + /// Gets the URL associated with this object. + final String url; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + SslError Function( + SslCertificate certificate, + String url, + )? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.webview_flutter_android.SslError.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.SslError.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.SslError.pigeon_newInstance was null, expected non-null int.'); + final SslCertificate? arg_certificate = (args[1] as SslCertificate?); + assert(arg_certificate != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.SslError.pigeon_newInstance was null, expected non-null SslCertificate.'); + final String? arg_url = (args[2] as String?); + assert(arg_url != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.SslError.pigeon_newInstance was null, expected non-null String.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call(arg_certificate!, arg_url!) ?? + SslError.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + certificate: arg_certificate!, + url: arg_url!, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } + + /// Gets the most severe SSL error in this object's set of errors. + Future getPrimaryError() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecSslError; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_android.SslError.getPrimaryError'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as SslErrorType?)!; + } + } + + /// Determines whether this object includes the supplied error. + Future hasError(SslErrorType error) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecSslError; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_android.SslError.hasError'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, error]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as bool?)!; + } + } + + @override + SslError pigeon_copy() { + return SslError.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + certificate: certificate, + url: url, + ); + } +} + +/// A distinguished name helper class. +/// +/// A 3-tuple of: +/// the most specific common name (CN) +/// the most specific organization (O) +/// the most specific organizational unit (OU) +class SslCertificateDName extends PigeonInternalProxyApiBaseClass { + /// Constructs [SslCertificateDName] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + SslCertificateDName.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); + + late final _PigeonInternalProxyApiBaseCodec + _pigeonVar_codecSslCertificateDName = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + SslCertificateDName Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.webview_flutter_android.SslCertificateDName.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.SslCertificateDName.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.SslCertificateDName.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + SslCertificateDName.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } + + /// The most specific Common-name (CN) component of this name. + Future getCName() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecSslCertificateDName; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_android.SslCertificateDName.getCName'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as String?)!; + } + } + + /// The distinguished name (normally includes CN, O, and OU names). + Future getDName() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecSslCertificateDName; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_android.SslCertificateDName.getDName'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as String?)!; + } + } + + /// The most specific Organization (O) component of this name. + Future getOName() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecSslCertificateDName; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_android.SslCertificateDName.getOName'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as String?)!; + } + } + + /// The most specific Organizational Unit (OU) component of this name. + Future getUName() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecSslCertificateDName; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_android.SslCertificateDName.getUName'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as String?)!; + } + } + + @override + SslCertificateDName pigeon_copy() { + return SslCertificateDName.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } +} + +/// SSL certificate info (certificate details) class. +/// +/// See https://developer.android.com/reference/android/net/http/SslCertificate. +class SslCertificate extends PigeonInternalProxyApiBaseClass { + /// Constructs [SslCertificate] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + SslCertificate.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); + + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecSslCertificate = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + SslCertificate Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.webview_flutter_android.SslCertificate.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.SslCertificate.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.webview_flutter_android.SslCertificate.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + SslCertificate.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } + + /// Issued-by distinguished name or null if none has been set. + Future getIssuedBy() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecSslCertificate; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_android.SslCertificate.getIssuedBy'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return (pigeonVar_replyList[0] as SslCertificateDName?); + } + } + + /// Issued-to distinguished name or null if none has been set. + Future getIssuedTo() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecSslCertificate; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_android.SslCertificate.getIssuedTo'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return (pigeonVar_replyList[0] as SslCertificateDName?); + } + } + + /// Not-after date from the certificate validity period or null if none has been + /// set. + Future getValidNotAfterMsSinceEpoch() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecSslCertificate; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_android.SslCertificate.getValidNotAfterMsSinceEpoch'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return (pigeonVar_replyList[0] as int?); + } + } + + /// Not-before date from the certificate validity period or null if none has + /// been set. + Future getValidNotBeforeMsSinceEpoch() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecSslCertificate; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_android.SslCertificate.getValidNotBeforeMsSinceEpoch'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return (pigeonVar_replyList[0] as int?); + } + } + + /// The X509Certificate used to create this SslCertificate or null if no + /// certificate was provided. + /// + /// Always returns null on Android versions below Q. + Future getX509Certificate() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecSslCertificate; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.webview_flutter_android.SslCertificate.getX509Certificate'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return (pigeonVar_replyList[0] as X509Certificate?); + } + } + + @override + SslCertificate pigeon_copy() { + return SslCertificate.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } +} diff --git a/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_controller.dart b/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_controller.dart index 7dc1c7973764..7317affbd857 100644 --- a/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_controller.dart +++ b/packages/webview_flutter/webview_flutter_android/lib/src/android_webview_controller.dart @@ -1450,6 +1450,25 @@ class AndroidNavigationDelegate extends PlatformNavigationDelegate { httpAuthHandler.cancel(); } }, + onFormResubmission: + (_, __, android_webview.AndroidMessage dontResend, ___) { + dontResend.sendToTarget(); + }, + onReceivedClientCertRequest: ( + _, + __, + android_webview.ClientCertRequest request, + ) { + request.cancel(); + }, + onReceivedSslError: ( + _, + __, + android_webview.SslErrorHandler handler, + ___, + ) { + handler.cancel(); + }, ); _downloadListener = (this.params as AndroidNavigationDelegateCreationParams) @@ -1474,7 +1493,10 @@ class AndroidNavigationDelegate extends PlatformNavigationDelegate { params as AndroidNavigationDelegateCreationParams; late final android_webview.WebChromeClient _webChromeClient = - _androidParams.androidWebViewProxy.newWebChromeClient(); + _androidParams.androidWebViewProxy.newWebChromeClient( + onJsConfirm: (_, __, ___, ____) async => false, + onShowFileChooser: (_, __, ___) async => [], + ); /// Gets the native [android_webview.WebChromeClient] that is bridged by this [AndroidNavigationDelegate]. /// diff --git a/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_android_widget.dart b/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_android_widget.dart index e17e50ec6dfa..b9b311a1abcd 100644 --- a/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_android_widget.dart +++ b/packages/webview_flutter/webview_flutter_android/lib/src/legacy/webview_android_widget.dart @@ -185,6 +185,25 @@ class WebViewAndroidPlatformController extends WebViewPlatformController { ); }; }), + onFormResubmission: + (_, __, android_webview.AndroidMessage dontResend, ___) { + dontResend.sendToTarget(); + }, + onReceivedClientCertRequest: ( + _, + __, + android_webview.ClientCertRequest request, + ) { + request.cancel(); + }, + onReceivedSslError: ( + _, + __, + android_webview.SslErrorHandler handler, + ___, + ) { + handler.cancel(); + }, requestLoading: withWeakReferenceTo(this, ( WeakReference weakReference, ) { @@ -247,18 +266,21 @@ class WebViewAndroidPlatformController extends WebViewPlatformController { @visibleForTesting late final android_webview.WebChromeClient webChromeClient = android_webview.WebChromeClient( - onProgressChanged: withWeakReferenceTo( - this, - (WeakReference weakReference) { - return (_, __, int progress) { - final WebViewAndroidPlatformController? controller = - weakReference.target; - if (controller != null && controller._hasProgressTracking) { - controller.callbacksHandler.onProgress(progress); - } - }; - }, - )); + onProgressChanged: withWeakReferenceTo( + this, + (WeakReference weakReference) { + return (_, __, int progress) { + final WebViewAndroidPlatformController? controller = + weakReference.target; + if (controller != null && controller._hasProgressTracking) { + controller.callbacksHandler.onProgress(progress); + } + }; + }, + ), + onJsConfirm: (_, __, ___, ____) async => false, + onShowFileChooser: (_, __, ___) async => [], + ); /// Manages the JavaScript storage APIs. final android_webview.WebStorage webStorage; @@ -647,6 +669,23 @@ class WebViewProxy { android_webview.WebView webView, android_webview.WebResourceRequest request, )? requestLoading, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + android_webview.AndroidMessage, + android_webview.AndroidMessage, + )? onFormResubmission, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + android_webview.ClientCertRequest, + )? onReceivedClientCertRequest, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + android_webview.SslErrorHandler, + android_webview.SslError, + )? onReceivedSslError, void Function( android_webview.WebViewClient, android_webview.WebView webView, diff --git a/packages/webview_flutter/webview_flutter_android/pigeons/android_webkit.dart b/packages/webview_flutter/webview_flutter_android/pigeons/android_webkit.dart index 8d3a4dbed5c8..cc173f8f875f 100644 --- a/packages/webview_flutter/webview_flutter_android/pigeons/android_webkit.dart +++ b/packages/webview_flutter/webview_flutter_android/pigeons/android_webkit.dart @@ -80,6 +80,32 @@ enum ConsoleMessageLevel { unknown, } +/// Type of error for a SslCertificate. +/// +/// See https://developer.android.com/reference/android/net/http/SslError#SSL_DATE_INVALID. +enum SslErrorType { + /// The date of the certificate is invalid. + dateInvalid, + + /// The certificate has expired. + expired, + + /// Hostname mismatch. + idMismatch, + + /// A generic error occurred. + invalid, + + /// The certificate is not yet valid. + notYetValid, + + /// The certificate authority is not trusted. + untrusted, + + /// The type is not recognized by this wrapper. + unknown, +} + /// Encompasses parameters to the `WebViewClient.shouldInterceptRequest` method. /// /// See https://developer.android.com/reference/android/webkit/WebResourceRequest. @@ -456,6 +482,49 @@ abstract class WebViewClient { String realm, )? onReceivedHttpAuthRequest; + /// Ask the host application if the browser should resend data as the + /// requested page was a result of a POST. + void Function( + WebView view, + AndroidMessage dontResend, + AndroidMessage resend, + )? onFormResubmission; + + /// Notify the host application that the WebView will load the resource + /// specified by the given url. + void Function(WebView view, String url)? onLoadResource; + + /// Notify the host application that WebView content left over from previous + /// page navigations will no longer be drawn. + void Function(WebView view, String url)? onPageCommitVisible; + + /// Notify the host application to handle a SSL client certificate request. + void Function( + WebView view, + ClientCertRequest request, + )? onReceivedClientCertRequest; + + /// Notify the host application that a request to automatically log in the + /// user has been processed. + void Function( + WebView view, + String realm, + String? account, + String args, + )? onReceivedLoginRequest; + + /// Notifies the host application that an SSL error occurred while loading a + /// resource. + void Function( + WebView view, + SslErrorHandler handler, + SslError error, + )? onReceivedSslError; + + /// Notify the host application that the scale applied to the WebView has + /// changed. + void Function(WebView view, double oldScale, double newScale)? onScaleChanged; + /// Sets the required synchronous return value for the Java method, /// `WebViewClient.shouldOverrideUrlLoading(...)`. /// @@ -513,7 +582,7 @@ abstract class WebChromeClient { late List Function( WebView webView, FileChooserParams params, - )? onShowFileChooser; + ) onShowFileChooser; /// Notify the host application that web content is requesting permission to /// access the specified resources and the permission currently isn't granted @@ -554,7 +623,7 @@ abstract class WebChromeClient { /// Notify the host application that the web page wants to display a /// JavaScript `confirm()` dialog. @async - late bool Function(WebView webView, String url, String message)? onJsConfirm; + late bool Function(WebView webView, String url, String message) onJsConfirm; /// Notify the host application that the web page wants to display a /// JavaScript `prompt()` dialog. @@ -800,3 +869,160 @@ abstract class HttpAuthHandler { /// credentials. void proceed(String username, String password); } + +/// Defines a message containing a description and arbitrary data object that +/// can be sent to a `Handler`. +/// +/// See https://developer.android.com/reference/android/os/Message. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.os.Message'), +) +abstract class AndroidMessage { + /// Sends this message to the Android native `Handler` specified by + /// getTarget(). + /// + /// Throws a null pointer exception if this field has not been set. + void sendToTarget(); +} + +/// Defines a message containing a description and arbitrary data object that +/// can be sent to a `Handler`. +/// +/// See https://developer.android.com/reference/android/webkit/ClientCertRequest. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'android.webkit.ClientCertRequest', + ), +) +abstract class ClientCertRequest { + /// Cancel this request. + void cancel(); + + /// Ignore the request for now. + void ignore(); + + /// Proceed with the specified private key and client certificate chain. + void proceed(PrivateKey privateKey, List chain); +} + +/// A private key. +/// +/// The purpose of this interface is to group (and provide type safety for) all +/// private key interfaces. +/// +/// See https://developer.android.com/reference/java/security/PrivateKey. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'java.security.PrivateKey', + ), +) +abstract class PrivateKey {} + +/// Abstract class for X.509 certificates. +/// +/// This provides a standard way to access all the attributes of an X.509 +/// certificate. +/// +/// See https://developer.android.com/reference/java/security/cert/X509Certificate. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'java.security.cert.X509Certificate', + ), +) +abstract class X509Certificate {} + +/// Represents a request for handling an SSL error. +/// +/// See https://developer.android.com/reference/android/webkit/SslErrorHandler. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'android.webkit.SslErrorHandler', + ), +) +abstract class SslErrorHandler { + /// Instructs the WebView that encountered the SSL certificate error to + /// terminate communication with the server. + void cancel(); + + /// Instructs the WebView that encountered the SSL certificate error to ignore + /// the error and continue communicating with the server. + void proceed(); +} + +/// This class represents a set of one or more SSL errors and the associated SSL +/// certificate. +/// +/// See https://developer.android.com/reference/android/net/http/SslError. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'android.net.http.SslError', + ), +) +abstract class SslError { + /// Gets the SSL certificate associated with this object. + late SslCertificate certificate; + + /// Gets the URL associated with this object. + late String url; + + /// Gets the most severe SSL error in this object's set of errors. + SslErrorType getPrimaryError(); + + /// Determines whether this object includes the supplied error. + bool hasError(SslErrorType error); +} + +/// A distinguished name helper class. +/// +/// A 3-tuple of: +/// the most specific common name (CN) +/// the most specific organization (O) +/// the most specific organizational unit (OU) +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'android.net.http.SslCertificate.DName', + ), +) +abstract class SslCertificateDName { + /// The most specific Common-name (CN) component of this name. + String getCName(); + + /// The distinguished name (normally includes CN, O, and OU names). + String getDName(); + + /// The most specific Organization (O) component of this name. + String getOName(); + + /// The most specific Organizational Unit (OU) component of this name. + String getUName(); +} + +/// SSL certificate info (certificate details) class. +/// +/// See https://developer.android.com/reference/android/net/http/SslCertificate. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'android.net.http.SslCertificate', + ), +) +abstract class SslCertificate { + /// Issued-by distinguished name or null if none has been set. + SslCertificateDName? getIssuedBy(); + + /// Issued-to distinguished name or null if none has been set. + SslCertificateDName? getIssuedTo(); + + /// Not-after date from the certificate validity period or null if none has been + /// set. + int? getValidNotAfterMsSinceEpoch(); + + /// Not-before date from the certificate validity period or null if none has + /// been set. + int? getValidNotBeforeMsSinceEpoch(); + + /// The X509Certificate used to create this SslCertificate or null if no + /// certificate was provided. + /// + /// Always returns null on Android versions below Q. + X509Certificate? getX509Certificate(); +} diff --git a/packages/webview_flutter/webview_flutter_android/pubspec.yaml b/packages/webview_flutter/webview_flutter_android/pubspec.yaml index f9b5eae6e969..915ac70f768d 100644 --- a/packages/webview_flutter/webview_flutter_android/pubspec.yaml +++ b/packages/webview_flutter/webview_flutter_android/pubspec.yaml @@ -2,7 +2,7 @@ name: webview_flutter_android description: A Flutter plugin that provides a WebView widget on Android. repository: https://github.com/flutter/packages/tree/main/packages/webview_flutter/webview_flutter_android issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+webview%22 -version: 4.3.4 +version: 4.3.5 environment: sdk: ^3.6.0 @@ -27,7 +27,7 @@ dev_dependencies: flutter_test: sdk: flutter mockito: ^5.4.4 - pigeon: ^22.5.0 + pigeon: ^25.2.0 topics: - html diff --git a/packages/webview_flutter/webview_flutter_android/test/android_navigation_delegate_test.dart b/packages/webview_flutter/webview_flutter_android/test/android_navigation_delegate_test.dart index b61e0a2561c7..fef0b9f1e80e 100644 --- a/packages/webview_flutter/webview_flutter_android/test/android_navigation_delegate_test.dart +++ b/packages/webview_flutter/webview_flutter_android/test/android_navigation_delegate_test.dart @@ -653,6 +653,13 @@ class CapturingWebViewClient extends android_webview.WebViewClient { super.onReceivedRequestError, super.requestLoading, super.urlLoading, + super.onFormResubmission, + super.onLoadResource, + super.onPageCommitVisible, + super.onReceivedClientCertRequest, + super.onReceivedLoginRequest, + super.onReceivedSslError, + super.onScaleChanged, }) : super.pigeon_detached( pigeon_instanceManager: android_webview.PigeonInstanceManager( onWeakReferenceRemoved: (_) {})) { @@ -674,7 +681,7 @@ class CapturingWebViewClient extends android_webview.WebViewClient { class CapturingWebChromeClient extends android_webview.WebChromeClient { CapturingWebChromeClient({ super.onProgressChanged, - super.onShowFileChooser, + required super.onShowFileChooser, super.onGeolocationPermissionsShowPrompt, super.onGeolocationPermissionsHidePrompt, super.onShowCustomView, @@ -682,7 +689,7 @@ class CapturingWebChromeClient extends android_webview.WebChromeClient { super.onPermissionRequest, super.onConsoleMessage, super.onJsAlert, - super.onJsConfirm, + required super.onJsConfirm, super.onJsPrompt, }) : super.pigeon_detached( pigeon_instanceManager: android_webview.PigeonInstanceManager( @@ -691,7 +698,10 @@ class CapturingWebChromeClient extends android_webview.WebChromeClient { } static CapturingWebChromeClient lastCreatedDelegate = - CapturingWebChromeClient(); + CapturingWebChromeClient( + onJsConfirm: (_, __, ___, ____) async => false, + onShowFileChooser: (_, __, ___) async => [], + ); } // Records the last created instance of itself. diff --git a/packages/webview_flutter/webview_flutter_android/test/android_navigation_delegate_test.mocks.dart b/packages/webview_flutter/webview_flutter_android/test/android_navigation_delegate_test.mocks.dart index efe2191cc974..7d84c4694a10 100644 --- a/packages/webview_flutter/webview_flutter_android/test/android_navigation_delegate_test.mocks.dart +++ b/packages/webview_flutter/webview_flutter_android/test/android_navigation_delegate_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in webview_flutter_android/test/android_navigation_delegate_test.dart. // Do not manually edit this file. @@ -16,6 +16,7 @@ import 'package:webview_flutter_android/src/android_webkit.g.dart' as _i2; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types @@ -23,35 +24,20 @@ import 'package:webview_flutter_android/src/android_webkit.g.dart' as _i2; class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { - _FakePigeonInstanceManager_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeHttpAuthHandler_1 extends _i1.SmartFake implements _i2.HttpAuthHandler { - _FakeHttpAuthHandler_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeHttpAuthHandler_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeDownloadListener_2 extends _i1.SmartFake implements _i2.DownloadListener { - _FakeDownloadListener_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeDownloadListener_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [HttpAuthHandler]. @@ -73,52 +59,31 @@ class MockHttpAuthHandler extends _i1.Mock implements _i2.HttpAuthHandler { @override _i3.Future useHttpAuthUsernamePassword() => (super.noSuchMethod( - Invocation.method( - #useHttpAuthUsernamePassword, - [], - ), + Invocation.method(#useHttpAuthUsernamePassword, []), returnValue: _i3.Future.value(false), ) as _i3.Future); @override _i3.Future cancel() => (super.noSuchMethod( - Invocation.method( - #cancel, - [], - ), + Invocation.method(#cancel, []), returnValue: _i3.Future.value(), returnValueForMissingStub: _i3.Future.value(), ) as _i3.Future); @override - _i3.Future proceed( - String? username, - String? password, - ) => + _i3.Future proceed(String? username, String? password) => (super.noSuchMethod( - Invocation.method( - #proceed, - [ - username, - password, - ], - ), + Invocation.method(#proceed, [username, password]), returnValue: _i3.Future.value(), returnValueForMissingStub: _i3.Future.value(), ) as _i3.Future); @override _i2.HttpAuthHandler pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), returnValue: _FakeHttpAuthHandler_1( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), ) as _i2.HttpAuthHandler); } @@ -132,31 +97,25 @@ class MockDownloadListener extends _i1.Mock implements _i2.DownloadListener { } @override - void Function( - _i2.DownloadListener, - String, - String, - String, - String, - int, - ) get onDownloadStart => (super.noSuchMethod( - Invocation.getter(#onDownloadStart), - returnValue: ( - _i2.DownloadListener pigeon_instance, - String url, - String userAgent, - String contentDisposition, - String mimetype, - int contentLength, - ) {}, - ) as void Function( - _i2.DownloadListener, - String, - String, - String, - String, - int, - )); + void Function(_i2.DownloadListener, String, String, String, String, int) + get onDownloadStart => (super.noSuchMethod( + Invocation.getter(#onDownloadStart), + returnValue: ( + _i2.DownloadListener pigeon_instance, + String url, + String userAgent, + String contentDisposition, + String mimetype, + int contentLength, + ) {}, + ) as void Function( + _i2.DownloadListener, + String, + String, + String, + String, + int, + )); @override _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( @@ -169,16 +128,10 @@ class MockDownloadListener extends _i1.Mock implements _i2.DownloadListener { @override _i2.DownloadListener pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), returnValue: _FakeDownloadListener_2( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), ) as _i2.DownloadListener); } diff --git a/packages/webview_flutter/webview_flutter_android/test/android_webview_controller_test.dart b/packages/webview_flutter/webview_flutter_android/test/android_webview_controller_test.dart index 6762d1f01699..4fd19cf68a86 100644 --- a/packages/webview_flutter/webview_flutter_android/test/android_webview_controller_test.dart +++ b/packages/webview_flutter/webview_flutter_android/test/android_webview_controller_test.dart @@ -46,11 +46,11 @@ void main() { void Function( android_webview.WebChromeClient, android_webview.WebView, int)? onProgressChanged, - Future> Function( + required Future> Function( android_webview.WebChromeClient, android_webview.WebView, android_webview.FileChooserParams, - )? onShowFileChooser, + ) onShowFileChooser, void Function(android_webview.WebChromeClient, android_webview.PermissionRequest)? onPermissionRequest, @@ -71,12 +71,12 @@ void main() { Future Function(android_webview.WebChromeClient, android_webview.WebView, String, String)? onJsAlert, - Future Function( + required Future Function( android_webview.WebChromeClient, android_webview.WebView, String, String, - )? onJsConfirm, + ) onJsConfirm, Future Function( android_webview.WebChromeClient, android_webview.WebView, @@ -196,6 +196,46 @@ void main() { String, String)? onReceivedHttpAuthRequest, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + android_webview.AndroidMessage, + android_webview.AndroidMessage, + )? onFormResubmission, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + String, + )? onLoadResource, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + String, + )? onPageCommitVisible, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + android_webview.ClientCertRequest, + )? onReceivedClientCertRequest, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + String, + String, + String, + )? onReceivedLoginRequest, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + android_webview.SslErrorHandler, + android_webview.SslError, + )? onReceivedSslError, + void Function( + android_webview.WebViewClient, + android_webview.WebView, + double, + double, + )? onScaleChanged, }) => mockWebViewClient ?? MockWebViewClient(), instanceFlutterAssetManager: () => @@ -629,7 +669,10 @@ void main() { controller.setPlatformNavigationDelegate(androidNavigationDelegate); CapturingWebChromeClient.lastCreatedDelegate.onProgressChanged!( - TestWebChromeClient(), + TestWebChromeClient( + onJsConfirm: (_, __, ___, ____) async => false, + onShowFileChooser: (_, __, ___) async => [], + ), MockWebView(), 42, ); @@ -645,7 +688,10 @@ void main() { // Should not cause LateInitializationError CapturingWebChromeClient.lastCreatedDelegate.onProgressChanged!( - TestWebChromeClient(), + TestWebChromeClient( + onJsConfirm: (_, __, ___, ____) async => false, + onShowFileChooser: (_, __, ___) async => [], + ), MockWebView(), 42, ); @@ -895,6 +941,8 @@ void main() { onPermissionRequestCallback( android_webview.WebChromeClient.pigeon_detached( + onJsConfirm: (_, __, ___, ____) async => false, + onShowFileChooser: (_, __, ___) async => [], pigeon_instanceManager: testInstanceManager), mockPermissionRequest, ); @@ -949,6 +997,8 @@ void main() { onPermissionRequestCallback( android_webview.WebChromeClient.pigeon_detached( + onJsConfirm: (_, __, ___, ____) async => false, + onShowFileChooser: (_, __, ___) async => [], pigeon_instanceManager: testInstanceManager, ), mockPermissionRequest, @@ -2069,6 +2119,13 @@ class TestWebViewClient extends android_webview.WebViewClient { super.urlLoading, super.doUpdateVisitedHistory, super.onReceivedHttpAuthRequest, + super.onFormResubmission, + super.onLoadResource, + super.onPageCommitVisible, + super.onReceivedClientCertRequest, + super.onReceivedLoginRequest, + super.onReceivedSslError, + super.onScaleChanged, }) : super.pigeon_detached( pigeon_instanceManager: android_webview.PigeonInstanceManager( onWeakReferenceRemoved: (_) {}, @@ -2079,7 +2136,7 @@ class TestWebViewClient extends android_webview.WebViewClient { class TestWebChromeClient extends android_webview.WebChromeClient { TestWebChromeClient({ super.onProgressChanged, - super.onShowFileChooser, + required super.onShowFileChooser, super.onPermissionRequest, super.onShowCustomView, super.onHideCustomView, @@ -2087,7 +2144,7 @@ class TestWebChromeClient extends android_webview.WebChromeClient { super.onGeolocationPermissionsHidePrompt, super.onConsoleMessage, super.onJsAlert, - super.onJsConfirm, + required super.onJsConfirm, super.onJsPrompt, }) : super.pigeon_detached( pigeon_instanceManager: android_webview.PigeonInstanceManager( diff --git a/packages/webview_flutter/webview_flutter_android/test/android_webview_controller_test.mocks.dart b/packages/webview_flutter/webview_flutter_android/test/android_webview_controller_test.mocks.dart index 2e13f747bd67..02bcae66842f 100644 --- a/packages/webview_flutter/webview_flutter_android/test/android_webview_controller_test.mocks.dart +++ b/packages/webview_flutter/webview_flutter_android/test/android_webview_controller_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in webview_flutter_android/test/android_webview_controller_test.dart. // Do not manually edit this file. @@ -29,6 +29,7 @@ import 'package:webview_flutter_platform_interface/webview_flutter_platform_inte // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types @@ -36,34 +37,19 @@ import 'package:webview_flutter_platform_interface/webview_flutter_platform_inte class _FakeWebChromeClient_0 extends _i1.SmartFake implements _i2.WebChromeClient { - _FakeWebChromeClient_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebChromeClient_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWebViewClient_1 extends _i1.SmartFake implements _i2.WebViewClient { - _FakeWebViewClient_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebViewClient_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeDownloadListener_2 extends _i1.SmartFake implements _i2.DownloadListener { - _FakeDownloadListener_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeDownloadListener_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakePlatformNavigationDelegateCreationParams_3 extends _i1.SmartFake @@ -71,10 +57,7 @@ class _FakePlatformNavigationDelegateCreationParams_3 extends _i1.SmartFake _FakePlatformNavigationDelegateCreationParams_3( Object parent, Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + ) : super(parent, parentInvocation); } class _FakePlatformWebViewControllerCreationParams_4 extends _i1.SmartFake @@ -82,125 +65,67 @@ class _FakePlatformWebViewControllerCreationParams_4 extends _i1.SmartFake _FakePlatformWebViewControllerCreationParams_4( Object parent, Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + ) : super(parent, parentInvocation); } class _FakeObject_5 extends _i1.SmartFake implements Object { - _FakeObject_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeObject_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeOffset_6 extends _i1.SmartFake implements _i4.Offset { - _FakeOffset_6( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeOffset_6(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWebView_7 extends _i1.SmartFake implements _i2.WebView { - _FakeWebView_7( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebView_7(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeJavaScriptChannel_8 extends _i1.SmartFake implements _i2.JavaScriptChannel { - _FakeJavaScriptChannel_8( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeJavaScriptChannel_8(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeCookieManager_9 extends _i1.SmartFake implements _i2.CookieManager { - _FakeCookieManager_9( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeCookieManager_9(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeFlutterAssetManager_10 extends _i1.SmartFake implements _i2.FlutterAssetManager { - _FakeFlutterAssetManager_10( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeFlutterAssetManager_10(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWebStorage_11 extends _i1.SmartFake implements _i2.WebStorage { - _FakeWebStorage_11( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebStorage_11(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakePigeonInstanceManager_12 extends _i1.SmartFake implements _i2.PigeonInstanceManager { - _FakePigeonInstanceManager_12( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePigeonInstanceManager_12(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakePlatformViewsServiceProxy_13 extends _i1.SmartFake implements _i5.PlatformViewsServiceProxy { - _FakePlatformViewsServiceProxy_13( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePlatformViewsServiceProxy_13(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakePlatformWebViewController_14 extends _i1.SmartFake implements _i3.PlatformWebViewController { - _FakePlatformWebViewController_14( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePlatformWebViewController_14(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeSize_15 extends _i1.SmartFake implements _i4.Size { - _FakeSize_15( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeSize_15(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeGeolocationPermissionsCallback_16 extends _i1.SmartFake @@ -208,21 +133,13 @@ class _FakeGeolocationPermissionsCallback_16 extends _i1.SmartFake _FakeGeolocationPermissionsCallback_16( Object parent, Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + ) : super(parent, parentInvocation); } class _FakePermissionRequest_17 extends _i1.SmartFake implements _i2.PermissionRequest { - _FakePermissionRequest_17( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePermissionRequest_17(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeExpensiveAndroidViewController_18 extends _i1.SmartFake @@ -230,10 +147,7 @@ class _FakeExpensiveAndroidViewController_18 extends _i1.SmartFake _FakeExpensiveAndroidViewController_18( Object parent, Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + ) : super(parent, parentInvocation); } class _FakeSurfaceAndroidViewController_19 extends _i1.SmartFake @@ -241,30 +155,17 @@ class _FakeSurfaceAndroidViewController_19 extends _i1.SmartFake _FakeSurfaceAndroidViewController_19( Object parent, Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + ) : super(parent, parentInvocation); } class _FakeWebSettings_20 extends _i1.SmartFake implements _i2.WebSettings { - _FakeWebSettings_20( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebSettings_20(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWebViewPoint_21 extends _i1.SmartFake implements _i2.WebViewPoint { - _FakeWebViewPoint_21( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebViewPoint_21(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [AndroidNavigationDelegate]. @@ -329,22 +230,17 @@ class MockAndroidNavigationDelegate extends _i1.Mock @override _i8.Future setOnLoadRequest(_i7.LoadRequestCallback? onLoadRequest) => (super.noSuchMethod( - Invocation.method( - #setOnLoadRequest, - [onLoadRequest], - ), + Invocation.method(#setOnLoadRequest, [onLoadRequest]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setOnNavigationRequest( - _i3.NavigationRequestCallback? onNavigationRequest) => + _i3.NavigationRequestCallback? onNavigationRequest, + ) => (super.noSuchMethod( - Invocation.method( - #setOnNavigationRequest, - [onNavigationRequest], - ), + Invocation.method(#setOnNavigationRequest, [onNavigationRequest]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -352,10 +248,7 @@ class MockAndroidNavigationDelegate extends _i1.Mock @override _i8.Future setOnPageStarted(_i3.PageEventCallback? onPageStarted) => (super.noSuchMethod( - Invocation.method( - #setOnPageStarted, - [onPageStarted], - ), + Invocation.method(#setOnPageStarted, [onPageStarted]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -363,10 +256,7 @@ class MockAndroidNavigationDelegate extends _i1.Mock @override _i8.Future setOnPageFinished(_i3.PageEventCallback? onPageFinished) => (super.noSuchMethod( - Invocation.method( - #setOnPageFinished, - [onPageFinished], - ), + Invocation.method(#setOnPageFinished, [onPageFinished]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -374,10 +264,7 @@ class MockAndroidNavigationDelegate extends _i1.Mock @override _i8.Future setOnHttpError(_i3.HttpResponseErrorCallback? onHttpError) => (super.noSuchMethod( - Invocation.method( - #setOnHttpError, - [onHttpError], - ), + Invocation.method(#setOnHttpError, [onHttpError]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -385,22 +272,17 @@ class MockAndroidNavigationDelegate extends _i1.Mock @override _i8.Future setOnProgress(_i3.ProgressCallback? onProgress) => (super.noSuchMethod( - Invocation.method( - #setOnProgress, - [onProgress], - ), + Invocation.method(#setOnProgress, [onProgress]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setOnWebResourceError( - _i3.WebResourceErrorCallback? onWebResourceError) => + _i3.WebResourceErrorCallback? onWebResourceError, + ) => (super.noSuchMethod( - Invocation.method( - #setOnWebResourceError, - [onWebResourceError], - ), + Invocation.method(#setOnWebResourceError, [onWebResourceError]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -408,22 +290,17 @@ class MockAndroidNavigationDelegate extends _i1.Mock @override _i8.Future setOnUrlChange(_i3.UrlChangeCallback? onUrlChange) => (super.noSuchMethod( - Invocation.method( - #setOnUrlChange, - [onUrlChange], - ), + Invocation.method(#setOnUrlChange, [onUrlChange]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setOnHttpAuthRequest( - _i3.HttpAuthRequestCallback? onHttpAuthRequest) => + _i3.HttpAuthRequestCallback? onHttpAuthRequest, + ) => (super.noSuchMethod( - Invocation.method( - #setOnHttpAuthRequest, - [onHttpAuthRequest], - ), + Invocation.method(#setOnHttpAuthRequest, [onHttpAuthRequest]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -457,45 +334,29 @@ class MockAndroidWebViewController extends _i1.Mock @override _i8.Future setAllowFileAccess(bool? allow) => (super.noSuchMethod( - Invocation.method( - #setAllowFileAccess, - [allow], - ), + Invocation.method(#setAllowFileAccess, [allow]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future loadFile(String? absoluteFilePath) => (super.noSuchMethod( - Invocation.method( - #loadFile, - [absoluteFilePath], - ), + Invocation.method(#loadFile, [absoluteFilePath]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future loadFlutterAsset(String? key) => (super.noSuchMethod( - Invocation.method( - #loadFlutterAsset, - [key], - ), + Invocation.method(#loadFlutterAsset, [key]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override - _i8.Future loadHtmlString( - String? html, { - String? baseUrl, - }) => + _i8.Future loadHtmlString(String? html, {String? baseUrl}) => (super.noSuchMethod( - Invocation.method( - #loadHtmlString, - [html], - {#baseUrl: baseUrl}, - ), + Invocation.method(#loadHtmlString, [html], {#baseUrl: baseUrl}), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -503,112 +364,80 @@ class MockAndroidWebViewController extends _i1.Mock @override _i8.Future loadRequest(_i3.LoadRequestParams? params) => (super.noSuchMethod( - Invocation.method( - #loadRequest, - [params], - ), + Invocation.method(#loadRequest, [params]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future currentUrl() => (super.noSuchMethod( - Invocation.method( - #currentUrl, - [], - ), + Invocation.method(#currentUrl, []), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future canGoBack() => (super.noSuchMethod( - Invocation.method( - #canGoBack, - [], - ), + Invocation.method(#canGoBack, []), returnValue: _i8.Future.value(false), returnValueForMissingStub: _i8.Future.value(false), ) as _i8.Future); @override _i8.Future canGoForward() => (super.noSuchMethod( - Invocation.method( - #canGoForward, - [], - ), + Invocation.method(#canGoForward, []), returnValue: _i8.Future.value(false), returnValueForMissingStub: _i8.Future.value(false), ) as _i8.Future); @override _i8.Future goBack() => (super.noSuchMethod( - Invocation.method( - #goBack, - [], - ), + Invocation.method(#goBack, []), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future goForward() => (super.noSuchMethod( - Invocation.method( - #goForward, - [], - ), + Invocation.method(#goForward, []), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future reload() => (super.noSuchMethod( - Invocation.method( - #reload, - [], - ), + Invocation.method(#reload, []), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future clearCache() => (super.noSuchMethod( - Invocation.method( - #clearCache, - [], - ), + Invocation.method(#clearCache, []), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future clearLocalStorage() => (super.noSuchMethod( - Invocation.method( - #clearLocalStorage, - [], - ), + Invocation.method(#clearLocalStorage, []), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setPlatformNavigationDelegate( - _i3.PlatformNavigationDelegate? handler) => + _i3.PlatformNavigationDelegate? handler, + ) => (super.noSuchMethod( - Invocation.method( - #setPlatformNavigationDelegate, - [handler], - ), + Invocation.method(#setPlatformNavigationDelegate, [handler]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future runJavaScript(String? javaScript) => (super.noSuchMethod( - Invocation.method( - #runJavaScript, - [javaScript], - ), + Invocation.method(#runJavaScript, [javaScript]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -616,34 +445,27 @@ class MockAndroidWebViewController extends _i1.Mock @override _i8.Future runJavaScriptReturningResult(String? javaScript) => (super.noSuchMethod( - Invocation.method( - #runJavaScriptReturningResult, - [javaScript], - ), - returnValue: _i8.Future.value(_FakeObject_5( - this, - Invocation.method( - #runJavaScriptReturningResult, - [javaScript], + Invocation.method(#runJavaScriptReturningResult, [javaScript]), + returnValue: _i8.Future.value( + _FakeObject_5( + this, + Invocation.method(#runJavaScriptReturningResult, [javaScript]), ), - )), - returnValueForMissingStub: _i8.Future.value(_FakeObject_5( - this, - Invocation.method( - #runJavaScriptReturningResult, - [javaScript], + ), + returnValueForMissingStub: _i8.Future.value( + _FakeObject_5( + this, + Invocation.method(#runJavaScriptReturningResult, [javaScript]), ), - )), + ), ) as _i8.Future); @override _i8.Future addJavaScriptChannel( - _i3.JavaScriptChannelParams? javaScriptChannelParams) => + _i3.JavaScriptChannelParams? javaScriptChannelParams, + ) => (super.noSuchMethod( - Invocation.method( - #addJavaScriptChannel, - [javaScriptChannelParams], - ), + Invocation.method(#addJavaScriptChannel, [javaScriptChannelParams]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -651,96 +473,55 @@ class MockAndroidWebViewController extends _i1.Mock @override _i8.Future removeJavaScriptChannel(String? javaScriptChannelName) => (super.noSuchMethod( - Invocation.method( - #removeJavaScriptChannel, - [javaScriptChannelName], - ), + Invocation.method(#removeJavaScriptChannel, [ + javaScriptChannelName, + ]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future getTitle() => (super.noSuchMethod( - Invocation.method( - #getTitle, - [], - ), + Invocation.method(#getTitle, []), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override - _i8.Future scrollTo( - int? x, - int? y, - ) => - (super.noSuchMethod( - Invocation.method( - #scrollTo, - [ - x, - y, - ], - ), + _i8.Future scrollTo(int? x, int? y) => (super.noSuchMethod( + Invocation.method(#scrollTo, [x, y]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override - _i8.Future scrollBy( - int? x, - int? y, - ) => - (super.noSuchMethod( - Invocation.method( - #scrollBy, - [ - x, - y, - ], - ), + _i8.Future scrollBy(int? x, int? y) => (super.noSuchMethod( + Invocation.method(#scrollBy, [x, y]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future<_i4.Offset> getScrollPosition() => (super.noSuchMethod( - Invocation.method( - #getScrollPosition, - [], + Invocation.method(#getScrollPosition, []), + returnValue: _i8.Future<_i4.Offset>.value( + _FakeOffset_6(this, Invocation.method(#getScrollPosition, [])), + ), + returnValueForMissingStub: _i8.Future<_i4.Offset>.value( + _FakeOffset_6(this, Invocation.method(#getScrollPosition, [])), ), - returnValue: _i8.Future<_i4.Offset>.value(_FakeOffset_6( - this, - Invocation.method( - #getScrollPosition, - [], - ), - )), - returnValueForMissingStub: _i8.Future<_i4.Offset>.value(_FakeOffset_6( - this, - Invocation.method( - #getScrollPosition, - [], - ), - )), ) as _i8.Future<_i4.Offset>); @override _i8.Future enableZoom(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #enableZoom, - [enabled], - ), + Invocation.method(#enableZoom, [enabled]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setBackgroundColor(_i4.Color? color) => (super.noSuchMethod( - Invocation.method( - #setBackgroundColor, - [color], - ), + Invocation.method(#setBackgroundColor, [color]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -748,32 +529,26 @@ class MockAndroidWebViewController extends _i1.Mock @override _i8.Future setJavaScriptMode(_i3.JavaScriptMode? javaScriptMode) => (super.noSuchMethod( - Invocation.method( - #setJavaScriptMode, - [javaScriptMode], - ), + Invocation.method(#setJavaScriptMode, [javaScriptMode]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setUserAgent(String? userAgent) => (super.noSuchMethod( - Invocation.method( - #setUserAgent, - [userAgent], - ), + Invocation.method(#setUserAgent, [userAgent]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setOnScrollPositionChange( - void Function(_i3.ScrollPositionChange)? onScrollPositionChange) => + void Function(_i3.ScrollPositionChange)? onScrollPositionChange, + ) => (super.noSuchMethod( - Invocation.method( - #setOnScrollPositionChange, - [onScrollPositionChange], - ), + Invocation.method(#setOnScrollPositionChange, [ + onScrollPositionChange, + ]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -781,66 +556,51 @@ class MockAndroidWebViewController extends _i1.Mock @override _i8.Future setMediaPlaybackRequiresUserGesture(bool? require) => (super.noSuchMethod( - Invocation.method( - #setMediaPlaybackRequiresUserGesture, - [require], - ), + Invocation.method(#setMediaPlaybackRequiresUserGesture, [require]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setTextZoom(int? textZoom) => (super.noSuchMethod( - Invocation.method( - #setTextZoom, - [textZoom], - ), + Invocation.method(#setTextZoom, [textZoom]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setAllowContentAccess(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setAllowContentAccess, - [enabled], - ), + Invocation.method(#setAllowContentAccess, [enabled]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setGeolocationEnabled(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setGeolocationEnabled, - [enabled], - ), + Invocation.method(#setGeolocationEnabled, [enabled]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setOnShowFileSelector( - _i8.Future> Function(_i7.FileSelectorParams)? - onShowFileSelector) => + _i8.Future> Function(_i7.FileSelectorParams)? + onShowFileSelector, + ) => (super.noSuchMethod( - Invocation.method( - #setOnShowFileSelector, - [onShowFileSelector], - ), + Invocation.method(#setOnShowFileSelector, [onShowFileSelector]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setOnPlatformPermissionRequest( - void Function(_i3.PlatformWebViewPermissionRequest)? - onPermissionRequest) => + void Function(_i3.PlatformWebViewPermissionRequest)? onPermissionRequest, + ) => (super.noSuchMethod( - Invocation.method( - #setOnPlatformPermissionRequest, - [onPermissionRequest], - ), + Invocation.method(#setOnPlatformPermissionRequest, [ + onPermissionRequest, + ]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -851,14 +611,10 @@ class MockAndroidWebViewController extends _i1.Mock _i7.OnGeolocationPermissionsHidePrompt? onHidePrompt, }) => (super.noSuchMethod( - Invocation.method( - #setGeolocationPermissionsPromptCallbacks, - [], - { - #onShowPrompt: onShowPrompt, - #onHidePrompt: onHidePrompt, - }, - ), + Invocation.method(#setGeolocationPermissionsPromptCallbacks, [], { + #onShowPrompt: onShowPrompt, + #onHidePrompt: onHidePrompt, + }), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -869,75 +625,66 @@ class MockAndroidWebViewController extends _i1.Mock required _i7.OnHideCustomWidgetCallback? onHideCustomWidget, }) => (super.noSuchMethod( - Invocation.method( - #setCustomWidgetCallbacks, - [], - { - #onShowCustomWidget: onShowCustomWidget, - #onHideCustomWidget: onHideCustomWidget, - }, - ), + Invocation.method(#setCustomWidgetCallbacks, [], { + #onShowCustomWidget: onShowCustomWidget, + #onHideCustomWidget: onHideCustomWidget, + }), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setOnConsoleMessage( - void Function(_i3.JavaScriptConsoleMessage)? onConsoleMessage) => + void Function(_i3.JavaScriptConsoleMessage)? onConsoleMessage, + ) => (super.noSuchMethod( - Invocation.method( - #setOnConsoleMessage, - [onConsoleMessage], - ), + Invocation.method(#setOnConsoleMessage, [onConsoleMessage]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future getUserAgent() => (super.noSuchMethod( - Invocation.method( - #getUserAgent, - [], - ), + Invocation.method(#getUserAgent, []), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setOnJavaScriptAlertDialog( - _i8.Future Function(_i3.JavaScriptAlertDialogRequest)? - onJavaScriptAlertDialog) => + _i8.Future Function(_i3.JavaScriptAlertDialogRequest)? + onJavaScriptAlertDialog, + ) => (super.noSuchMethod( - Invocation.method( - #setOnJavaScriptAlertDialog, - [onJavaScriptAlertDialog], - ), + Invocation.method(#setOnJavaScriptAlertDialog, [ + onJavaScriptAlertDialog, + ]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setOnJavaScriptConfirmDialog( - _i8.Future Function(_i3.JavaScriptConfirmDialogRequest)? - onJavaScriptConfirmDialog) => + _i8.Future Function(_i3.JavaScriptConfirmDialogRequest)? + onJavaScriptConfirmDialog, + ) => (super.noSuchMethod( - Invocation.method( - #setOnJavaScriptConfirmDialog, - [onJavaScriptConfirmDialog], - ), + Invocation.method(#setOnJavaScriptConfirmDialog, [ + onJavaScriptConfirmDialog, + ]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setOnJavaScriptTextInputDialog( - _i8.Future Function(_i3.JavaScriptTextInputDialogRequest)? - onJavaScriptTextInputDialog) => + _i8.Future Function(_i3.JavaScriptTextInputDialogRequest)? + onJavaScriptTextInputDialog, + ) => (super.noSuchMethod( - Invocation.method( - #setOnJavaScriptTextInputDialog, - [onJavaScriptTextInputDialog], - ), + Invocation.method(#setOnJavaScriptTextInputDialog, [ + onJavaScriptTextInputDialog, + ]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -949,63 +696,31 @@ class MockAndroidWebViewController extends _i1.Mock class MockAndroidWebViewProxy extends _i1.Mock implements _i9.AndroidWebViewProxy { @override - _i2.WebView Function( - {void Function( - _i2.WebView, - int, - int, - int, - int, - )? onScrollChanged}) get newWebView => (super.noSuchMethod( + _i2.WebView Function({ + void Function(_i2.WebView, int, int, int, int)? onScrollChanged, + }) get newWebView => (super.noSuchMethod( Invocation.getter(#newWebView), - returnValue: ( - {void Function( - _i2.WebView, - int, - int, - int, - int, - )? onScrollChanged}) => - _FakeWebView_7( - this, - Invocation.getter(#newWebView), - ), - returnValueForMissingStub: ( - {void Function( - _i2.WebView, - int, - int, - int, - int, - )? onScrollChanged}) => - _FakeWebView_7( - this, - Invocation.getter(#newWebView), - ), - ) as _i2.WebView Function( - {void Function( - _i2.WebView, - int, - int, - int, - int, - )? onScrollChanged})); + returnValue: ({ + void Function(_i2.WebView, int, int, int, int)? onScrollChanged, + }) => + _FakeWebView_7(this, Invocation.getter(#newWebView)), + returnValueForMissingStub: ({ + void Function(_i2.WebView, int, int, int, int)? onScrollChanged, + }) => + _FakeWebView_7(this, Invocation.getter(#newWebView)), + ) as _i2.WebView Function({ + void Function(_i2.WebView, int, int, int, int)? onScrollChanged, + })); @override _i2.JavaScriptChannel Function({ required String channelName, - required void Function( - _i2.JavaScriptChannel, - String, - ) postMessage, + required void Function(_i2.JavaScriptChannel, String) postMessage, }) get newJavaScriptChannel => (super.noSuchMethod( Invocation.getter(#newJavaScriptChannel), returnValue: ({ required String channelName, - required void Function( - _i2.JavaScriptChannel, - String, - ) postMessage, + required void Function(_i2.JavaScriptChannel, String) postMessage, }) => _FakeJavaScriptChannel_8( this, @@ -1013,10 +728,7 @@ class MockAndroidWebViewProxy extends _i1.Mock ), returnValueForMissingStub: ({ required String channelName, - required void Function( - _i2.JavaScriptChannel, - String, - ) postMessage, + required void Function(_i2.JavaScriptChannel, String) postMessage, }) => _FakeJavaScriptChannel_8( this, @@ -1024,37 +736,27 @@ class MockAndroidWebViewProxy extends _i1.Mock ), ) as _i2.JavaScriptChannel Function({ required String channelName, - required void Function( - _i2.JavaScriptChannel, - String, - ) postMessage, + required void Function(_i2.JavaScriptChannel, String) postMessage, })); @override _i2.WebViewClient Function({ + void Function(_i2.WebViewClient, _i2.WebView, String, bool)? + doUpdateVisitedHistory, void Function( _i2.WebViewClient, _i2.WebView, - String, - bool, - )? doUpdateVisitedHistory, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onPageFinished, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onPageStarted, - void Function( - _i2.WebViewClient, - _i2.WebView, - int, - String, - String, - )? onReceivedError, + _i2.AndroidMessage, + _i2.AndroidMessage, + )? onFormResubmission, + void Function(_i2.WebViewClient, _i2.WebView, String)? onLoadResource, + void Function(_i2.WebViewClient, _i2.WebView, String)? onPageCommitVisible, + void Function(_i2.WebViewClient, _i2.WebView, String)? onPageFinished, + void Function(_i2.WebViewClient, _i2.WebView, String)? onPageStarted, + void Function(_i2.WebViewClient, _i2.WebView, _i2.ClientCertRequest)? + onReceivedClientCertRequest, + void Function(_i2.WebViewClient, _i2.WebView, int, String, String)? + onReceivedError, void Function( _i2.WebViewClient, _i2.WebView, @@ -1068,6 +770,8 @@ class MockAndroidWebViewProxy extends _i1.Mock _i2.WebResourceRequest, _i2.WebResourceResponse, )? onReceivedHttpError, + void Function(_i2.WebViewClient, _i2.WebView, String, String?, String)? + onReceivedLoginRequest, void Function( _i2.WebViewClient, _i2.WebView, @@ -1083,32 +787,35 @@ class MockAndroidWebViewProxy extends _i1.Mock void Function( _i2.WebViewClient, _i2.WebView, - _i2.WebResourceRequest, - )? requestLoading, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? urlLoading, + _i2.SslErrorHandler, + _i2.SslError, + )? onReceivedSslError, + void Function(_i2.WebViewClient, _i2.WebView, double, double)? + onScaleChanged, + void Function(_i2.WebViewClient, _i2.WebView, _i2.WebResourceRequest)? + requestLoading, + void Function(_i2.WebViewClient, _i2.WebView, String)? urlLoading, }) get newWebViewClient => (super.noSuchMethod( Invocation.getter(#newWebViewClient), returnValue: ({ + void Function(_i2.WebViewClient, _i2.WebView, String, bool)? + doUpdateVisitedHistory, void Function( _i2.WebViewClient, _i2.WebView, - String, - bool, - )? doUpdateVisitedHistory, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onPageFinished, + _i2.AndroidMessage, + _i2.AndroidMessage, + )? onFormResubmission, + void Function(_i2.WebViewClient, _i2.WebView, String)? onLoadResource, + void Function(_i2.WebViewClient, _i2.WebView, String)? + onPageCommitVisible, + void Function(_i2.WebViewClient, _i2.WebView, String)? onPageFinished, + void Function(_i2.WebViewClient, _i2.WebView, String)? onPageStarted, void Function( _i2.WebViewClient, _i2.WebView, - String, - )? onPageStarted, + _i2.ClientCertRequest, + )? onReceivedClientCertRequest, void Function( _i2.WebViewClient, _i2.WebView, @@ -1129,6 +836,13 @@ class MockAndroidWebViewProxy extends _i1.Mock _i2.WebResourceRequest, _i2.WebResourceResponse, )? onReceivedHttpError, + void Function( + _i2.WebViewClient, + _i2.WebView, + String, + String?, + String, + )? onReceivedLoginRequest, void Function( _i2.WebViewClient, _i2.WebView, @@ -1144,35 +858,41 @@ class MockAndroidWebViewProxy extends _i1.Mock void Function( _i2.WebViewClient, _i2.WebView, - _i2.WebResourceRequest, - )? requestLoading, + _i2.SslErrorHandler, + _i2.SslError, + )? onReceivedSslError, + void Function(_i2.WebViewClient, _i2.WebView, double, double)? + onScaleChanged, void Function( _i2.WebViewClient, _i2.WebView, - String, - )? urlLoading, + _i2.WebResourceRequest, + )? requestLoading, + void Function(_i2.WebViewClient, _i2.WebView, String)? urlLoading, }) => _FakeWebViewClient_1( this, Invocation.getter(#newWebViewClient), ), returnValueForMissingStub: ({ + void Function(_i2.WebViewClient, _i2.WebView, String, bool)? + doUpdateVisitedHistory, void Function( _i2.WebViewClient, _i2.WebView, - String, - bool, - )? doUpdateVisitedHistory, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onPageFinished, + _i2.AndroidMessage, + _i2.AndroidMessage, + )? onFormResubmission, + void Function(_i2.WebViewClient, _i2.WebView, String)? onLoadResource, + void Function(_i2.WebViewClient, _i2.WebView, String)? + onPageCommitVisible, + void Function(_i2.WebViewClient, _i2.WebView, String)? onPageFinished, + void Function(_i2.WebViewClient, _i2.WebView, String)? onPageStarted, void Function( _i2.WebViewClient, _i2.WebView, - String, - )? onPageStarted, + _i2.ClientCertRequest, + )? onReceivedClientCertRequest, void Function( _i2.WebViewClient, _i2.WebView, @@ -1193,6 +913,13 @@ class MockAndroidWebViewProxy extends _i1.Mock _i2.WebResourceRequest, _i2.WebResourceResponse, )? onReceivedHttpError, + void Function( + _i2.WebViewClient, + _i2.WebView, + String, + String?, + String, + )? onReceivedLoginRequest, void Function( _i2.WebViewClient, _i2.WebView, @@ -1208,42 +935,43 @@ class MockAndroidWebViewProxy extends _i1.Mock void Function( _i2.WebViewClient, _i2.WebView, - _i2.WebResourceRequest, - )? requestLoading, + _i2.SslErrorHandler, + _i2.SslError, + )? onReceivedSslError, + void Function(_i2.WebViewClient, _i2.WebView, double, double)? + onScaleChanged, void Function( _i2.WebViewClient, _i2.WebView, - String, - )? urlLoading, + _i2.WebResourceRequest, + )? requestLoading, + void Function(_i2.WebViewClient, _i2.WebView, String)? urlLoading, }) => _FakeWebViewClient_1( this, Invocation.getter(#newWebViewClient), ), ) as _i2.WebViewClient Function({ + void Function(_i2.WebViewClient, _i2.WebView, String, bool)? + doUpdateVisitedHistory, void Function( _i2.WebViewClient, _i2.WebView, - String, - bool, - )? doUpdateVisitedHistory, + _i2.AndroidMessage, + _i2.AndroidMessage, + )? onFormResubmission, + void Function(_i2.WebViewClient, _i2.WebView, String)? onLoadResource, + void Function(_i2.WebViewClient, _i2.WebView, String)? + onPageCommitVisible, + void Function(_i2.WebViewClient, _i2.WebView, String)? onPageFinished, + void Function(_i2.WebViewClient, _i2.WebView, String)? onPageStarted, void Function( _i2.WebViewClient, _i2.WebView, - String, - )? onPageFinished, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onPageStarted, - void Function( - _i2.WebViewClient, - _i2.WebView, - int, - String, - String, - )? onReceivedError, + _i2.ClientCertRequest, + )? onReceivedClientCertRequest, + void Function(_i2.WebViewClient, _i2.WebView, int, String, String)? + onReceivedError, void Function( _i2.WebViewClient, _i2.WebView, @@ -1257,6 +985,13 @@ class MockAndroidWebViewProxy extends _i1.Mock _i2.WebResourceRequest, _i2.WebResourceResponse, )? onReceivedHttpError, + void Function( + _i2.WebViewClient, + _i2.WebView, + String, + String?, + String, + )? onReceivedLoginRequest, void Function( _i2.WebViewClient, _i2.WebView, @@ -1272,68 +1007,84 @@ class MockAndroidWebViewProxy extends _i1.Mock void Function( _i2.WebViewClient, _i2.WebView, - _i2.WebResourceRequest, - )? requestLoading, + _i2.SslErrorHandler, + _i2.SslError, + )? onReceivedSslError, + void Function(_i2.WebViewClient, _i2.WebView, double, double)? + onScaleChanged, void Function( _i2.WebViewClient, _i2.WebView, - String, - )? urlLoading, + _i2.WebResourceRequest, + )? requestLoading, + void Function(_i2.WebViewClient, _i2.WebView, String)? urlLoading, })); @override - _i2.DownloadListener Function( - {required void Function( - _i2.DownloadListener, - String, - String, - String, - String, - int, - ) onDownloadStart}) get newDownloadListener => (super.noSuchMethod( + _i2.DownloadListener Function({ + required void Function( + _i2.DownloadListener, + String, + String, + String, + String, + int, + ) onDownloadStart, + }) get newDownloadListener => (super.noSuchMethod( Invocation.getter(#newDownloadListener), - returnValue: ( - {required void Function( - _i2.DownloadListener, - String, - String, - String, - String, - int, - ) onDownloadStart}) => - _FakeDownloadListener_2( - this, - Invocation.getter(#newDownloadListener), - ), - returnValueForMissingStub: ( - {required void Function( - _i2.DownloadListener, - String, - String, - String, - String, - int, - ) onDownloadStart}) => + returnValue: ({ + required void Function( + _i2.DownloadListener, + String, + String, + String, + String, + int, + ) onDownloadStart, + }) => _FakeDownloadListener_2( this, Invocation.getter(#newDownloadListener), ), - ) as _i2.DownloadListener Function( - {required void Function( + returnValueForMissingStub: ({ + required void Function( _i2.DownloadListener, String, String, String, String, int, - ) onDownloadStart})); + ) onDownloadStart, + }) => + _FakeDownloadListener_2( + this, + Invocation.getter(#newDownloadListener), + ), + ) as _i2.DownloadListener Function({ + required void Function( + _i2.DownloadListener, + String, + String, + String, + String, + int, + ) onDownloadStart, + })); @override _i2.WebChromeClient Function({ - void Function( + required _i8.Future Function( + _i2.WebChromeClient, + _i2.WebView, + String, + String, + ) onJsConfirm, + required _i8.Future> Function( _i2.WebChromeClient, - _i2.ConsoleMessage, - )? onConsoleMessage, + _i2.WebView, + _i2.FileChooserParams, + ) onShowFileChooser, + void Function(_i2.WebChromeClient, _i2.ConsoleMessage)? onConsoleMessage, void Function(_i2.WebChromeClient)? onGeolocationPermissionsHidePrompt, void Function( _i2.WebChromeClient, @@ -1341,18 +1092,8 @@ class MockAndroidWebViewProxy extends _i1.Mock _i2.GeolocationPermissionsCallback, )? onGeolocationPermissionsShowPrompt, void Function(_i2.WebChromeClient)? onHideCustomView, - _i8.Future Function( - _i2.WebChromeClient, - _i2.WebView, - String, - String, - )? onJsAlert, - _i8.Future Function( - _i2.WebChromeClient, - _i2.WebView, - String, - String, - )? onJsConfirm, + _i8.Future Function(_i2.WebChromeClient, _i2.WebView, String, String)? + onJsAlert, _i8.Future Function( _i2.WebChromeClient, _i2.WebView, @@ -1360,32 +1101,16 @@ class MockAndroidWebViewProxy extends _i1.Mock String, String, )? onJsPrompt, - void Function( - _i2.WebChromeClient, - _i2.PermissionRequest, - )? onPermissionRequest, - void Function( - _i2.WebChromeClient, - _i2.WebView, - int, - )? onProgressChanged, - void Function( - _i2.WebChromeClient, - _i2.View, - _i2.CustomViewCallback, - )? onShowCustomView, - _i8.Future> Function( - _i2.WebChromeClient, - _i2.WebView, - _i2.FileChooserParams, - )? onShowFileChooser, + void Function(_i2.WebChromeClient, _i2.PermissionRequest)? + onPermissionRequest, + void Function(_i2.WebChromeClient, _i2.WebView, int)? onProgressChanged, + void Function(_i2.WebChromeClient, _i2.View, _i2.CustomViewCallback)? + onShowCustomView, }) get newWebChromeClient => (super.noSuchMethod( Invocation.getter(#newWebChromeClient), returnValue: ({ - void Function( - _i2.WebChromeClient, - _i2.ConsoleMessage, - )? onConsoleMessage, + void Function(_i2.WebChromeClient, _i2.ConsoleMessage)? + onConsoleMessage, void Function(_i2.WebChromeClient)? onGeolocationPermissionsHidePrompt, void Function( @@ -1400,12 +1125,12 @@ class MockAndroidWebViewProxy extends _i1.Mock String, String, )? onJsAlert, - _i8.Future Function( + required _i8.Future Function( _i2.WebChromeClient, _i2.WebView, String, String, - )? onJsConfirm, + ) onJsConfirm, _i8.Future Function( _i2.WebChromeClient, _i2.WebView, @@ -1413,35 +1138,28 @@ class MockAndroidWebViewProxy extends _i1.Mock String, String, )? onJsPrompt, - void Function( - _i2.WebChromeClient, - _i2.PermissionRequest, - )? onPermissionRequest, - void Function( - _i2.WebChromeClient, - _i2.WebView, - int, - )? onProgressChanged, + void Function(_i2.WebChromeClient, _i2.PermissionRequest)? + onPermissionRequest, + void Function(_i2.WebChromeClient, _i2.WebView, int)? + onProgressChanged, void Function( _i2.WebChromeClient, _i2.View, _i2.CustomViewCallback, )? onShowCustomView, - _i8.Future> Function( + required _i8.Future> Function( _i2.WebChromeClient, _i2.WebView, _i2.FileChooserParams, - )? onShowFileChooser, + ) onShowFileChooser, }) => _FakeWebChromeClient_0( this, Invocation.getter(#newWebChromeClient), ), returnValueForMissingStub: ({ - void Function( - _i2.WebChromeClient, - _i2.ConsoleMessage, - )? onConsoleMessage, + void Function(_i2.WebChromeClient, _i2.ConsoleMessage)? + onConsoleMessage, void Function(_i2.WebChromeClient)? onGeolocationPermissionsHidePrompt, void Function( @@ -1456,12 +1174,12 @@ class MockAndroidWebViewProxy extends _i1.Mock String, String, )? onJsAlert, - _i8.Future Function( + required _i8.Future Function( _i2.WebChromeClient, _i2.WebView, String, String, - )? onJsConfirm, + ) onJsConfirm, _i8.Future Function( _i2.WebChromeClient, _i2.WebView, @@ -1469,35 +1187,39 @@ class MockAndroidWebViewProxy extends _i1.Mock String, String, )? onJsPrompt, - void Function( - _i2.WebChromeClient, - _i2.PermissionRequest, - )? onPermissionRequest, - void Function( - _i2.WebChromeClient, - _i2.WebView, - int, - )? onProgressChanged, + void Function(_i2.WebChromeClient, _i2.PermissionRequest)? + onPermissionRequest, + void Function(_i2.WebChromeClient, _i2.WebView, int)? + onProgressChanged, void Function( _i2.WebChromeClient, _i2.View, _i2.CustomViewCallback, )? onShowCustomView, - _i8.Future> Function( + required _i8.Future> Function( _i2.WebChromeClient, _i2.WebView, _i2.FileChooserParams, - )? onShowFileChooser, + ) onShowFileChooser, }) => _FakeWebChromeClient_0( this, Invocation.getter(#newWebChromeClient), ), ) as _i2.WebChromeClient Function({ - void Function( + required _i8.Future Function( + _i2.WebChromeClient, + _i2.WebView, + String, + String, + ) onJsConfirm, + required _i8.Future> Function( _i2.WebChromeClient, - _i2.ConsoleMessage, - )? onConsoleMessage, + _i2.WebView, + _i2.FileChooserParams, + ) onShowFileChooser, + void Function(_i2.WebChromeClient, _i2.ConsoleMessage)? + onConsoleMessage, void Function(_i2.WebChromeClient)? onGeolocationPermissionsHidePrompt, void Function( _i2.WebChromeClient, @@ -1511,12 +1233,6 @@ class MockAndroidWebViewProxy extends _i1.Mock String, String, )? onJsAlert, - _i8.Future Function( - _i2.WebChromeClient, - _i2.WebView, - String, - String, - )? onJsConfirm, _i8.Future Function( _i2.WebChromeClient, _i2.WebView, @@ -1524,25 +1240,14 @@ class MockAndroidWebViewProxy extends _i1.Mock String, String, )? onJsPrompt, - void Function( - _i2.WebChromeClient, - _i2.PermissionRequest, - )? onPermissionRequest, - void Function( - _i2.WebChromeClient, - _i2.WebView, - int, - )? onProgressChanged, + void Function(_i2.WebChromeClient, _i2.PermissionRequest)? + onPermissionRequest, + void Function(_i2.WebChromeClient, _i2.WebView, int)? onProgressChanged, void Function( _i2.WebChromeClient, _i2.View, _i2.CustomViewCallback, )? onShowCustomView, - _i8.Future> Function( - _i2.WebChromeClient, - _i2.WebView, - _i2.FileChooserParams, - )? onShowFileChooser, })); @override @@ -1693,22 +1398,15 @@ class MockExpensiveAndroidViewController extends _i1.Mock @override _i6.PointTransformer get pointTransformer => (super.noSuchMethod( Invocation.getter(#pointTransformer), - returnValue: (_i4.Offset position) => _FakeOffset_6( - this, - Invocation.getter(#pointTransformer), - ), - returnValueForMissingStub: (_i4.Offset position) => _FakeOffset_6( - this, - Invocation.getter(#pointTransformer), - ), + returnValue: (_i4.Offset position) => + _FakeOffset_6(this, Invocation.getter(#pointTransformer)), + returnValueForMissingStub: (_i4.Offset position) => + _FakeOffset_6(this, Invocation.getter(#pointTransformer)), ) as _i6.PointTransformer); @override set pointTransformer(_i6.PointTransformer? transformer) => super.noSuchMethod( - Invocation.setter( - #pointTransformer, - transformer, - ), + Invocation.setter(#pointTransformer, transformer), returnValueForMissingStub: null, ); @@ -1729,94 +1427,60 @@ class MockExpensiveAndroidViewController extends _i1.Mock @override _i8.Future setOffset(_i4.Offset? off) => (super.noSuchMethod( - Invocation.method( - #setOffset, - [off], - ), + Invocation.method(#setOffset, [off]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override - _i8.Future create({ - _i4.Size? size, - _i4.Offset? position, - }) => + _i8.Future create({_i4.Size? size, _i4.Offset? position}) => (super.noSuchMethod( - Invocation.method( - #create, - [], - { - #size: size, - #position: position, - }, - ), + Invocation.method(#create, [], {#size: size, #position: position}), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future<_i4.Size> setSize(_i4.Size? size) => (super.noSuchMethod( - Invocation.method( - #setSize, - [size], + Invocation.method(#setSize, [size]), + returnValue: _i8.Future<_i4.Size>.value( + _FakeSize_15(this, Invocation.method(#setSize, [size])), + ), + returnValueForMissingStub: _i8.Future<_i4.Size>.value( + _FakeSize_15(this, Invocation.method(#setSize, [size])), ), - returnValue: _i8.Future<_i4.Size>.value(_FakeSize_15( - this, - Invocation.method( - #setSize, - [size], - ), - )), - returnValueForMissingStub: _i8.Future<_i4.Size>.value(_FakeSize_15( - this, - Invocation.method( - #setSize, - [size], - ), - )), ) as _i8.Future<_i4.Size>); @override _i8.Future sendMotionEvent(_i6.AndroidMotionEvent? event) => (super.noSuchMethod( - Invocation.method( - #sendMotionEvent, - [event], - ), + Invocation.method(#sendMotionEvent, [event]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override void addOnPlatformViewCreatedListener( - _i6.PlatformViewCreatedCallback? listener) => + _i6.PlatformViewCreatedCallback? listener, + ) => super.noSuchMethod( - Invocation.method( - #addOnPlatformViewCreatedListener, - [listener], - ), + Invocation.method(#addOnPlatformViewCreatedListener, [listener]), returnValueForMissingStub: null, ); @override void removeOnPlatformViewCreatedListener( - _i6.PlatformViewCreatedCallback? listener) => + _i6.PlatformViewCreatedCallback? listener, + ) => super.noSuchMethod( - Invocation.method( - #removeOnPlatformViewCreatedListener, - [listener], - ), + Invocation.method(#removeOnPlatformViewCreatedListener, [listener]), returnValueForMissingStub: null, ); @override _i8.Future setLayoutDirection(_i4.TextDirection? layoutDirection) => (super.noSuchMethod( - Invocation.method( - #setLayoutDirection, - [layoutDirection], - ), + Invocation.method(#setLayoutDirection, [layoutDirection]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -1824,30 +1488,21 @@ class MockExpensiveAndroidViewController extends _i1.Mock @override _i8.Future dispatchPointerEvent(_i11.PointerEvent? event) => (super.noSuchMethod( - Invocation.method( - #dispatchPointerEvent, - [event], - ), + Invocation.method(#dispatchPointerEvent, [event]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future clearFocus() => (super.noSuchMethod( - Invocation.method( - #clearFocus, - [], - ), + Invocation.method(#clearFocus, []), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future dispose() => (super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -1873,57 +1528,41 @@ class MockFlutterAssetManager extends _i1.Mock @override _i8.Future> list(String? path) => (super.noSuchMethod( - Invocation.method( - #list, - [path], - ), + Invocation.method(#list, [path]), returnValue: _i8.Future>.value([]), - returnValueForMissingStub: _i8.Future>.value([]), + returnValueForMissingStub: _i8.Future>.value( + [], + ), ) as _i8.Future>); @override _i8.Future getAssetFilePathByName(String? name) => (super.noSuchMethod( - Invocation.method( - #getAssetFilePathByName, - [name], - ), - returnValue: _i8.Future.value(_i12.dummyValue( - this, - Invocation.method( - #getAssetFilePathByName, - [name], + Invocation.method(#getAssetFilePathByName, [name]), + returnValue: _i8.Future.value( + _i12.dummyValue( + this, + Invocation.method(#getAssetFilePathByName, [name]), ), - )), - returnValueForMissingStub: - _i8.Future.value(_i12.dummyValue( - this, - Invocation.method( - #getAssetFilePathByName, - [name], + ), + returnValueForMissingStub: _i8.Future.value( + _i12.dummyValue( + this, + Invocation.method(#getAssetFilePathByName, [name]), ), - )), + ), ) as _i8.Future); @override _i2.FlutterAssetManager pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), returnValue: _FakeFlutterAssetManager_10( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), returnValueForMissingStub: _FakeFlutterAssetManager_10( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), ) as _i2.FlutterAssetManager); } @@ -1947,43 +1586,23 @@ class MockGeolocationPermissionsCallback extends _i1.Mock ) as _i2.PigeonInstanceManager); @override - _i8.Future invoke( - String? origin, - bool? allow, - bool? retain, - ) => + _i8.Future invoke(String? origin, bool? allow, bool? retain) => (super.noSuchMethod( - Invocation.method( - #invoke, - [ - origin, - allow, - retain, - ], - ), + Invocation.method(#invoke, [origin, allow, retain]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i2.GeolocationPermissionsCallback pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), returnValue: _FakeGeolocationPermissionsCallback_16( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), returnValueForMissingStub: _FakeGeolocationPermissionsCallback_16( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), ) as _i2.GeolocationPermissionsCallback); } @@ -2006,23 +1625,13 @@ class MockJavaScriptChannel extends _i1.Mock implements _i2.JavaScriptChannel { ) as String); @override - void Function( - _i2.JavaScriptChannel, - String, - ) get postMessage => (super.noSuchMethod( + void Function(_i2.JavaScriptChannel, String) get postMessage => + (super.noSuchMethod( Invocation.getter(#postMessage), - returnValue: ( - _i2.JavaScriptChannel pigeon_instance, - String message, - ) {}, - returnValueForMissingStub: ( - _i2.JavaScriptChannel pigeon_instance, - String message, - ) {}, - ) as void Function( - _i2.JavaScriptChannel, - String, - )); + returnValue: (_i2.JavaScriptChannel pigeon_instance, String message) {}, + returnValueForMissingStub: + (_i2.JavaScriptChannel pigeon_instance, String message) {}, + ) as void Function(_i2.JavaScriptChannel, String)); @override _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( @@ -2039,23 +1648,14 @@ class MockJavaScriptChannel extends _i1.Mock implements _i2.JavaScriptChannel { @override _i2.JavaScriptChannel pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), returnValue: _FakeJavaScriptChannel_8( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), returnValueForMissingStub: _FakeJavaScriptChannel_8( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), ) as _i2.JavaScriptChannel); } @@ -2086,43 +1686,28 @@ class MockPermissionRequest extends _i1.Mock implements _i2.PermissionRequest { @override _i8.Future grant(List? resources) => (super.noSuchMethod( - Invocation.method( - #grant, - [resources], - ), + Invocation.method(#grant, [resources]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future deny() => (super.noSuchMethod( - Invocation.method( - #deny, - [], - ), + Invocation.method(#deny, []), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i2.PermissionRequest pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), returnValue: _FakePermissionRequest_17( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), returnValueForMissingStub: _FakePermissionRequest_17( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), ) as _i2.PermissionRequest); } @@ -2143,47 +1728,35 @@ class MockPlatformViewsServiceProxy extends _i1.Mock _i4.VoidCallback? onFocus, }) => (super.noSuchMethod( - Invocation.method( - #initExpensiveAndroidView, - [], - { + Invocation.method(#initExpensiveAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + returnValue: _FakeExpensiveAndroidViewController_18( + this, + Invocation.method(#initExpensiveAndroidView, [], { #id: id, #viewType: viewType, #layoutDirection: layoutDirection, #creationParams: creationParams, #creationParamsCodec: creationParamsCodec, #onFocus: onFocus, - }, - ), - returnValue: _FakeExpensiveAndroidViewController_18( - this, - Invocation.method( - #initExpensiveAndroidView, - [], - { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }, - ), + }), ), returnValueForMissingStub: _FakeExpensiveAndroidViewController_18( this, - Invocation.method( - #initExpensiveAndroidView, - [], - { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }, - ), + Invocation.method(#initExpensiveAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), ), ) as _i6.ExpensiveAndroidViewController); @@ -2197,47 +1770,35 @@ class MockPlatformViewsServiceProxy extends _i1.Mock _i4.VoidCallback? onFocus, }) => (super.noSuchMethod( - Invocation.method( - #initSurfaceAndroidView, - [], - { + Invocation.method(#initSurfaceAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), + returnValue: _FakeSurfaceAndroidViewController_19( + this, + Invocation.method(#initSurfaceAndroidView, [], { #id: id, #viewType: viewType, #layoutDirection: layoutDirection, #creationParams: creationParams, #creationParamsCodec: creationParamsCodec, #onFocus: onFocus, - }, - ), - returnValue: _FakeSurfaceAndroidViewController_19( - this, - Invocation.method( - #initSurfaceAndroidView, - [], - { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }, - ), + }), ), returnValueForMissingStub: _FakeSurfaceAndroidViewController_19( this, - Invocation.method( - #initSurfaceAndroidView, - [], - { - #id: id, - #viewType: viewType, - #layoutDirection: layoutDirection, - #creationParams: creationParams, - #creationParamsCodec: creationParamsCodec, - #onFocus: onFocus, - }, - ), + Invocation.method(#initSurfaceAndroidView, [], { + #id: id, + #viewType: viewType, + #layoutDirection: layoutDirection, + #creationParams: creationParams, + #creationParamsCodec: creationParamsCodec, + #onFocus: onFocus, + }), ), ) as _i6.SurfaceAndroidViewController); } @@ -2271,22 +1832,15 @@ class MockSurfaceAndroidViewController extends _i1.Mock @override _i6.PointTransformer get pointTransformer => (super.noSuchMethod( Invocation.getter(#pointTransformer), - returnValue: (_i4.Offset position) => _FakeOffset_6( - this, - Invocation.getter(#pointTransformer), - ), - returnValueForMissingStub: (_i4.Offset position) => _FakeOffset_6( - this, - Invocation.getter(#pointTransformer), - ), + returnValue: (_i4.Offset position) => + _FakeOffset_6(this, Invocation.getter(#pointTransformer)), + returnValueForMissingStub: (_i4.Offset position) => + _FakeOffset_6(this, Invocation.getter(#pointTransformer)), ) as _i6.PointTransformer); @override set pointTransformer(_i6.PointTransformer? transformer) => super.noSuchMethod( - Invocation.setter( - #pointTransformer, - transformer, - ), + Invocation.setter(#pointTransformer, transformer), returnValueForMissingStub: null, ); @@ -2307,94 +1861,60 @@ class MockSurfaceAndroidViewController extends _i1.Mock @override _i8.Future setOffset(_i4.Offset? off) => (super.noSuchMethod( - Invocation.method( - #setOffset, - [off], - ), + Invocation.method(#setOffset, [off]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override - _i8.Future create({ - _i4.Size? size, - _i4.Offset? position, - }) => + _i8.Future create({_i4.Size? size, _i4.Offset? position}) => (super.noSuchMethod( - Invocation.method( - #create, - [], - { - #size: size, - #position: position, - }, - ), + Invocation.method(#create, [], {#size: size, #position: position}), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future<_i4.Size> setSize(_i4.Size? size) => (super.noSuchMethod( - Invocation.method( - #setSize, - [size], + Invocation.method(#setSize, [size]), + returnValue: _i8.Future<_i4.Size>.value( + _FakeSize_15(this, Invocation.method(#setSize, [size])), + ), + returnValueForMissingStub: _i8.Future<_i4.Size>.value( + _FakeSize_15(this, Invocation.method(#setSize, [size])), ), - returnValue: _i8.Future<_i4.Size>.value(_FakeSize_15( - this, - Invocation.method( - #setSize, - [size], - ), - )), - returnValueForMissingStub: _i8.Future<_i4.Size>.value(_FakeSize_15( - this, - Invocation.method( - #setSize, - [size], - ), - )), ) as _i8.Future<_i4.Size>); @override _i8.Future sendMotionEvent(_i6.AndroidMotionEvent? event) => (super.noSuchMethod( - Invocation.method( - #sendMotionEvent, - [event], - ), + Invocation.method(#sendMotionEvent, [event]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override void addOnPlatformViewCreatedListener( - _i6.PlatformViewCreatedCallback? listener) => + _i6.PlatformViewCreatedCallback? listener, + ) => super.noSuchMethod( - Invocation.method( - #addOnPlatformViewCreatedListener, - [listener], - ), + Invocation.method(#addOnPlatformViewCreatedListener, [listener]), returnValueForMissingStub: null, ); @override void removeOnPlatformViewCreatedListener( - _i6.PlatformViewCreatedCallback? listener) => + _i6.PlatformViewCreatedCallback? listener, + ) => super.noSuchMethod( - Invocation.method( - #removeOnPlatformViewCreatedListener, - [listener], - ), + Invocation.method(#removeOnPlatformViewCreatedListener, [listener]), returnValueForMissingStub: null, ); @override _i8.Future setLayoutDirection(_i4.TextDirection? layoutDirection) => (super.noSuchMethod( - Invocation.method( - #setLayoutDirection, - [layoutDirection], - ), + Invocation.method(#setLayoutDirection, [layoutDirection]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -2402,30 +1922,21 @@ class MockSurfaceAndroidViewController extends _i1.Mock @override _i8.Future dispatchPointerEvent(_i11.PointerEvent? event) => (super.noSuchMethod( - Invocation.method( - #dispatchPointerEvent, - [event], - ), + Invocation.method(#dispatchPointerEvent, [event]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future clearFocus() => (super.noSuchMethod( - Invocation.method( - #clearFocus, - [], - ), + Invocation.method(#clearFocus, []), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future dispose() => (super.noSuchMethod( - Invocation.method( - #dispose, - [], - ), + Invocation.method(#dispose, []), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -2435,6 +1946,56 @@ class MockSurfaceAndroidViewController extends _i1.Mock /// /// See the documentation for Mockito's code generation for more information. class MockWebChromeClient extends _i1.Mock implements _i2.WebChromeClient { + @override + _i8.Future> Function( + _i2.WebChromeClient, + _i2.WebView, + _i2.FileChooserParams, + ) get onShowFileChooser => (super.noSuchMethod( + Invocation.getter(#onShowFileChooser), + returnValue: ( + _i2.WebChromeClient pigeon_instance, + _i2.WebView webView, + _i2.FileChooserParams params, + ) => + _i8.Future>.value([]), + returnValueForMissingStub: ( + _i2.WebChromeClient pigeon_instance, + _i2.WebView webView, + _i2.FileChooserParams params, + ) => + _i8.Future>.value([]), + ) as _i8.Future> Function( + _i2.WebChromeClient, + _i2.WebView, + _i2.FileChooserParams, + )); + + @override + _i8.Future Function(_i2.WebChromeClient, _i2.WebView, String, String) + get onJsConfirm => (super.noSuchMethod( + Invocation.getter(#onJsConfirm), + returnValue: ( + _i2.WebChromeClient pigeon_instance, + _i2.WebView webView, + String url, + String message, + ) => + _i8.Future.value(false), + returnValueForMissingStub: ( + _i2.WebChromeClient pigeon_instance, + _i2.WebView webView, + String url, + String message, + ) => + _i8.Future.value(false), + ) as _i8.Future Function( + _i2.WebChromeClient, + _i2.WebView, + String, + String, + )); + @override _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( Invocation.getter(#pigeon_instanceManager), @@ -2451,10 +2012,9 @@ class MockWebChromeClient extends _i1.Mock implements _i2.WebChromeClient { @override _i8.Future setSynchronousReturnValueForOnShowFileChooser(bool? value) => (super.noSuchMethod( - Invocation.method( - #setSynchronousReturnValueForOnShowFileChooser, - [value], - ), + Invocation.method(#setSynchronousReturnValueForOnShowFileChooser, [ + value, + ]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -2462,10 +2022,9 @@ class MockWebChromeClient extends _i1.Mock implements _i2.WebChromeClient { @override _i8.Future setSynchronousReturnValueForOnConsoleMessage(bool? value) => (super.noSuchMethod( - Invocation.method( - #setSynchronousReturnValueForOnConsoleMessage, - [value], - ), + Invocation.method(#setSynchronousReturnValueForOnConsoleMessage, [ + value, + ]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -2473,10 +2032,7 @@ class MockWebChromeClient extends _i1.Mock implements _i2.WebChromeClient { @override _i8.Future setSynchronousReturnValueForOnJsAlert(bool? value) => (super.noSuchMethod( - Invocation.method( - #setSynchronousReturnValueForOnJsAlert, - [value], - ), + Invocation.method(#setSynchronousReturnValueForOnJsAlert, [value]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -2484,10 +2040,9 @@ class MockWebChromeClient extends _i1.Mock implements _i2.WebChromeClient { @override _i8.Future setSynchronousReturnValueForOnJsConfirm(bool? value) => (super.noSuchMethod( - Invocation.method( - #setSynchronousReturnValueForOnJsConfirm, - [value], - ), + Invocation.method(#setSynchronousReturnValueForOnJsConfirm, [ + value, + ]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -2495,33 +2050,21 @@ class MockWebChromeClient extends _i1.Mock implements _i2.WebChromeClient { @override _i8.Future setSynchronousReturnValueForOnJsPrompt(bool? value) => (super.noSuchMethod( - Invocation.method( - #setSynchronousReturnValueForOnJsPrompt, - [value], - ), + Invocation.method(#setSynchronousReturnValueForOnJsPrompt, [value]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i2.WebChromeClient pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), returnValue: _FakeWebChromeClient_0( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), returnValueForMissingStub: _FakeWebChromeClient_0( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), ) as _i2.WebChromeClient); } @@ -2545,10 +2088,7 @@ class MockWebSettings extends _i1.Mock implements _i2.WebSettings { @override _i8.Future setDomStorageEnabled(bool? flag) => (super.noSuchMethod( - Invocation.method( - #setDomStorageEnabled, - [flag], - ), + Invocation.method(#setDomStorageEnabled, [flag]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -2556,10 +2096,9 @@ class MockWebSettings extends _i1.Mock implements _i2.WebSettings { @override _i8.Future setJavaScriptCanOpenWindowsAutomatically(bool? flag) => (super.noSuchMethod( - Invocation.method( - #setJavaScriptCanOpenWindowsAutomatically, - [flag], - ), + Invocation.method(#setJavaScriptCanOpenWindowsAutomatically, [ + flag, + ]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -2567,20 +2106,14 @@ class MockWebSettings extends _i1.Mock implements _i2.WebSettings { @override _i8.Future setSupportMultipleWindows(bool? support) => (super.noSuchMethod( - Invocation.method( - #setSupportMultipleWindows, - [support], - ), + Invocation.method(#setSupportMultipleWindows, [support]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setJavaScriptEnabled(bool? flag) => (super.noSuchMethod( - Invocation.method( - #setJavaScriptEnabled, - [flag], - ), + Invocation.method(#setJavaScriptEnabled, [flag]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -2588,10 +2121,7 @@ class MockWebSettings extends _i1.Mock implements _i2.WebSettings { @override _i8.Future setUserAgentString(String? userAgentString) => (super.noSuchMethod( - Invocation.method( - #setUserAgentString, - [userAgentString], - ), + Invocation.method(#setUserAgentString, [userAgentString]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -2599,20 +2129,14 @@ class MockWebSettings extends _i1.Mock implements _i2.WebSettings { @override _i8.Future setMediaPlaybackRequiresUserGesture(bool? require) => (super.noSuchMethod( - Invocation.method( - #setMediaPlaybackRequiresUserGesture, - [require], - ), + Invocation.method(#setMediaPlaybackRequiresUserGesture, [require]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setSupportZoom(bool? support) => (super.noSuchMethod( - Invocation.method( - #setSupportZoom, - [support], - ), + Invocation.method(#setSupportZoom, [support]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -2620,126 +2144,87 @@ class MockWebSettings extends _i1.Mock implements _i2.WebSettings { @override _i8.Future setLoadWithOverviewMode(bool? overview) => (super.noSuchMethod( - Invocation.method( - #setLoadWithOverviewMode, - [overview], - ), + Invocation.method(#setLoadWithOverviewMode, [overview]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setUseWideViewPort(bool? use) => (super.noSuchMethod( - Invocation.method( - #setUseWideViewPort, - [use], - ), + Invocation.method(#setUseWideViewPort, [use]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setDisplayZoomControls(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setDisplayZoomControls, - [enabled], - ), + Invocation.method(#setDisplayZoomControls, [enabled]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setBuiltInZoomControls(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setBuiltInZoomControls, - [enabled], - ), + Invocation.method(#setBuiltInZoomControls, [enabled]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setAllowFileAccess(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setAllowFileAccess, - [enabled], - ), + Invocation.method(#setAllowFileAccess, [enabled]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setAllowContentAccess(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setAllowContentAccess, - [enabled], - ), + Invocation.method(#setAllowContentAccess, [enabled]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setGeolocationEnabled(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setGeolocationEnabled, - [enabled], - ), + Invocation.method(#setGeolocationEnabled, [enabled]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setTextZoom(int? textZoom) => (super.noSuchMethod( - Invocation.method( - #setTextZoom, - [textZoom], - ), + Invocation.method(#setTextZoom, [textZoom]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future getUserAgentString() => (super.noSuchMethod( - Invocation.method( - #getUserAgentString, - [], - ), - returnValue: _i8.Future.value(_i12.dummyValue( - this, - Invocation.method( - #getUserAgentString, - [], + Invocation.method(#getUserAgentString, []), + returnValue: _i8.Future.value( + _i12.dummyValue( + this, + Invocation.method(#getUserAgentString, []), ), - )), - returnValueForMissingStub: - _i8.Future.value(_i12.dummyValue( - this, - Invocation.method( - #getUserAgentString, - [], + ), + returnValueForMissingStub: _i8.Future.value( + _i12.dummyValue( + this, + Invocation.method(#getUserAgentString, []), ), - )), + ), ) as _i8.Future); @override _i2.WebSettings pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), returnValue: _FakeWebSettings_20( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), returnValueForMissingStub: _FakeWebSettings_20( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), ) as _i2.WebSettings); } @@ -2776,41 +2261,21 @@ class MockWebView extends _i1.Mock implements _i2.WebView { @override _i2.WebSettings pigeonVar_settings() => (super.noSuchMethod( - Invocation.method( - #pigeonVar_settings, - [], - ), + Invocation.method(#pigeonVar_settings, []), returnValue: _FakeWebSettings_20( this, - Invocation.method( - #pigeonVar_settings, - [], - ), + Invocation.method(#pigeonVar_settings, []), ), returnValueForMissingStub: _FakeWebSettings_20( this, - Invocation.method( - #pigeonVar_settings, - [], - ), + Invocation.method(#pigeonVar_settings, []), ), ) as _i2.WebSettings); @override - _i8.Future loadData( - String? data, - String? mimeType, - String? encoding, - ) => + _i8.Future loadData(String? data, String? mimeType, String? encoding) => (super.noSuchMethod( - Invocation.method( - #loadData, - [ - data, - mimeType, - encoding, - ], - ), + Invocation.method(#loadData, [data, mimeType, encoding]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -2824,120 +2289,78 @@ class MockWebView extends _i1.Mock implements _i2.WebView { String? historyUrl, ) => (super.noSuchMethod( - Invocation.method( - #loadDataWithBaseUrl, - [ - baseUrl, - data, - mimeType, - encoding, - historyUrl, - ], - ), + Invocation.method(#loadDataWithBaseUrl, [ + baseUrl, + data, + mimeType, + encoding, + historyUrl, + ]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override - _i8.Future loadUrl( - String? url, - Map? headers, - ) => + _i8.Future loadUrl(String? url, Map? headers) => (super.noSuchMethod( - Invocation.method( - #loadUrl, - [ - url, - headers, - ], - ), + Invocation.method(#loadUrl, [url, headers]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override - _i8.Future postUrl( - String? url, - _i13.Uint8List? data, - ) => + _i8.Future postUrl(String? url, _i13.Uint8List? data) => (super.noSuchMethod( - Invocation.method( - #postUrl, - [ - url, - data, - ], - ), + Invocation.method(#postUrl, [url, data]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future getUrl() => (super.noSuchMethod( - Invocation.method( - #getUrl, - [], - ), + Invocation.method(#getUrl, []), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future canGoBack() => (super.noSuchMethod( - Invocation.method( - #canGoBack, - [], - ), + Invocation.method(#canGoBack, []), returnValue: _i8.Future.value(false), returnValueForMissingStub: _i8.Future.value(false), ) as _i8.Future); @override _i8.Future canGoForward() => (super.noSuchMethod( - Invocation.method( - #canGoForward, - [], - ), + Invocation.method(#canGoForward, []), returnValue: _i8.Future.value(false), returnValueForMissingStub: _i8.Future.value(false), ) as _i8.Future); @override _i8.Future goBack() => (super.noSuchMethod( - Invocation.method( - #goBack, - [], - ), + Invocation.method(#goBack, []), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future goForward() => (super.noSuchMethod( - Invocation.method( - #goForward, - [], - ), + Invocation.method(#goForward, []), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future reload() => (super.noSuchMethod( - Invocation.method( - #reload, - [], - ), + Invocation.method(#reload, []), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future clearCache(bool? includeDiskFiles) => (super.noSuchMethod( - Invocation.method( - #clearCache, - [includeDiskFiles], - ), + Invocation.method(#clearCache, [includeDiskFiles]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -2945,20 +2368,14 @@ class MockWebView extends _i1.Mock implements _i2.WebView { @override _i8.Future evaluateJavascript(String? javascriptString) => (super.noSuchMethod( - Invocation.method( - #evaluateJavascript, - [javascriptString], - ), + Invocation.method(#evaluateJavascript, [javascriptString]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future getTitle() => (super.noSuchMethod( - Invocation.method( - #getTitle, - [], - ), + Invocation.method(#getTitle, []), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -2966,10 +2383,7 @@ class MockWebView extends _i1.Mock implements _i2.WebView { @override _i8.Future setWebViewClient(_i2.WebViewClient? client) => (super.noSuchMethod( - Invocation.method( - #setWebViewClient, - [client], - ), + Invocation.method(#setWebViewClient, [client]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -2977,20 +2391,14 @@ class MockWebView extends _i1.Mock implements _i2.WebView { @override _i8.Future addJavaScriptChannel(_i2.JavaScriptChannel? channel) => (super.noSuchMethod( - Invocation.method( - #addJavaScriptChannel, - [channel], - ), + Invocation.method(#addJavaScriptChannel, [channel]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future removeJavaScriptChannel(String? name) => (super.noSuchMethod( - Invocation.method( - #removeJavaScriptChannel, - [name], - ), + Invocation.method(#removeJavaScriptChannel, [name]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -2998,10 +2406,7 @@ class MockWebView extends _i1.Mock implements _i2.WebView { @override _i8.Future setDownloadListener(_i2.DownloadListener? listener) => (super.noSuchMethod( - Invocation.method( - #setDownloadListener, - [listener], - ), + Invocation.method(#setDownloadListener, [listener]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @@ -3009,111 +2414,67 @@ class MockWebView extends _i1.Mock implements _i2.WebView { @override _i8.Future setWebChromeClient(_i2.WebChromeClient? client) => (super.noSuchMethod( - Invocation.method( - #setWebChromeClient, - [client], - ), + Invocation.method(#setWebChromeClient, [client]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future setBackgroundColor(int? color) => (super.noSuchMethod( - Invocation.method( - #setBackgroundColor, - [color], - ), + Invocation.method(#setBackgroundColor, [color]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future destroy() => (super.noSuchMethod( - Invocation.method( - #destroy, - [], - ), + Invocation.method(#destroy, []), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i2.WebView pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), returnValue: _FakeWebView_7( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), returnValueForMissingStub: _FakeWebView_7( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), ) as _i2.WebView); @override - _i8.Future scrollTo( - int? x, - int? y, - ) => - (super.noSuchMethod( - Invocation.method( - #scrollTo, - [ - x, - y, - ], - ), + _i8.Future scrollTo(int? x, int? y) => (super.noSuchMethod( + Invocation.method(#scrollTo, [x, y]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override - _i8.Future scrollBy( - int? x, - int? y, - ) => - (super.noSuchMethod( - Invocation.method( - #scrollBy, - [ - x, - y, - ], - ), + _i8.Future scrollBy(int? x, int? y) => (super.noSuchMethod( + Invocation.method(#scrollBy, [x, y]), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i8.Future<_i2.WebViewPoint> getScrollPosition() => (super.noSuchMethod( - Invocation.method( - #getScrollPosition, - [], - ), - returnValue: _i8.Future<_i2.WebViewPoint>.value(_FakeWebViewPoint_21( - this, - Invocation.method( - #getScrollPosition, - [], + Invocation.method(#getScrollPosition, []), + returnValue: _i8.Future<_i2.WebViewPoint>.value( + _FakeWebViewPoint_21( + this, + Invocation.method(#getScrollPosition, []), ), - )), - returnValueForMissingStub: - _i8.Future<_i2.WebViewPoint>.value(_FakeWebViewPoint_21( - this, - Invocation.method( - #getScrollPosition, - [], + ), + returnValueForMissingStub: _i8.Future<_i2.WebViewPoint>.value( + _FakeWebViewPoint_21( + this, + Invocation.method(#getScrollPosition, []), ), - )), + ), ) as _i8.Future<_i2.WebViewPoint>); } @@ -3136,7 +2497,8 @@ class MockWebViewClient extends _i1.Mock implements _i2.WebViewClient { @override _i8.Future setSynchronousReturnValueForShouldOverrideUrlLoading( - bool? value) => + bool? value, + ) => (super.noSuchMethod( Invocation.method( #setSynchronousReturnValueForShouldOverrideUrlLoading, @@ -3148,23 +2510,14 @@ class MockWebViewClient extends _i1.Mock implements _i2.WebViewClient { @override _i2.WebViewClient pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), returnValue: _FakeWebViewClient_1( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), returnValueForMissingStub: _FakeWebViewClient_1( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), ) as _i2.WebViewClient); } @@ -3188,33 +2541,21 @@ class MockWebStorage extends _i1.Mock implements _i2.WebStorage { @override _i8.Future deleteAllData() => (super.noSuchMethod( - Invocation.method( - #deleteAllData, - [], - ), + Invocation.method(#deleteAllData, []), returnValue: _i8.Future.value(), returnValueForMissingStub: _i8.Future.value(), ) as _i8.Future); @override _i2.WebStorage pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), returnValue: _FakeWebStorage_11( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), returnValueForMissingStub: _FakeWebStorage_11( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), ) as _i2.WebStorage); } diff --git a/packages/webview_flutter/webview_flutter_android/test/android_webview_cookie_manager_test.mocks.dart b/packages/webview_flutter/webview_flutter_android/test/android_webview_cookie_manager_test.mocks.dart index 9a80b3c10f10..8d6b892fcfcb 100644 --- a/packages/webview_flutter/webview_flutter_android/test/android_webview_cookie_manager_test.mocks.dart +++ b/packages/webview_flutter/webview_flutter_android/test/android_webview_cookie_manager_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in webview_flutter_android/test/android_webview_cookie_manager_test.dart. // Do not manually edit this file. @@ -21,6 +21,7 @@ import 'package:webview_flutter_platform_interface/webview_flutter_platform_inte // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types @@ -28,23 +29,13 @@ import 'package:webview_flutter_platform_interface/webview_flutter_platform_inte class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { - _FakePigeonInstanceManager_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeCookieManager_1 extends _i1.SmartFake implements _i2.CookieManager { - _FakeCookieManager_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeCookieManager_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakePlatformWebViewControllerCreationParams_2 extends _i1.SmartFake @@ -52,30 +43,17 @@ class _FakePlatformWebViewControllerCreationParams_2 extends _i1.SmartFake _FakePlatformWebViewControllerCreationParams_2( Object parent, Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + ) : super(parent, parentInvocation); } class _FakeObject_3 extends _i1.SmartFake implements Object { - _FakeObject_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeObject_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeOffset_4 extends _i1.SmartFake implements _i4.Offset { - _FakeOffset_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeOffset_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [CookieManager]. @@ -96,28 +74,15 @@ class MockCookieManager extends _i1.Mock implements _i2.CookieManager { ) as _i2.PigeonInstanceManager); @override - _i5.Future setCookie( - String? url, - String? value, - ) => - (super.noSuchMethod( - Invocation.method( - #setCookie, - [ - url, - value, - ], - ), + _i5.Future setCookie(String? url, String? value) => (super.noSuchMethod( + Invocation.method(#setCookie, [url, value]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future removeAllCookies() => (super.noSuchMethod( - Invocation.method( - #removeAllCookies, - [], - ), + Invocation.method(#removeAllCookies, []), returnValue: _i5.Future.value(false), ) as _i5.Future); @@ -127,29 +92,17 @@ class MockCookieManager extends _i1.Mock implements _i2.CookieManager { bool? accept, ) => (super.noSuchMethod( - Invocation.method( - #setAcceptThirdPartyCookies, - [ - webView, - accept, - ], - ), + Invocation.method(#setAcceptThirdPartyCookies, [webView, accept]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i2.CookieManager pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), returnValue: _FakeCookieManager_1( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), ) as _i2.CookieManager); } @@ -164,10 +117,9 @@ class MockAndroidWebViewController extends _i1.Mock } @override - int get webViewIdentifier => (super.noSuchMethod( - Invocation.getter(#webViewIdentifier), - returnValue: 0, - ) as int); + int get webViewIdentifier => + (super.noSuchMethod(Invocation.getter(#webViewIdentifier), returnValue: 0) + as int); @override _i3.PlatformWebViewControllerCreationParams get params => (super.noSuchMethod( @@ -180,45 +132,29 @@ class MockAndroidWebViewController extends _i1.Mock @override _i5.Future setAllowFileAccess(bool? allow) => (super.noSuchMethod( - Invocation.method( - #setAllowFileAccess, - [allow], - ), + Invocation.method(#setAllowFileAccess, [allow]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future loadFile(String? absoluteFilePath) => (super.noSuchMethod( - Invocation.method( - #loadFile, - [absoluteFilePath], - ), + Invocation.method(#loadFile, [absoluteFilePath]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future loadFlutterAsset(String? key) => (super.noSuchMethod( - Invocation.method( - #loadFlutterAsset, - [key], - ), + Invocation.method(#loadFlutterAsset, [key]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override - _i5.Future loadHtmlString( - String? html, { - String? baseUrl, - }) => + _i5.Future loadHtmlString(String? html, {String? baseUrl}) => (super.noSuchMethod( - Invocation.method( - #loadHtmlString, - [html], - {#baseUrl: baseUrl}, - ), + Invocation.method(#loadHtmlString, [html], {#baseUrl: baseUrl}), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @@ -226,109 +162,77 @@ class MockAndroidWebViewController extends _i1.Mock @override _i5.Future loadRequest(_i3.LoadRequestParams? params) => (super.noSuchMethod( - Invocation.method( - #loadRequest, - [params], - ), + Invocation.method(#loadRequest, [params]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future currentUrl() => (super.noSuchMethod( - Invocation.method( - #currentUrl, - [], - ), + Invocation.method(#currentUrl, []), returnValue: _i5.Future.value(), ) as _i5.Future); @override _i5.Future canGoBack() => (super.noSuchMethod( - Invocation.method( - #canGoBack, - [], - ), + Invocation.method(#canGoBack, []), returnValue: _i5.Future.value(false), ) as _i5.Future); @override _i5.Future canGoForward() => (super.noSuchMethod( - Invocation.method( - #canGoForward, - [], - ), + Invocation.method(#canGoForward, []), returnValue: _i5.Future.value(false), ) as _i5.Future); @override _i5.Future goBack() => (super.noSuchMethod( - Invocation.method( - #goBack, - [], - ), + Invocation.method(#goBack, []), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future goForward() => (super.noSuchMethod( - Invocation.method( - #goForward, - [], - ), + Invocation.method(#goForward, []), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future reload() => (super.noSuchMethod( - Invocation.method( - #reload, - [], - ), + Invocation.method(#reload, []), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future clearCache() => (super.noSuchMethod( - Invocation.method( - #clearCache, - [], - ), + Invocation.method(#clearCache, []), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future clearLocalStorage() => (super.noSuchMethod( - Invocation.method( - #clearLocalStorage, - [], - ), + Invocation.method(#clearLocalStorage, []), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future setPlatformNavigationDelegate( - _i3.PlatformNavigationDelegate? handler) => + _i3.PlatformNavigationDelegate? handler, + ) => (super.noSuchMethod( - Invocation.method( - #setPlatformNavigationDelegate, - [handler], - ), + Invocation.method(#setPlatformNavigationDelegate, [handler]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future runJavaScript(String? javaScript) => (super.noSuchMethod( - Invocation.method( - #runJavaScript, - [javaScript], - ), + Invocation.method(#runJavaScript, [javaScript]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @@ -336,27 +240,21 @@ class MockAndroidWebViewController extends _i1.Mock @override _i5.Future runJavaScriptReturningResult(String? javaScript) => (super.noSuchMethod( - Invocation.method( - #runJavaScriptReturningResult, - [javaScript], - ), - returnValue: _i5.Future.value(_FakeObject_3( - this, - Invocation.method( - #runJavaScriptReturningResult, - [javaScript], + Invocation.method(#runJavaScriptReturningResult, [javaScript]), + returnValue: _i5.Future.value( + _FakeObject_3( + this, + Invocation.method(#runJavaScriptReturningResult, [javaScript]), ), - )), + ), ) as _i5.Future); @override _i5.Future addJavaScriptChannel( - _i3.JavaScriptChannelParams? javaScriptChannelParams) => + _i3.JavaScriptChannelParams? javaScriptChannelParams, + ) => (super.noSuchMethod( - Invocation.method( - #addJavaScriptChannel, - [javaScriptChannelParams], - ), + Invocation.method(#addJavaScriptChannel, [javaScriptChannelParams]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @@ -364,88 +262,51 @@ class MockAndroidWebViewController extends _i1.Mock @override _i5.Future removeJavaScriptChannel(String? javaScriptChannelName) => (super.noSuchMethod( - Invocation.method( - #removeJavaScriptChannel, - [javaScriptChannelName], - ), + Invocation.method(#removeJavaScriptChannel, [ + javaScriptChannelName, + ]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future getTitle() => (super.noSuchMethod( - Invocation.method( - #getTitle, - [], - ), + Invocation.method(#getTitle, []), returnValue: _i5.Future.value(), ) as _i5.Future); @override - _i5.Future scrollTo( - int? x, - int? y, - ) => - (super.noSuchMethod( - Invocation.method( - #scrollTo, - [ - x, - y, - ], - ), + _i5.Future scrollTo(int? x, int? y) => (super.noSuchMethod( + Invocation.method(#scrollTo, [x, y]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override - _i5.Future scrollBy( - int? x, - int? y, - ) => - (super.noSuchMethod( - Invocation.method( - #scrollBy, - [ - x, - y, - ], - ), + _i5.Future scrollBy(int? x, int? y) => (super.noSuchMethod( + Invocation.method(#scrollBy, [x, y]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future<_i4.Offset> getScrollPosition() => (super.noSuchMethod( - Invocation.method( - #getScrollPosition, - [], + Invocation.method(#getScrollPosition, []), + returnValue: _i5.Future<_i4.Offset>.value( + _FakeOffset_4(this, Invocation.method(#getScrollPosition, [])), ), - returnValue: _i5.Future<_i4.Offset>.value(_FakeOffset_4( - this, - Invocation.method( - #getScrollPosition, - [], - ), - )), ) as _i5.Future<_i4.Offset>); @override _i5.Future enableZoom(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #enableZoom, - [enabled], - ), + Invocation.method(#enableZoom, [enabled]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future setBackgroundColor(_i4.Color? color) => (super.noSuchMethod( - Invocation.method( - #setBackgroundColor, - [color], - ), + Invocation.method(#setBackgroundColor, [color]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @@ -453,32 +314,26 @@ class MockAndroidWebViewController extends _i1.Mock @override _i5.Future setJavaScriptMode(_i3.JavaScriptMode? javaScriptMode) => (super.noSuchMethod( - Invocation.method( - #setJavaScriptMode, - [javaScriptMode], - ), + Invocation.method(#setJavaScriptMode, [javaScriptMode]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future setUserAgent(String? userAgent) => (super.noSuchMethod( - Invocation.method( - #setUserAgent, - [userAgent], - ), + Invocation.method(#setUserAgent, [userAgent]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future setOnScrollPositionChange( - void Function(_i3.ScrollPositionChange)? onScrollPositionChange) => + void Function(_i3.ScrollPositionChange)? onScrollPositionChange, + ) => (super.noSuchMethod( - Invocation.method( - #setOnScrollPositionChange, - [onScrollPositionChange], - ), + Invocation.method(#setOnScrollPositionChange, [ + onScrollPositionChange, + ]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @@ -486,66 +341,51 @@ class MockAndroidWebViewController extends _i1.Mock @override _i5.Future setMediaPlaybackRequiresUserGesture(bool? require) => (super.noSuchMethod( - Invocation.method( - #setMediaPlaybackRequiresUserGesture, - [require], - ), + Invocation.method(#setMediaPlaybackRequiresUserGesture, [require]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future setTextZoom(int? textZoom) => (super.noSuchMethod( - Invocation.method( - #setTextZoom, - [textZoom], - ), + Invocation.method(#setTextZoom, [textZoom]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future setAllowContentAccess(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setAllowContentAccess, - [enabled], - ), + Invocation.method(#setAllowContentAccess, [enabled]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future setGeolocationEnabled(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setGeolocationEnabled, - [enabled], - ), + Invocation.method(#setGeolocationEnabled, [enabled]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future setOnShowFileSelector( - _i5.Future> Function(_i6.FileSelectorParams)? - onShowFileSelector) => + _i5.Future> Function(_i6.FileSelectorParams)? + onShowFileSelector, + ) => (super.noSuchMethod( - Invocation.method( - #setOnShowFileSelector, - [onShowFileSelector], - ), + Invocation.method(#setOnShowFileSelector, [onShowFileSelector]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future setOnPlatformPermissionRequest( - void Function(_i3.PlatformWebViewPermissionRequest)? - onPermissionRequest) => + void Function(_i3.PlatformWebViewPermissionRequest)? onPermissionRequest, + ) => (super.noSuchMethod( - Invocation.method( - #setOnPlatformPermissionRequest, - [onPermissionRequest], - ), + Invocation.method(#setOnPlatformPermissionRequest, [ + onPermissionRequest, + ]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @@ -556,14 +396,10 @@ class MockAndroidWebViewController extends _i1.Mock _i6.OnGeolocationPermissionsHidePrompt? onHidePrompt, }) => (super.noSuchMethod( - Invocation.method( - #setGeolocationPermissionsPromptCallbacks, - [], - { - #onShowPrompt: onShowPrompt, - #onHidePrompt: onHidePrompt, - }, - ), + Invocation.method(#setGeolocationPermissionsPromptCallbacks, [], { + #onShowPrompt: onShowPrompt, + #onHidePrompt: onHidePrompt, + }), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @@ -574,74 +410,65 @@ class MockAndroidWebViewController extends _i1.Mock required _i6.OnHideCustomWidgetCallback? onHideCustomWidget, }) => (super.noSuchMethod( - Invocation.method( - #setCustomWidgetCallbacks, - [], - { - #onShowCustomWidget: onShowCustomWidget, - #onHideCustomWidget: onHideCustomWidget, - }, - ), + Invocation.method(#setCustomWidgetCallbacks, [], { + #onShowCustomWidget: onShowCustomWidget, + #onHideCustomWidget: onHideCustomWidget, + }), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future setOnConsoleMessage( - void Function(_i3.JavaScriptConsoleMessage)? onConsoleMessage) => + void Function(_i3.JavaScriptConsoleMessage)? onConsoleMessage, + ) => (super.noSuchMethod( - Invocation.method( - #setOnConsoleMessage, - [onConsoleMessage], - ), + Invocation.method(#setOnConsoleMessage, [onConsoleMessage]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future getUserAgent() => (super.noSuchMethod( - Invocation.method( - #getUserAgent, - [], - ), + Invocation.method(#getUserAgent, []), returnValue: _i5.Future.value(), ) as _i5.Future); @override _i5.Future setOnJavaScriptAlertDialog( - _i5.Future Function(_i3.JavaScriptAlertDialogRequest)? - onJavaScriptAlertDialog) => + _i5.Future Function(_i3.JavaScriptAlertDialogRequest)? + onJavaScriptAlertDialog, + ) => (super.noSuchMethod( - Invocation.method( - #setOnJavaScriptAlertDialog, - [onJavaScriptAlertDialog], - ), + Invocation.method(#setOnJavaScriptAlertDialog, [ + onJavaScriptAlertDialog, + ]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future setOnJavaScriptConfirmDialog( - _i5.Future Function(_i3.JavaScriptConfirmDialogRequest)? - onJavaScriptConfirmDialog) => + _i5.Future Function(_i3.JavaScriptConfirmDialogRequest)? + onJavaScriptConfirmDialog, + ) => (super.noSuchMethod( - Invocation.method( - #setOnJavaScriptConfirmDialog, - [onJavaScriptConfirmDialog], - ), + Invocation.method(#setOnJavaScriptConfirmDialog, [ + onJavaScriptConfirmDialog, + ]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); @override _i5.Future setOnJavaScriptTextInputDialog( - _i5.Future Function(_i3.JavaScriptTextInputDialogRequest)? - onJavaScriptTextInputDialog) => + _i5.Future Function(_i3.JavaScriptTextInputDialogRequest)? + onJavaScriptTextInputDialog, + ) => (super.noSuchMethod( - Invocation.method( - #setOnJavaScriptTextInputDialog, - [onJavaScriptTextInputDialog], - ), + Invocation.method(#setOnJavaScriptTextInputDialog, [ + onJavaScriptTextInputDialog, + ]), returnValue: _i5.Future.value(), returnValueForMissingStub: _i5.Future.value(), ) as _i5.Future); diff --git a/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_cookie_manager_test.mocks.dart b/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_cookie_manager_test.mocks.dart index 28c0d95b8149..68d1d82b29c6 100644 --- a/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_cookie_manager_test.mocks.dart +++ b/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_cookie_manager_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in webview_flutter_android/test/legacy/webview_android_cookie_manager_test.dart. // Do not manually edit this file. @@ -16,6 +16,7 @@ import 'package:webview_flutter_android/src/android_webkit.g.dart' as _i2; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types @@ -23,23 +24,13 @@ import 'package:webview_flutter_android/src/android_webkit.g.dart' as _i2; class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { - _FakePigeonInstanceManager_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeCookieManager_1 extends _i1.SmartFake implements _i2.CookieManager { - _FakeCookieManager_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeCookieManager_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [CookieManager]. @@ -60,28 +51,15 @@ class MockCookieManager extends _i1.Mock implements _i2.CookieManager { ) as _i2.PigeonInstanceManager); @override - _i3.Future setCookie( - String? url, - String? value, - ) => - (super.noSuchMethod( - Invocation.method( - #setCookie, - [ - url, - value, - ], - ), + _i3.Future setCookie(String? url, String? value) => (super.noSuchMethod( + Invocation.method(#setCookie, [url, value]), returnValue: _i3.Future.value(), returnValueForMissingStub: _i3.Future.value(), ) as _i3.Future); @override _i3.Future removeAllCookies() => (super.noSuchMethod( - Invocation.method( - #removeAllCookies, - [], - ), + Invocation.method(#removeAllCookies, []), returnValue: _i3.Future.value(false), ) as _i3.Future); @@ -91,29 +69,17 @@ class MockCookieManager extends _i1.Mock implements _i2.CookieManager { bool? accept, ) => (super.noSuchMethod( - Invocation.method( - #setAcceptThirdPartyCookies, - [ - webView, - accept, - ], - ), + Invocation.method(#setAcceptThirdPartyCookies, [webView, accept]), returnValue: _i3.Future.value(), returnValueForMissingStub: _i3.Future.value(), ) as _i3.Future); @override _i2.CookieManager pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), returnValue: _FakeCookieManager_1( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), ) as _i2.CookieManager); } diff --git a/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_widget_test.dart b/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_widget_test.dart index db160b9e5b85..0729179af856 100644 --- a/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_widget_test.dart +++ b/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_widget_test.dart @@ -66,6 +66,9 @@ void main() { onReceivedRequestError: anyNamed('onReceivedRequestError'), requestLoading: anyNamed('requestLoading'), urlLoading: anyNamed('urlLoading'), + onReceivedSslError: anyNamed('onReceivedSslError'), + onFormResubmission: anyNamed('onFormResubmission'), + onReceivedClientCertRequest: anyNamed('onReceivedClientCertRequest'), )).thenReturn(mockWebViewClient); mockCallbacksHandler = MockWebViewPlatformCallbacksHandler(); @@ -237,6 +240,10 @@ void main() { onReceivedRequestError: anyNamed('onReceivedRequestError'), requestLoading: anyNamed('requestLoading'), urlLoading: anyNamed('urlLoading'), + onReceivedSslError: anyNamed('onReceivedSslError'), + onFormResubmission: anyNamed('onFormResubmission'), + onReceivedClientCertRequest: + anyNamed('onReceivedClientCertRequest'), )).thenReturn(mockWebViewClient); await buildWidget( @@ -733,6 +740,9 @@ void main() { onReceivedRequestError: anyNamed('onReceivedRequestError'), requestLoading: anyNamed('requestLoading'), urlLoading: anyNamed('urlLoading'), + onReceivedSslError: anyNamed('onReceivedSslError'), + onFormResubmission: anyNamed('onFormResubmission'), + onReceivedClientCertRequest: anyNamed('onReceivedClientCertRequest'), )).captured.single as void Function( android_webview.WebViewClient, android_webview.WebView, String); @@ -752,6 +762,9 @@ void main() { onReceivedRequestError: anyNamed('onReceivedRequestError'), requestLoading: anyNamed('requestLoading'), urlLoading: anyNamed('urlLoading'), + onReceivedSslError: anyNamed('onReceivedSslError'), + onFormResubmission: anyNamed('onFormResubmission'), + onReceivedClientCertRequest: anyNamed('onReceivedClientCertRequest'), )).captured.single as void Function( android_webview.WebViewClient, android_webview.WebView, String); @@ -772,6 +785,9 @@ void main() { onReceivedRequestError: anyNamed('onReceivedRequestError'), requestLoading: anyNamed('requestLoading'), urlLoading: anyNamed('urlLoading'), + onReceivedSslError: anyNamed('onReceivedSslError'), + onFormResubmission: anyNamed('onFormResubmission'), + onReceivedClientCertRequest: anyNamed('onReceivedClientCertRequest'), )).captured.single as void Function(android_webview.WebViewClient, android_webview.WebView, int, String, String); @@ -810,6 +826,9 @@ void main() { onReceivedRequestError: captureAnyNamed('onReceivedRequestError'), requestLoading: anyNamed('requestLoading'), urlLoading: anyNamed('urlLoading'), + onReceivedSslError: anyNamed('onReceivedSslError'), + onFormResubmission: anyNamed('onFormResubmission'), + onReceivedClientCertRequest: anyNamed('onReceivedClientCertRequest'), )).captured.single as void Function( android_webview.WebViewClient, android_webview.WebView, @@ -862,6 +881,9 @@ void main() { onReceivedRequestError: anyNamed('onReceivedRequestError'), requestLoading: anyNamed('requestLoading'), urlLoading: captureAnyNamed('urlLoading'), + onReceivedSslError: anyNamed('onReceivedSslError'), + onFormResubmission: anyNamed('onFormResubmission'), + onReceivedClientCertRequest: anyNamed('onReceivedClientCertRequest'), )).captured.single as void Function( android_webview.WebViewClient, android_webview.WebView, String); @@ -892,6 +914,9 @@ void main() { onReceivedRequestError: anyNamed('onReceivedRequestError'), requestLoading: captureAnyNamed('requestLoading'), urlLoading: anyNamed('urlLoading'), + onReceivedSslError: anyNamed('onReceivedSslError'), + onFormResubmission: anyNamed('onFormResubmission'), + onReceivedClientCertRequest: anyNamed('onReceivedClientCertRequest'), )).captured.single as void Function( android_webview.WebViewClient, android_webview.WebView, diff --git a/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_widget_test.mocks.dart b/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_widget_test.mocks.dart index ff695040404a..b7d9898b9c0c 100644 --- a/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_widget_test.mocks.dart +++ b/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_widget_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in webview_flutter_android/test/legacy/webview_android_widget_test.dart. // Do not manually edit this file. @@ -22,6 +22,7 @@ import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_ // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types @@ -29,129 +30,69 @@ import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_ class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { - _FakePigeonInstanceManager_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeFlutterAssetManager_1 extends _i1.SmartFake implements _i2.FlutterAssetManager { - _FakeFlutterAssetManager_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeFlutterAssetManager_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWebSettings_2 extends _i1.SmartFake implements _i2.WebSettings { - _FakeWebSettings_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebSettings_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWebStorage_3 extends _i1.SmartFake implements _i2.WebStorage { - _FakeWebStorage_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebStorage_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWebView_4 extends _i1.SmartFake implements _i2.WebView { - _FakeWebView_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebView_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWebViewPoint_5 extends _i1.SmartFake implements _i2.WebViewPoint { - _FakeWebViewPoint_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebViewPoint_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWebResourceRequest_6 extends _i1.SmartFake implements _i2.WebResourceRequest { - _FakeWebResourceRequest_6( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebResourceRequest_6(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeDownloadListener_7 extends _i1.SmartFake implements _i2.DownloadListener { - _FakeDownloadListener_7( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeDownloadListener_7(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeJavascriptChannelRegistry_8 extends _i1.SmartFake implements _i3.JavascriptChannelRegistry { - _FakeJavascriptChannelRegistry_8( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeJavascriptChannelRegistry_8(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeJavaScriptChannel_9 extends _i1.SmartFake implements _i2.JavaScriptChannel { - _FakeJavaScriptChannel_9( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeJavaScriptChannel_9(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWebChromeClient_10 extends _i1.SmartFake implements _i2.WebChromeClient { - _FakeWebChromeClient_10( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebChromeClient_10(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } class _FakeWebViewClient_11 extends _i1.SmartFake implements _i2.WebViewClient { - _FakeWebViewClient_11( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + _FakeWebViewClient_11(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [FlutterAssetManager]. @@ -174,41 +115,28 @@ class MockFlutterAssetManager extends _i1.Mock @override _i4.Future> list(String? path) => (super.noSuchMethod( - Invocation.method( - #list, - [path], - ), + Invocation.method(#list, [path]), returnValue: _i4.Future>.value([]), ) as _i4.Future>); @override _i4.Future getAssetFilePathByName(String? name) => (super.noSuchMethod( - Invocation.method( - #getAssetFilePathByName, - [name], - ), - returnValue: _i4.Future.value(_i5.dummyValue( - this, - Invocation.method( - #getAssetFilePathByName, - [name], + Invocation.method(#getAssetFilePathByName, [name]), + returnValue: _i4.Future.value( + _i5.dummyValue( + this, + Invocation.method(#getAssetFilePathByName, [name]), ), - )), + ), ) as _i4.Future); @override _i2.FlutterAssetManager pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), returnValue: _FakeFlutterAssetManager_1( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), ) as _i2.FlutterAssetManager); } @@ -232,10 +160,7 @@ class MockWebSettings extends _i1.Mock implements _i2.WebSettings { @override _i4.Future setDomStorageEnabled(bool? flag) => (super.noSuchMethod( - Invocation.method( - #setDomStorageEnabled, - [flag], - ), + Invocation.method(#setDomStorageEnabled, [flag]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @@ -243,10 +168,9 @@ class MockWebSettings extends _i1.Mock implements _i2.WebSettings { @override _i4.Future setJavaScriptCanOpenWindowsAutomatically(bool? flag) => (super.noSuchMethod( - Invocation.method( - #setJavaScriptCanOpenWindowsAutomatically, - [flag], - ), + Invocation.method(#setJavaScriptCanOpenWindowsAutomatically, [ + flag, + ]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @@ -254,20 +178,14 @@ class MockWebSettings extends _i1.Mock implements _i2.WebSettings { @override _i4.Future setSupportMultipleWindows(bool? support) => (super.noSuchMethod( - Invocation.method( - #setSupportMultipleWindows, - [support], - ), + Invocation.method(#setSupportMultipleWindows, [support]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override _i4.Future setJavaScriptEnabled(bool? flag) => (super.noSuchMethod( - Invocation.method( - #setJavaScriptEnabled, - [flag], - ), + Invocation.method(#setJavaScriptEnabled, [flag]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @@ -275,10 +193,7 @@ class MockWebSettings extends _i1.Mock implements _i2.WebSettings { @override _i4.Future setUserAgentString(String? userAgentString) => (super.noSuchMethod( - Invocation.method( - #setUserAgentString, - [userAgentString], - ), + Invocation.method(#setUserAgentString, [userAgentString]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @@ -286,20 +201,14 @@ class MockWebSettings extends _i1.Mock implements _i2.WebSettings { @override _i4.Future setMediaPlaybackRequiresUserGesture(bool? require) => (super.noSuchMethod( - Invocation.method( - #setMediaPlaybackRequiresUserGesture, - [require], - ), + Invocation.method(#setMediaPlaybackRequiresUserGesture, [require]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override _i4.Future setSupportZoom(bool? support) => (super.noSuchMethod( - Invocation.method( - #setSupportZoom, - [support], - ), + Invocation.method(#setSupportZoom, [support]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @@ -307,111 +216,77 @@ class MockWebSettings extends _i1.Mock implements _i2.WebSettings { @override _i4.Future setLoadWithOverviewMode(bool? overview) => (super.noSuchMethod( - Invocation.method( - #setLoadWithOverviewMode, - [overview], - ), + Invocation.method(#setLoadWithOverviewMode, [overview]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override _i4.Future setUseWideViewPort(bool? use) => (super.noSuchMethod( - Invocation.method( - #setUseWideViewPort, - [use], - ), + Invocation.method(#setUseWideViewPort, [use]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override _i4.Future setDisplayZoomControls(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setDisplayZoomControls, - [enabled], - ), + Invocation.method(#setDisplayZoomControls, [enabled]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override _i4.Future setBuiltInZoomControls(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setBuiltInZoomControls, - [enabled], - ), + Invocation.method(#setBuiltInZoomControls, [enabled]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override _i4.Future setAllowFileAccess(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setAllowFileAccess, - [enabled], - ), + Invocation.method(#setAllowFileAccess, [enabled]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override _i4.Future setAllowContentAccess(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setAllowContentAccess, - [enabled], - ), + Invocation.method(#setAllowContentAccess, [enabled]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override _i4.Future setGeolocationEnabled(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setGeolocationEnabled, - [enabled], - ), + Invocation.method(#setGeolocationEnabled, [enabled]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override _i4.Future setTextZoom(int? textZoom) => (super.noSuchMethod( - Invocation.method( - #setTextZoom, - [textZoom], - ), + Invocation.method(#setTextZoom, [textZoom]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override _i4.Future getUserAgentString() => (super.noSuchMethod( - Invocation.method( - #getUserAgentString, - [], - ), - returnValue: _i4.Future.value(_i5.dummyValue( - this, - Invocation.method( - #getUserAgentString, - [], + Invocation.method(#getUserAgentString, []), + returnValue: _i4.Future.value( + _i5.dummyValue( + this, + Invocation.method(#getUserAgentString, []), ), - )), + ), ) as _i4.Future); @override _i2.WebSettings pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), returnValue: _FakeWebSettings_2( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), ) as _i2.WebSettings); } @@ -435,26 +310,17 @@ class MockWebStorage extends _i1.Mock implements _i2.WebStorage { @override _i4.Future deleteAllData() => (super.noSuchMethod( - Invocation.method( - #deleteAllData, - [], - ), + Invocation.method(#deleteAllData, []), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override _i2.WebStorage pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), returnValue: _FakeWebStorage_3( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), ) as _i2.WebStorage); } @@ -470,10 +336,7 @@ class MockWebView extends _i1.Mock implements _i2.WebView { @override _i2.WebSettings get settings => (super.noSuchMethod( Invocation.getter(#settings), - returnValue: _FakeWebSettings_2( - this, - Invocation.getter(#settings), - ), + returnValue: _FakeWebSettings_2(this, Invocation.getter(#settings)), ) as _i2.WebSettings); @override @@ -487,34 +350,17 @@ class MockWebView extends _i1.Mock implements _i2.WebView { @override _i2.WebSettings pigeonVar_settings() => (super.noSuchMethod( - Invocation.method( - #pigeonVar_settings, - [], - ), + Invocation.method(#pigeonVar_settings, []), returnValue: _FakeWebSettings_2( this, - Invocation.method( - #pigeonVar_settings, - [], - ), + Invocation.method(#pigeonVar_settings, []), ), ) as _i2.WebSettings); @override - _i4.Future loadData( - String? data, - String? mimeType, - String? encoding, - ) => + _i4.Future loadData(String? data, String? mimeType, String? encoding) => (super.noSuchMethod( - Invocation.method( - #loadData, - [ - data, - mimeType, - encoding, - ], - ), + Invocation.method(#loadData, [data, mimeType, encoding]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @@ -528,117 +374,75 @@ class MockWebView extends _i1.Mock implements _i2.WebView { String? historyUrl, ) => (super.noSuchMethod( - Invocation.method( - #loadDataWithBaseUrl, - [ - baseUrl, - data, - mimeType, - encoding, - historyUrl, - ], - ), + Invocation.method(#loadDataWithBaseUrl, [ + baseUrl, + data, + mimeType, + encoding, + historyUrl, + ]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override - _i4.Future loadUrl( - String? url, - Map? headers, - ) => + _i4.Future loadUrl(String? url, Map? headers) => (super.noSuchMethod( - Invocation.method( - #loadUrl, - [ - url, - headers, - ], - ), + Invocation.method(#loadUrl, [url, headers]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override - _i4.Future postUrl( - String? url, - _i6.Uint8List? data, - ) => + _i4.Future postUrl(String? url, _i6.Uint8List? data) => (super.noSuchMethod( - Invocation.method( - #postUrl, - [ - url, - data, - ], - ), + Invocation.method(#postUrl, [url, data]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override _i4.Future getUrl() => (super.noSuchMethod( - Invocation.method( - #getUrl, - [], - ), + Invocation.method(#getUrl, []), returnValue: _i4.Future.value(), ) as _i4.Future); @override _i4.Future canGoBack() => (super.noSuchMethod( - Invocation.method( - #canGoBack, - [], - ), + Invocation.method(#canGoBack, []), returnValue: _i4.Future.value(false), ) as _i4.Future); @override _i4.Future canGoForward() => (super.noSuchMethod( - Invocation.method( - #canGoForward, - [], - ), + Invocation.method(#canGoForward, []), returnValue: _i4.Future.value(false), ) as _i4.Future); @override _i4.Future goBack() => (super.noSuchMethod( - Invocation.method( - #goBack, - [], - ), + Invocation.method(#goBack, []), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override _i4.Future goForward() => (super.noSuchMethod( - Invocation.method( - #goForward, - [], - ), + Invocation.method(#goForward, []), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override _i4.Future reload() => (super.noSuchMethod( - Invocation.method( - #reload, - [], - ), + Invocation.method(#reload, []), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override _i4.Future clearCache(bool? includeDiskFiles) => (super.noSuchMethod( - Invocation.method( - #clearCache, - [includeDiskFiles], - ), + Invocation.method(#clearCache, [includeDiskFiles]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @@ -646,29 +450,20 @@ class MockWebView extends _i1.Mock implements _i2.WebView { @override _i4.Future evaluateJavascript(String? javascriptString) => (super.noSuchMethod( - Invocation.method( - #evaluateJavascript, - [javascriptString], - ), + Invocation.method(#evaluateJavascript, [javascriptString]), returnValue: _i4.Future.value(), ) as _i4.Future); @override _i4.Future getTitle() => (super.noSuchMethod( - Invocation.method( - #getTitle, - [], - ), + Invocation.method(#getTitle, []), returnValue: _i4.Future.value(), ) as _i4.Future); @override _i4.Future setWebViewClient(_i2.WebViewClient? client) => (super.noSuchMethod( - Invocation.method( - #setWebViewClient, - [client], - ), + Invocation.method(#setWebViewClient, [client]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @@ -676,20 +471,14 @@ class MockWebView extends _i1.Mock implements _i2.WebView { @override _i4.Future addJavaScriptChannel(_i2.JavaScriptChannel? channel) => (super.noSuchMethod( - Invocation.method( - #addJavaScriptChannel, - [channel], - ), + Invocation.method(#addJavaScriptChannel, [channel]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override _i4.Future removeJavaScriptChannel(String? name) => (super.noSuchMethod( - Invocation.method( - #removeJavaScriptChannel, - [name], - ), + Invocation.method(#removeJavaScriptChannel, [name]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @@ -697,10 +486,7 @@ class MockWebView extends _i1.Mock implements _i2.WebView { @override _i4.Future setDownloadListener(_i2.DownloadListener? listener) => (super.noSuchMethod( - Invocation.method( - #setDownloadListener, - [listener], - ), + Invocation.method(#setDownloadListener, [listener]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @@ -708,96 +494,57 @@ class MockWebView extends _i1.Mock implements _i2.WebView { @override _i4.Future setWebChromeClient(_i2.WebChromeClient? client) => (super.noSuchMethod( - Invocation.method( - #setWebChromeClient, - [client], - ), + Invocation.method(#setWebChromeClient, [client]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override _i4.Future setBackgroundColor(int? color) => (super.noSuchMethod( - Invocation.method( - #setBackgroundColor, - [color], - ), + Invocation.method(#setBackgroundColor, [color]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override _i4.Future destroy() => (super.noSuchMethod( - Invocation.method( - #destroy, - [], - ), + Invocation.method(#destroy, []), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override _i2.WebView pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), returnValue: _FakeWebView_4( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), ) as _i2.WebView); @override - _i4.Future scrollTo( - int? x, - int? y, - ) => - (super.noSuchMethod( - Invocation.method( - #scrollTo, - [ - x, - y, - ], - ), + _i4.Future scrollTo(int? x, int? y) => (super.noSuchMethod( + Invocation.method(#scrollTo, [x, y]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override - _i4.Future scrollBy( - int? x, - int? y, - ) => - (super.noSuchMethod( - Invocation.method( - #scrollBy, - [ - x, - y, - ], - ), + _i4.Future scrollBy(int? x, int? y) => (super.noSuchMethod( + Invocation.method(#scrollBy, [x, y]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override _i4.Future<_i2.WebViewPoint> getScrollPosition() => (super.noSuchMethod( - Invocation.method( - #getScrollPosition, - [], - ), - returnValue: _i4.Future<_i2.WebViewPoint>.value(_FakeWebViewPoint_5( - this, - Invocation.method( - #getScrollPosition, - [], + Invocation.method(#getScrollPosition, []), + returnValue: _i4.Future<_i2.WebViewPoint>.value( + _FakeWebViewPoint_5( + this, + Invocation.method(#getScrollPosition, []), ), - )), + ), ) as _i4.Future<_i2.WebViewPoint>); } @@ -813,10 +560,7 @@ class MockWebResourceRequest extends _i1.Mock @override String get url => (super.noSuchMethod( Invocation.getter(#url), - returnValue: _i5.dummyValue( - this, - Invocation.getter(#url), - ), + returnValue: _i5.dummyValue(this, Invocation.getter(#url)), ) as String); @override @@ -826,10 +570,9 @@ class MockWebResourceRequest extends _i1.Mock ) as bool); @override - bool get hasGesture => (super.noSuchMethod( - Invocation.getter(#hasGesture), - returnValue: false, - ) as bool); + bool get hasGesture => + (super.noSuchMethod(Invocation.getter(#hasGesture), returnValue: false) + as bool); @override String get method => (super.noSuchMethod( @@ -851,16 +594,10 @@ class MockWebResourceRequest extends _i1.Mock @override _i2.WebResourceRequest pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), returnValue: _FakeWebResourceRequest_6( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), ) as _i2.WebResourceRequest); } @@ -874,31 +611,25 @@ class MockDownloadListener extends _i1.Mock implements _i2.DownloadListener { } @override - void Function( - _i2.DownloadListener, - String, - String, - String, - String, - int, - ) get onDownloadStart => (super.noSuchMethod( - Invocation.getter(#onDownloadStart), - returnValue: ( - _i2.DownloadListener pigeon_instance, - String url, - String userAgent, - String contentDisposition, - String mimetype, - int contentLength, - ) {}, - ) as void Function( - _i2.DownloadListener, - String, - String, - String, - String, - int, - )); + void Function(_i2.DownloadListener, String, String, String, String, int) + get onDownloadStart => (super.noSuchMethod( + Invocation.getter(#onDownloadStart), + returnValue: ( + _i2.DownloadListener pigeon_instance, + String url, + String userAgent, + String contentDisposition, + String mimetype, + int contentLength, + ) {}, + ) as void Function( + _i2.DownloadListener, + String, + String, + String, + String, + int, + )); @override _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( @@ -911,16 +642,10 @@ class MockDownloadListener extends _i1.Mock implements _i2.DownloadListener { @override _i2.DownloadListener pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), returnValue: _FakeDownloadListener_7( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), ) as _i2.DownloadListener); } @@ -954,19 +679,11 @@ class MockWebViewAndroidJavaScriptChannel extends _i1.Mock ) as String); @override - void Function( - _i2.JavaScriptChannel, - String, - ) get postMessage => (super.noSuchMethod( + void Function(_i2.JavaScriptChannel, String) get postMessage => + (super.noSuchMethod( Invocation.getter(#postMessage), - returnValue: ( - _i2.JavaScriptChannel pigeon_instance, - String message, - ) {}, - ) as void Function( - _i2.JavaScriptChannel, - String, - )); + returnValue: (_i2.JavaScriptChannel pigeon_instance, String message) {}, + ) as void Function(_i2.JavaScriptChannel, String)); @override _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( @@ -979,16 +696,10 @@ class MockWebViewAndroidJavaScriptChannel extends _i1.Mock @override _i2.JavaScriptChannel pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), returnValue: _FakeJavaScriptChannel_9( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), ) as _i2.JavaScriptChannel); } @@ -1001,6 +712,43 @@ class MockWebChromeClient extends _i1.Mock implements _i2.WebChromeClient { _i1.throwOnMissingStub(this); } + @override + _i4.Future> Function( + _i2.WebChromeClient, + _i2.WebView, + _i2.FileChooserParams, + ) get onShowFileChooser => (super.noSuchMethod( + Invocation.getter(#onShowFileChooser), + returnValue: ( + _i2.WebChromeClient pigeon_instance, + _i2.WebView webView, + _i2.FileChooserParams params, + ) => + _i4.Future>.value([]), + ) as _i4.Future> Function( + _i2.WebChromeClient, + _i2.WebView, + _i2.FileChooserParams, + )); + + @override + _i4.Future Function(_i2.WebChromeClient, _i2.WebView, String, String) + get onJsConfirm => (super.noSuchMethod( + Invocation.getter(#onJsConfirm), + returnValue: ( + _i2.WebChromeClient pigeon_instance, + _i2.WebView webView, + String url, + String message, + ) => + _i4.Future.value(false), + ) as _i4.Future Function( + _i2.WebChromeClient, + _i2.WebView, + String, + String, + )); + @override _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( Invocation.getter(#pigeon_instanceManager), @@ -1013,10 +761,9 @@ class MockWebChromeClient extends _i1.Mock implements _i2.WebChromeClient { @override _i4.Future setSynchronousReturnValueForOnShowFileChooser(bool? value) => (super.noSuchMethod( - Invocation.method( - #setSynchronousReturnValueForOnShowFileChooser, - [value], - ), + Invocation.method(#setSynchronousReturnValueForOnShowFileChooser, [ + value, + ]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @@ -1024,10 +771,9 @@ class MockWebChromeClient extends _i1.Mock implements _i2.WebChromeClient { @override _i4.Future setSynchronousReturnValueForOnConsoleMessage(bool? value) => (super.noSuchMethod( - Invocation.method( - #setSynchronousReturnValueForOnConsoleMessage, - [value], - ), + Invocation.method(#setSynchronousReturnValueForOnConsoleMessage, [ + value, + ]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @@ -1035,10 +781,7 @@ class MockWebChromeClient extends _i1.Mock implements _i2.WebChromeClient { @override _i4.Future setSynchronousReturnValueForOnJsAlert(bool? value) => (super.noSuchMethod( - Invocation.method( - #setSynchronousReturnValueForOnJsAlert, - [value], - ), + Invocation.method(#setSynchronousReturnValueForOnJsAlert, [value]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @@ -1046,10 +789,9 @@ class MockWebChromeClient extends _i1.Mock implements _i2.WebChromeClient { @override _i4.Future setSynchronousReturnValueForOnJsConfirm(bool? value) => (super.noSuchMethod( - Invocation.method( - #setSynchronousReturnValueForOnJsConfirm, - [value], - ), + Invocation.method(#setSynchronousReturnValueForOnJsConfirm, [ + value, + ]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @@ -1057,26 +799,17 @@ class MockWebChromeClient extends _i1.Mock implements _i2.WebChromeClient { @override _i4.Future setSynchronousReturnValueForOnJsPrompt(bool? value) => (super.noSuchMethod( - Invocation.method( - #setSynchronousReturnValueForOnJsPrompt, - [value], - ), + Invocation.method(#setSynchronousReturnValueForOnJsPrompt, [value]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); @override _i2.WebChromeClient pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), returnValue: _FakeWebChromeClient_10( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), ) as _i2.WebChromeClient); } @@ -1100,7 +833,8 @@ class MockWebViewClient extends _i1.Mock implements _i2.WebViewClient { @override _i4.Future setSynchronousReturnValueForShouldOverrideUrlLoading( - bool? value) => + bool? value, + ) => (super.noSuchMethod( Invocation.method( #setSynchronousReturnValueForShouldOverrideUrlLoading, @@ -1112,16 +846,10 @@ class MockWebViewClient extends _i1.Mock implements _i2.WebViewClient { @override _i2.WebViewClient pigeon_copy() => (super.noSuchMethod( - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), returnValue: _FakeWebViewClient_11( this, - Invocation.method( - #pigeon_copy, - [], - ), + Invocation.method(#pigeon_copy, []), ), ) as _i2.WebViewClient); } @@ -1142,28 +870,16 @@ class MockJavascriptChannelRegistry extends _i1.Mock ) as Map); @override - void onJavascriptChannelMessage( - String? channel, - String? message, - ) => + void onJavascriptChannelMessage(String? channel, String? message) => super.noSuchMethod( - Invocation.method( - #onJavascriptChannelMessage, - [ - channel, - message, - ], - ), + Invocation.method(#onJavascriptChannelMessage, [channel, message]), returnValueForMissingStub: null, ); @override void updateJavascriptChannelsFromSet(Set<_i3.JavascriptChannel>? channels) => super.noSuchMethod( - Invocation.method( - #updateJavascriptChannelsFromSet, - [channels], - ), + Invocation.method(#updateJavascriptChannelsFromSet, [channels]), returnValueForMissingStub: null, ); } @@ -1183,50 +899,34 @@ class MockWebViewPlatformCallbacksHandler extends _i1.Mock required bool? isForMainFrame, }) => (super.noSuchMethod( - Invocation.method( - #onNavigationRequest, - [], - { - #url: url, - #isForMainFrame: isForMainFrame, - }, - ), + Invocation.method(#onNavigationRequest, [], { + #url: url, + #isForMainFrame: isForMainFrame, + }), returnValue: _i4.Future.value(false), ) as _i4.FutureOr); @override void onPageStarted(String? url) => super.noSuchMethod( - Invocation.method( - #onPageStarted, - [url], - ), + Invocation.method(#onPageStarted, [url]), returnValueForMissingStub: null, ); @override void onPageFinished(String? url) => super.noSuchMethod( - Invocation.method( - #onPageFinished, - [url], - ), + Invocation.method(#onPageFinished, [url]), returnValueForMissingStub: null, ); @override void onProgress(int? progress) => super.noSuchMethod( - Invocation.method( - #onProgress, - [progress], - ), + Invocation.method(#onProgress, [progress]), returnValueForMissingStub: null, ); @override void onWebResourceError(_i3.WebResourceError? error) => super.noSuchMethod( - Invocation.method( - #onWebResourceError, - [error], - ), + Invocation.method(#onWebResourceError, [error]), returnValueForMissingStub: null, ); } @@ -1241,92 +941,75 @@ class MockWebViewProxy extends _i1.Mock implements _i7.WebViewProxy { @override _i2.WebView createWebView() => (super.noSuchMethod( - Invocation.method( - #createWebView, - [], - ), + Invocation.method(#createWebView, []), returnValue: _FakeWebView_4( this, - Invocation.method( - #createWebView, - [], - ), + Invocation.method(#createWebView, []), ), ) as _i2.WebView); @override _i2.WebViewClient createWebViewClient({ - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onPageStarted, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? onPageFinished, + void Function(_i2.WebViewClient, _i2.WebView, String)? onPageStarted, + void Function(_i2.WebViewClient, _i2.WebView, String)? onPageFinished, void Function( _i2.WebViewClient, _i2.WebView, _i2.WebResourceRequest, _i2.WebResourceError, )? onReceivedRequestError, + void Function(_i2.WebViewClient, _i2.WebView, int, String, String)? + onReceivedError, + void Function(_i2.WebViewClient, _i2.WebView, _i2.WebResourceRequest)? + requestLoading, void Function( _i2.WebViewClient, _i2.WebView, - int, - String, - String, - )? onReceivedError, + _i2.AndroidMessage, + _i2.AndroidMessage, + )? onFormResubmission, + void Function(_i2.WebViewClient, _i2.WebView, _i2.ClientCertRequest)? + onReceivedClientCertRequest, void Function( _i2.WebViewClient, _i2.WebView, - _i2.WebResourceRequest, - )? requestLoading, - void Function( - _i2.WebViewClient, - _i2.WebView, - String, - )? urlLoading, + _i2.SslErrorHandler, + _i2.SslError, + )? onReceivedSslError, + void Function(_i2.WebViewClient, _i2.WebView, String)? urlLoading, }) => (super.noSuchMethod( - Invocation.method( - #createWebViewClient, - [], - { + Invocation.method(#createWebViewClient, [], { + #onPageStarted: onPageStarted, + #onPageFinished: onPageFinished, + #onReceivedRequestError: onReceivedRequestError, + #onReceivedError: onReceivedError, + #requestLoading: requestLoading, + #onFormResubmission: onFormResubmission, + #onReceivedClientCertRequest: onReceivedClientCertRequest, + #onReceivedSslError: onReceivedSslError, + #urlLoading: urlLoading, + }), + returnValue: _FakeWebViewClient_11( + this, + Invocation.method(#createWebViewClient, [], { #onPageStarted: onPageStarted, #onPageFinished: onPageFinished, #onReceivedRequestError: onReceivedRequestError, #onReceivedError: onReceivedError, #requestLoading: requestLoading, + #onFormResubmission: onFormResubmission, + #onReceivedClientCertRequest: onReceivedClientCertRequest, + #onReceivedSslError: onReceivedSslError, #urlLoading: urlLoading, - }, - ), - returnValue: _FakeWebViewClient_11( - this, - Invocation.method( - #createWebViewClient, - [], - { - #onPageStarted: onPageStarted, - #onPageFinished: onPageFinished, - #onReceivedRequestError: onReceivedRequestError, - #onReceivedError: onReceivedError, - #requestLoading: requestLoading, - #urlLoading: urlLoading, - }, - ), + }), ), ) as _i2.WebViewClient); @override _i4.Future setWebContentsDebuggingEnabled(bool? enabled) => (super.noSuchMethod( - Invocation.method( - #setWebContentsDebuggingEnabled, - [enabled], - ), + Invocation.method(#setWebContentsDebuggingEnabled, [enabled]), returnValue: _i4.Future.value(), returnValueForMissingStub: _i4.Future.value(), ) as _i4.Future); From 136c8de5cd20cae6e7296ef184efe1099822ae5c Mon Sep 17 00:00:00 2001 From: stuartmorgan-g Date: Mon, 14 Apr 2025 15:54:32 -0700 Subject: [PATCH 09/10] [tool] Run a config-only build before Xcode analyze (#9075) Currently xcode-analyze relies on the native project files already having been generated. This is unreliably locally, and now is problematic on CI as well since Xcode builds now (as of https://github.com/flutter/flutter/pull/165916) must match the last build mode, so analysis will fail if the previous CI step built in release mode (as is currently the case). This adds a config-only build call in debug mode before analyzing. Since running a config-only build is a common operation in the tool, this extracts a helper to abstract the logic. Unblocks the flutter/flutter->flutter/packages roller. --- .../lib/src/common/flutter_command_utils.dart | 46 ++++++++++++ script/tool/lib/src/fetch_deps_command.dart | 30 ++++---- .../lib/src/firebase_test_lab_command.dart | 31 ++++---- script/tool/lib/src/lint_android_command.dart | 10 ++- script/tool/lib/src/native_test_command.dart | 12 ++-- .../tool/lib/src/xcode_analyze_command.dart | 53 +++++++++----- .../test/firebase_test_lab_command_test.dart | 30 ++------ .../tool/test/xcode_analyze_command_test.dart | 72 +++++++++++++++++++ 8 files changed, 200 insertions(+), 84 deletions(-) create mode 100644 script/tool/lib/src/common/flutter_command_utils.dart diff --git a/script/tool/lib/src/common/flutter_command_utils.dart b/script/tool/lib/src/common/flutter_command_utils.dart new file mode 100644 index 000000000000..4c8ff7461470 --- /dev/null +++ b/script/tool/lib/src/common/flutter_command_utils.dart @@ -0,0 +1,46 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:platform/platform.dart'; + +import 'process_runner.dart'; +import 'repository_package.dart'; + +/// Runs the appropriate `flutter build --config-only` command for the given +/// target platform and build mode, to ensure that all of the native build files +/// are present for that mode. +/// +/// If [streamOutput] is false, output will only be printed if the command +/// fails. +Future runConfigOnlyBuild( + RepositoryPackage package, + ProcessRunner processRunner, + Platform platform, + FlutterPlatform targetPlatform, { + bool buildDebug = false, + List extraArgs = const [], +}) async { + final String flutterCommand = platform.isWindows ? 'flutter.bat' : 'flutter'; + + final String target = switch (targetPlatform) { + FlutterPlatform.android => 'apk', + FlutterPlatform.ios => 'ios', + FlutterPlatform.linux => 'linux', + FlutterPlatform.macos => 'macos', + FlutterPlatform.web => 'web', + FlutterPlatform.windows => 'windows', + }; + + final int exitCode = await processRunner.runAndStream( + flutterCommand, + [ + 'build', + target, + if (buildDebug) '--debug', + '--config-only', + ...extraArgs, + ], + workingDir: package.directory); + return exitCode == 0; +} diff --git a/script/tool/lib/src/fetch_deps_command.dart b/script/tool/lib/src/fetch_deps_command.dart index a6ac9b7a5203..ac57b35085bd 100644 --- a/script/tool/lib/src/fetch_deps_command.dart +++ b/script/tool/lib/src/fetch_deps_command.dart @@ -3,6 +3,7 @@ // found in the LICENSE file. import 'common/core.dart'; +import 'common/flutter_command_utils.dart'; import 'common/gradle.dart'; import 'common/output_utils.dart'; import 'common/package_looping_command.dart'; @@ -179,12 +180,9 @@ class FetchDepsCommand extends PackageLoopingCommand { processRunner: processRunner, platform: platform); if (!gradleProject.isConfigured()) { - final int exitCode = await processRunner.runAndStream( - flutterCommand, - ['build', 'apk', '--config-only'], - workingDir: example.directory, - ); - if (exitCode != 0) { + final bool buildSuccess = await runConfigOnlyBuild( + example, processRunner, platform, FlutterPlatform.android); + if (!buildSuccess) { printError('Unable to configure Gradle project.'); return PackageResult.fail(['Unable to configure Gradle.']); } @@ -203,23 +201,25 @@ class FetchDepsCommand extends PackageLoopingCommand { } Future _fetchDarwinDeps( - RepositoryPackage package, final String platform) async { - if (!pluginSupportsPlatform(platform, package, + RepositoryPackage package, final String platformString) async { + if (!pluginSupportsPlatform(platformString, package, requiredMode: PlatformSupport.inline)) { // Convert from the flag (lower case ios/macos) to the actual name. - final String displayPlatform = platform.replaceFirst('os', 'OS'); + final String displayPlatform = platformString.replaceFirst('os', 'OS'); return PackageResult.skip( 'Package does not have native $displayPlatform dependencies.'); } for (final RepositoryPackage example in package.getExamples()) { // Create the necessary native build files, which will run pub get and pod install if needed. - final int exitCode = await processRunner.runAndStream( - flutterCommand, - ['build', platform, '--config-only'], - workingDir: example.directory, - ); - if (exitCode != 0) { + final bool buildSuccess = await runConfigOnlyBuild( + example, + processRunner, + platform, + platformString == platformIOS + ? FlutterPlatform.ios + : FlutterPlatform.macos); + if (!buildSuccess) { printError('Unable to prepare native project files.'); return PackageResult.fail(['Unable to configure project.']); } diff --git a/script/tool/lib/src/firebase_test_lab_command.dart b/script/tool/lib/src/firebase_test_lab_command.dart index 3fb8e14cf3d5..445a5aec511a 100644 --- a/script/tool/lib/src/firebase_test_lab_command.dart +++ b/script/tool/lib/src/firebase_test_lab_command.dart @@ -8,6 +8,7 @@ import 'package:file/file.dart'; import 'package:uuid/uuid.dart'; import 'common/core.dart'; +import 'common/flutter_command_utils.dart'; import 'common/gradle.dart'; import 'common/output_utils.dart'; import 'common/package_looping_command.dart'; @@ -182,7 +183,7 @@ class FirebaseTestLabCommand extends PackageLoopingCommand { // Ensures that gradle wrapper exists final GradleProject project = GradleProject(example, processRunner: processRunner, platform: platform); - if (!await _ensureGradleWrapperExists(project)) { + if (!await _ensureGradleWrapperExists(example, project)) { return PackageResult.fail(['Unable to build example apk']); } @@ -245,26 +246,22 @@ class FirebaseTestLabCommand extends PackageLoopingCommand { /// Flutter build to generate it. /// /// Returns true if either gradlew was already present, or the build succeeds. - Future _ensureGradleWrapperExists(GradleProject project) async { + Future _ensureGradleWrapperExists( + RepositoryPackage package, GradleProject project) async { // Unconditionally re-run build with --debug --config-only, to ensure that // the project is in a debug state even if it was previously configured. print('Running flutter build apk...'); final String experiment = getStringArg(kEnableExperiment); - final int exitCode = await processRunner.runAndStream( - flutterCommand, - [ - 'build', - 'apk', - '--debug', - '--config-only', - if (experiment.isNotEmpty) '--enable-experiment=$experiment', - ], - workingDir: project.androidDirectory); - - if (exitCode != 0) { - return false; - } - return true; + return runConfigOnlyBuild( + package, + processRunner, + platform, + FlutterPlatform.android, + buildDebug: true, + extraArgs: [ + if (experiment.isNotEmpty) '--enable-experiment=$experiment', + ], + ); } /// Runs [test] from [example] as a Firebase Test Lab test, returning true if diff --git a/script/tool/lib/src/lint_android_command.dart b/script/tool/lib/src/lint_android_command.dart index b893d9b03157..e9d49b9b4591 100644 --- a/script/tool/lib/src/lint_android_command.dart +++ b/script/tool/lib/src/lint_android_command.dart @@ -3,6 +3,7 @@ // found in the LICENSE file. import 'common/core.dart'; +import 'common/flutter_command_utils.dart'; import 'common/gradle.dart'; import 'common/output_utils.dart'; import 'common/package_looping_command.dart'; @@ -41,12 +42,9 @@ class LintAndroidCommand extends PackageLoopingCommand { processRunner: processRunner, platform: platform); if (!project.isConfigured()) { - final int exitCode = await processRunner.runAndStream( - flutterCommand, - ['build', 'apk', '--config-only'], - workingDir: example.directory, - ); - if (exitCode != 0) { + final bool buildSuccess = await runConfigOnlyBuild( + example, processRunner, platform, FlutterPlatform.android); + if (!buildSuccess) { printError('Unable to configure Gradle project.'); return PackageResult.fail(['Unable to configure Gradle.']); } diff --git a/script/tool/lib/src/native_test_command.dart b/script/tool/lib/src/native_test_command.dart index d5995a35cd2a..6714b68f6075 100644 --- a/script/tool/lib/src/native_test_command.dart +++ b/script/tool/lib/src/native_test_command.dart @@ -9,6 +9,7 @@ import 'package:meta/meta.dart'; import 'common/cmake.dart'; import 'common/core.dart'; +import 'common/flutter_command_utils.dart'; import 'common/gradle.dart'; import 'common/output_utils.dart'; import 'common/package_looping_command.dart'; @@ -330,12 +331,13 @@ this command. platform: platform, ); if (!project.isConfigured()) { - final int exitCode = await processRunner.runAndStream( - flutterCommand, - ['build', 'apk', '--config-only'], - workingDir: example.directory, + final bool buildSuccess = await runConfigOnlyBuild( + example, + processRunner, + platform, + FlutterPlatform.android, ); - if (exitCode != 0) { + if (!buildSuccess) { printError('Unable to configure Gradle project.'); failed = true; continue; diff --git a/script/tool/lib/src/xcode_analyze_command.dart b/script/tool/lib/src/xcode_analyze_command.dart index 6d6bd4896498..7629a4e7346b 100644 --- a/script/tool/lib/src/xcode_analyze_command.dart +++ b/script/tool/lib/src/xcode_analyze_command.dart @@ -3,6 +3,7 @@ // found in the LICENSE file. import 'common/core.dart'; +import 'common/flutter_command_utils.dart'; import 'common/output_utils.dart'; import 'common/package_looping_command.dart'; import 'common/plugin_utils.dart'; @@ -74,19 +75,21 @@ class XcodeAnalyzeCommand extends PackageLoopingCommand { final List failures = []; if (testIOS && - !await _analyzePlugin(package, 'iOS', extraFlags: [ - '-destination', - 'generic/platform=iOS Simulator', - if (minIOSVersion.isNotEmpty) - 'IPHONEOS_DEPLOYMENT_TARGET=$minIOSVersion', - ])) { + !await _analyzePlugin(package, FlutterPlatform.ios, + extraFlags: [ + '-destination', + 'generic/platform=iOS Simulator', + if (minIOSVersion.isNotEmpty) + 'IPHONEOS_DEPLOYMENT_TARGET=$minIOSVersion', + ])) { failures.add('iOS'); } if (testMacOS && - !await _analyzePlugin(package, 'macOS', extraFlags: [ - if (minMacOSVersion.isNotEmpty) - 'MACOSX_DEPLOYMENT_TARGET=$minMacOSVersion', - ])) { + !await _analyzePlugin(package, FlutterPlatform.macos, + extraFlags: [ + if (minMacOSVersion.isNotEmpty) + 'MACOSX_DEPLOYMENT_TARGET=$minMacOSVersion', + ])) { failures.add('macOS'); } @@ -101,22 +104,40 @@ class XcodeAnalyzeCommand extends PackageLoopingCommand { /// Analyzes [plugin] for [targetPlatform], returning true if it passed analysis. Future _analyzePlugin( RepositoryPackage plugin, - String targetPlatform, { + FlutterPlatform targetPlatform, { List extraFlags = const [], }) async { + final String platformString = + targetPlatform == FlutterPlatform.ios ? 'iOS' : 'macOS'; bool passing = true; for (final RepositoryPackage example in plugin.getExamples()) { + // Unconditionally re-run build with --debug --config-only, to ensure that + // the project is in a debug state even if it was previously configured. + print('Running flutter build --config-only...'); + final bool buildSuccess = await runConfigOnlyBuild( + example, + processRunner, + platform, + targetPlatform, + buildDebug: true, + ); + if (!buildSuccess) { + printError('Unable to prepare native project files.'); + passing = false; + continue; + } + // Running tests and static analyzer. final String examplePath = getRelativePosixPath(example.directory, from: plugin.directory.parent); - print('Running $targetPlatform tests and analyzer for $examplePath...'); + print('Running $platformString tests and analyzer for $examplePath...'); final int exitCode = await _xcode.runXcodeBuild( example.directory, - targetPlatform, + platformString, // Clean before analyzing to remove cached swiftmodules from previous // runs, which can cause conflicts. actions: ['clean', 'analyze'], - workspace: '${targetPlatform.toLowerCase()}/Runner.xcworkspace', + workspace: '${platformString.toLowerCase()}/Runner.xcworkspace', scheme: 'Runner', configuration: 'Debug', hostPlatform: platform, @@ -126,9 +147,9 @@ class XcodeAnalyzeCommand extends PackageLoopingCommand { ], ); if (exitCode == 0) { - printSuccess('$examplePath ($targetPlatform) passed analysis.'); + printSuccess('$examplePath ($platformString) passed analysis.'); } else { - printError('$examplePath ($targetPlatform) failed analysis.'); + printError('$examplePath ($platformString) failed analysis.'); passing = false; } } diff --git a/script/tool/test/firebase_test_lab_command_test.dart b/script/tool/test/firebase_test_lab_command_test.dart index 13eeaa494ed2..f3d2b21e171e 100644 --- a/script/tool/test/firebase_test_lab_command_test.dart +++ b/script/tool/test/firebase_test_lab_command_test.dart @@ -167,11 +167,7 @@ public class MainActivityTest { ProcessCall( 'flutter', const ['build', 'apk', '--debug', '--config-only'], - plugin1 - .getExamples() - .first - .platformDirectory(FlutterPlatform.android) - .path), + plugin1.getExamples().first.directory.path), ProcessCall( 'gcloud', 'auth activate-service-account --key-file=/path/to/key' @@ -196,11 +192,7 @@ public class MainActivityTest { ProcessCall( 'flutter', const ['build', 'apk', '--debug', '--config-only'], - plugin2 - .getExamples() - .first - .platformDirectory(FlutterPlatform.android) - .path), + plugin2.getExamples().first.directory.path), ProcessCall( '/packages/plugin2/example/android/gradlew', 'app:assembleAndroidTest -Pverbose=true'.split(' '), @@ -264,11 +256,7 @@ public class MainActivityTest { ProcessCall( 'flutter', const ['build', 'apk', '--debug', '--config-only'], - plugin - .getExamples() - .first - .platformDirectory(FlutterPlatform.android) - .path), + plugin.getExamples().first.directory.path), ProcessCall( '/packages/plugin/example/android/gradlew', 'app:assembleAndroidTest -Pverbose=true'.split(' '), @@ -694,11 +682,7 @@ class MainActivityTest { ProcessCall( 'flutter', 'build apk --debug --config-only'.split(' '), - plugin - .getExamples() - .first - .platformDirectory(FlutterPlatform.android) - .path, + plugin.getExamples().first.directory.path, ), ProcessCall( '/packages/plugin/example/android/gradlew', @@ -878,11 +862,7 @@ class MainActivityTest { '--config-only', '--enable-experiment=exp1' ], - plugin - .getExamples() - .first - .platformDirectory(FlutterPlatform.android) - .path), + plugin.getExamples().first.directory.path), ProcessCall( '/packages/plugin/example/android/gradlew', 'app:assembleAndroidTest -Pverbose=true -Pextra-front-end-options=--enable-experiment%3Dexp1 -Pextra-gen-snapshot-options=--enable-experiment%3Dexp1' diff --git a/script/tool/test/xcode_analyze_command_test.dart b/script/tool/test/xcode_analyze_command_test.dart index a69ee23120da..7ffac396a592 100644 --- a/script/tool/test/xcode_analyze_command_test.dart +++ b/script/tool/test/xcode_analyze_command_test.dart @@ -105,6 +105,15 @@ void main() { expect( processRunner.recordedCalls, orderedEquals([ + ProcessCall( + 'flutter', + const [ + 'build', + 'ios', + '--debug', + '--config-only', + ], + pluginExampleDirectory.path), ProcessCall( 'xcrun', const [ @@ -146,6 +155,15 @@ void main() { expect( processRunner.recordedCalls, orderedEquals([ + ProcessCall( + 'flutter', + const [ + 'build', + 'ios', + '--debug', + '--config-only', + ], + pluginExampleDirectory.path), ProcessCall( 'xcrun', const [ @@ -245,6 +263,15 @@ void main() { expect( processRunner.recordedCalls, orderedEquals([ + ProcessCall( + 'flutter', + const [ + 'build', + 'macos', + '--debug', + '--config-only', + ], + pluginExampleDirectory.path), ProcessCall( 'xcrun', const [ @@ -280,6 +307,15 @@ void main() { expect( processRunner.recordedCalls, orderedEquals([ + ProcessCall( + 'flutter', + const [ + 'build', + 'macos', + '--debug', + '--config-only', + ], + pluginExampleDirectory.path), ProcessCall( 'xcrun', const [ @@ -353,6 +389,15 @@ void main() { expect( processRunner.recordedCalls, orderedEquals([ + ProcessCall( + 'flutter', + const [ + 'build', + 'ios', + '--debug', + '--config-only', + ], + pluginExampleDirectory.path), ProcessCall( 'xcrun', const [ @@ -370,6 +415,15 @@ void main() { 'GCC_TREAT_WARNINGS_AS_ERRORS=YES', ], pluginExampleDirectory.path), + ProcessCall( + 'flutter', + const [ + 'build', + 'macos', + '--debug', + '--config-only', + ], + pluginExampleDirectory.path), ProcessCall( 'xcrun', const [ @@ -411,6 +465,15 @@ void main() { expect( processRunner.recordedCalls, orderedEquals([ + ProcessCall( + 'flutter', + const [ + 'build', + 'macos', + '--debug', + '--config-only', + ], + pluginExampleDirectory.path), ProcessCall( 'xcrun', const [ @@ -451,6 +514,15 @@ void main() { expect( processRunner.recordedCalls, orderedEquals([ + ProcessCall( + 'flutter', + const [ + 'build', + 'ios', + '--debug', + '--config-only', + ], + pluginExampleDirectory.path), ProcessCall( 'xcrun', const [ From f23a97c9224a62503a2e7350084d50fd2d465ebe Mon Sep 17 00:00:00 2001 From: Maurice Parrish <10687576+bparrishMines@users.noreply.github.com> Date: Tue, 15 Apr 2025 12:17:18 -0600 Subject: [PATCH 10/10] [camera_android_camerax] Updates internal API wrapper to use ProxyApis (#8618) Also Fixes https://github.com/flutter/flutter/issues/164132 by passing a `TestInstanceManager` when needed. --- .../camera_android_camerax/CHANGELOG.md | 4 + .../android/build.gradle | 11 +- .../camerax/AnalyzerFlutterApiImpl.java | 74 - .../plugins/camerax/AnalyzerHostApiImpl.java | 119 - .../plugins/camerax/AnalyzerProxyApi.java | 64 + .../AspectRatioStrategyHostApiImpl.java | 65 - .../camerax/AspectRatioStrategyProxyApi.java | 88 + .../Camera2CameraControlHostApiImpl.java | 142 - .../camerax/Camera2CameraControlProxyApi.java | 65 + .../Camera2CameraInfoFlutterApiImpl.java | 30 - .../camerax/Camera2CameraInfoHostApiImpl.java | 123 - .../camerax/Camera2CameraInfoProxyApi.java | 65 + .../camerax/CameraAndroidCameraxPlugin.java | 246 +- .../CameraCharacteristicsProxyApi.java | 31 + .../camerax/CameraControlFlutterApiImpl.java | 29 - .../camerax/CameraControlHostApiImpl.java | 284 - .../camerax/CameraControlProxyApi.java | 161 + .../plugins/camerax/CameraFlutterApiImpl.java | 24 - .../plugins/camerax/CameraHostApiImpl.java | 61 - .../camerax/CameraInfoFlutterApiImpl.java | 29 - .../camerax/CameraInfoHostApiImpl.java | 95 - .../plugins/camerax/CameraInfoProxyApi.java | 45 + .../camerax/CameraIntegerRangeProxyApi.java | 35 + .../camerax/CameraPermissionsError.java | 45 + .../CameraPermissionsErrorProxyApi.java | 31 + .../camerax/CameraPermissionsManager.java | 22 +- .../plugins/camerax/CameraProxyApi.java | 33 + .../camerax/CameraSelectorFlutterApiImpl.java | 24 - .../camerax/CameraSelectorHostApiImpl.java | 63 - .../camerax/CameraSelectorProxyApi.java | 68 + .../plugins/camerax/CameraSizeProxyApi.java | 35 + .../CameraStateErrorFlutterApiWrapper.java | 57 - .../camerax/CameraStateFlutterApiWrapper.java | 102 - .../plugins/camerax/CameraStateProxyApi.java | 46 + .../CameraStateStateErrorProxyApi.java | 42 + .../plugins/camerax/CameraXLibrary.g.kt | 7207 +++++++++++ .../flutter/plugins/camerax/CameraXProxy.java | 94 - .../CaptureRequestOptionsHostApiImpl.java | 118 - .../CaptureRequestOptionsProxyApi.java | 59 + .../camerax/CaptureRequestProxyApi.java | 25 + .../camerax/DeviceOrientationManager.java | 67 +- ...eviceOrientationManagerFlutterApiImpl.java | 20 - .../DeviceOrientationManagerHostApiImpl.java | 117 - .../DeviceOrientationManagerProxyApi.java | 53 + ...yOrientedMeteringPointFactoryProxyApi.java | 42 + .../camerax/ExposureStateFlutterApiImpl.java | 49 - .../camerax/ExposureStateProxyApi.java | 31 + .../camerax/FallbackStrategyHostApiImpl.java | 80 - .../camerax/FallbackStrategyProxyApi.java | 64 + .../FocusMeteringActionBuilderProxyApi.java | 72 + .../FocusMeteringActionHostApiImpl.java | 124 - .../camerax/FocusMeteringActionProxyApi.java | 46 + .../FocusMeteringResultFlutterApiImpl.java | 55 - .../FocusMeteringResultHostApiImpl.java | 65 - .../camerax/FocusMeteringResultProxyApi.java | 24 + .../camerax/ImageAnalysisHostApiImpl.java | 114 - .../camerax/ImageAnalysisProxyApi.java | 75 + .../camerax/ImageCaptureHostApiImpl.java | 143 - .../plugins/camerax/ImageCaptureProxyApi.java | 137 + .../camerax/ImageProxyFlutterApiImpl.java | 67 - .../camerax/ImageProxyHostApiImpl.java | 82 - .../plugins/camerax/ImageProxyProxyApi.java | 48 + .../plugins/camerax/InstanceManager.java | 287 - .../camerax/JavaObjectHostApiImpl.java | 33 - .../camerax/LiveDataFlutterApiWrapper.java | 61 - .../plugins/camerax/LiveDataHostApiImpl.java | 115 - .../plugins/camerax/LiveDataProxyApi.java | 81 + .../camerax/MeteringPointFactoryProxyApi.java | 33 + .../camerax/MeteringPointHostApiImpl.java | 137 - .../camerax/MeteringPointProxyApi.java | 24 + .../camerax/ObserverFlutterApiWrapper.java | 112 - .../plugins/camerax/ObserverHostApiImpl.java | 102 - .../plugins/camerax/ObserverProxyApi.java | 64 + .../PendingRecordingFlutterApiImpl.java | 37 - .../camerax/PendingRecordingHostApiImpl.java | 107 - .../camerax/PendingRecordingProxyApi.java | 35 + .../camerax/PlaneProxyFlutterApiImpl.java | 67 - .../plugins/camerax/PlaneProxyProxyApi.java | 41 + .../plugins/camerax/PreviewHostApiImpl.java | 199 - .../plugins/camerax/PreviewProxyApi.java | 167 + .../ProcessCameraProviderFlutterApiImpl.java | 24 - .../ProcessCameraProviderHostApiImpl.java | 176 - .../ProcessCameraProviderProxyApi.java | 92 + .../plugins/camerax/ProxyApiRegistrar.java | 424 + .../camerax/ProxyLifecycleProvider.java | 3 +- .../camerax/QualitySelectorHostApiImpl.java | 141 - .../camerax/QualitySelectorProxyApi.java | 80 + .../camerax/RecorderFlutterApiImpl.java | 29 - .../plugins/camerax/RecorderHostApiImpl.java | 129 - .../plugins/camerax/RecorderProxyApi.java | 95 + .../camerax/RecordingFlutterApiImpl.java | 24 - .../plugins/camerax/RecordingHostApiImpl.java | 50 - .../plugins/camerax/RecordingProxyApi.java | 39 + .../camerax/ResolutionFilterHostApiImpl.java | 94 - .../camerax/ResolutionFilterProxyApi.java | 40 + .../camerax/ResolutionInfoProxyApi.java | 26 + .../ResolutionSelectorHostApiImpl.java | 96 - .../camerax/ResolutionSelectorProxyApi.java | 60 + .../ResolutionStrategyHostApiImpl.java | 81 - .../camerax/ResolutionStrategyProxyApi.java | 78 + .../flutter/plugins/camerax/ResultCompat.kt | 47 + .../camerax/SystemServicesFlutterApiImpl.java | 19 - .../camerax/SystemServicesHostApiImpl.java | 106 - .../camerax/SystemServicesManager.java | 60 + .../SystemServicesManagerProxyApi.java | 110 + .../camerax/VideoCaptureFlutterApiImpl.java | 25 - .../camerax/VideoCaptureHostApiImpl.java | 65 - .../plugins/camerax/VideoCaptureProxyApi.java | 37 + .../camerax/VideoRecordEventListener.java | 12 + .../VideoRecordEventListenerProxyApi.java | 66 + .../camerax/ZoomStateFlutterApiImpl.java | 38 - .../plugins/camerax/ZoomStateProxyApi.java | 29 + .../src/test/java/android/util/Range.java | 25 + .../src/test/java/android/util/Rational.java | 22 + .../src/test/java/android/util/Size.java | 39 + .../flutter/plugins/camerax/AnalyzerTest.java | 94 +- .../camerax/AspectRatioStrategyTest.java | 58 +- .../camerax/Camera2CameraControlTest.java | 131 +- .../camerax/Camera2CameraInfoTest.java | 93 +- .../CameraAndroidCameraxPluginTest.java | 350 +- .../plugins/camerax/CameraControlTest.java | 415 +- .../plugins/camerax/CameraInfoTest.java | 116 +- .../camerax/CameraIntegerRangeTest.java | 48 + .../camerax/CameraPermissionsErrorTest.java | 33 + .../camerax/CameraPermissionsManagerTest.java | 21 +- .../plugins/camerax/CameraSelectorTest.java | 85 +- .../plugins/camerax/CameraSizeTest.java | 48 + .../plugins/camerax/CameraStateErrorTest.java | 57 - .../camerax/CameraStateStateErrorTest.java | 27 + .../plugins/camerax/CameraStateTest.java | 94 +- .../flutter/plugins/camerax/CameraTest.java | 75 +- .../camerax/CaptureRequestOptionsTest.java | 104 +- .../DeviceOrientationManagerApiTest.java | 85 + .../camerax/DeviceOrientationManagerTest.java | 49 +- .../DeviceOrientationManagerWrapperTest.java | 108 - .../plugins/camerax/ExposureStateTest.java | 75 +- .../plugins/camerax/FallbackStrategyTest.java | 147 +- .../FocusMeteringActionBuilderTest.java | 64 + .../camerax/FocusMeteringActionTest.java | 189 +- .../camerax/FocusMeteringResultTest.java | 63 +- .../plugins/camerax/ImageAnalysisTest.java | 115 +- .../plugins/camerax/ImageCaptureTest.java | 342 +- .../plugins/camerax/ImageProxyTest.java | 121 +- .../plugins/camerax/InstanceManagerTest.java | 140 - .../camerax/JavaObjectHostApiTest.java | 32 - .../flutter/plugins/camerax/LiveDataTest.java | 177 +- .../camerax/MeteringPointFactoryTest.java | 44 + .../plugins/camerax/MeteringPointTest.java | 218 +- .../flutter/plugins/camerax/ObserverTest.java | 124 +- .../plugins/camerax/PendingRecordingTest.java | 131 +- .../plugins/camerax/PlaneProxyTest.java | 58 +- .../flutter/plugins/camerax/PreviewTest.java | 247 +- .../camerax/ProcessCameraProviderTest.java | 196 +- .../plugins/camerax/QualitySelectorTest.java | 134 +- .../flutter/plugins/camerax/RecorderTest.java | 179 +- .../plugins/camerax/RecordingTest.java | 100 +- .../plugins/camerax/ResolutionFilterTest.java | 48 +- .../plugins/camerax/ResolutionInfoTest.java | 26 + .../camerax/ResolutionSelectorTest.java | 92 +- .../camerax/ResolutionStrategyTest.java | 78 +- .../plugins/camerax/SystemServicesTest.java | 148 +- .../camerax/TestProxyApiRegistrar.java | 32 + .../plugins/camerax/VideoCaptureTest.java | 103 +- .../camerax/VideoRecordEventListenerTest.java | 40 + .../plugins/camerax/ZoomStateTest.java | 61 +- .../example/android/app/build.gradle | 5 + .../cameraxexample/InstanceManagerTest.java | 43 - .../example/lib/main.dart | 3 +- .../lib/src/analyzer.dart | 142 - .../lib/src/android_camera_camerax.dart | 825 +- ...roid_camera_camerax_flutter_api_impls.dart | 219 - .../lib/src/aspect_ratio_strategy.dart | 138 - .../lib/src/camera.dart | 121 - .../lib/src/camera2_camera_control.dart | 135 - .../lib/src/camera2_camera_info.dart | 140 - .../lib/src/camera_control.dart | 229 - .../lib/src/camera_info.dart | 140 - .../lib/src/camera_metadata.dart | 42 - .../lib/src/camera_selector.dart | 203 - .../lib/src/camera_state.dart | 127 - .../lib/src/camera_state_error.dart | 115 - .../lib/src/camerax_library.dart | 206 + .../lib/src/camerax_library.g.dart | 10684 ++++++++++++---- .../lib/src/camerax_proxy.dart | 717 +- .../lib/src/capture_request_options.dart | 139 - .../lib/src/device_orientation_manager.dart | 131 - .../lib/src/exposure_state.dart | 78 - .../lib/src/fallback_strategy.dart | 88 - .../lib/src/focus_metering_action.dart | 131 - .../lib/src/focus_metering_result.dart | 108 - .../lib/src/image_analysis.dart | 155 - .../lib/src/image_capture.dart | 195 - .../lib/src/image_proxy.dart | 146 - .../lib/src/instance_manager.dart | 197 - .../lib/src/java_object.dart | 84 - .../lib/src/live_data.dart | 193 - .../lib/src/metering_point.dart | 127 - .../lib/src/observer.dart | 132 - .../lib/src/pending_recording.dart | 115 - .../lib/src/plane_proxy.dart | 94 - .../lib/src/preview.dart | 171 - .../lib/src/process_camera_provider.dart | 222 - .../lib/src/quality_selector.dart | 145 - .../lib/src/recorder.dart | 179 - .../lib/src/recording.dart | 122 - .../lib/src/resolution_filter.dart | 107 - .../lib/src/resolution_selector.dart | 120 - .../lib/src/resolution_strategy.dart | 189 - .../lib/src/rotated_preview.dart | 10 +- .../lib/src/surface.dart | 37 - .../lib/src/system_services.dart | 92 - .../lib/src/use_case.dart | 17 - .../lib/src/video_capture.dart | 134 - .../lib/src/zoom_state.dart | 73 - .../pigeons/camerax_library.dart | 1405 +- .../pigeons/copyright.txt | 3 + .../camera_android_camerax/pubspec.yaml | 4 +- .../test/analyzer_test.dart | 116 - .../test/analyzer_test.mocks.dart | 59 - .../test/android_camera_camerax_test.dart | 9552 +++++++++----- .../android_camera_camerax_test.mocks.dart | 4124 ++++-- .../test/aspect_ratio_strategy_test.dart | 84 - .../aspect_ratio_strategy_test.mocks.dart | 68 - .../test/camera2_camera_control_test.dart | 126 - .../camera2_camera_control_test.mocks.dart | 169 - .../test/camera2_camera_info_test.dart | 155 - .../test/camera2_camera_info_test.mocks.dart | 188 - .../test/camera_control_test.dart | 306 - .../test/camera_control_test.mocks.dart | 148 - .../test/camera_info_test.dart | 178 - .../test/camera_info_test.mocks.dart | 156 - .../test/camera_selector_test.dart | 124 - .../test/camera_selector_test.mocks.dart | 82 - .../test/camera_state_error_test.dart | 53 - .../test/camera_state_error_test.mocks.dart | 40 - .../test/camera_state_test.dart | 68 - .../test/camera_state_test.mocks.dart | 40 - .../test/camera_test.dart | 104 - .../test/camera_test.mocks.dart | 67 - .../test/capture_request_options_test.dart | 143 - .../capture_request_options_test.mocks.dart | 66 - .../test/device_orientation_manager_test.dart | 99 - ...device_orientation_manager_test.mocks.dart | 100 - .../test/exposure_state_test.dart | 49 - .../test/exposure_state_test.mocks.dart | 40 - .../test/fallback_strategy_test.dart | 76 - .../test/fallback_strategy_test.mocks.dart | 69 - .../test/focus_metering_action_test.dart | 107 - .../focus_metering_action_test.mocks.dart | 112 - .../test/focus_metering_result_test.dart | 76 - .../focus_metering_result_test.mocks.dart | 102 - .../test/image_analysis_test.dart | 190 - .../test/image_analysis_test.mocks.dart | 121 - .../test/image_capture_test.dart | 154 - .../test/image_capture_test.mocks.dart | 132 - .../test/image_proxy_test.dart | 128 - .../test/image_proxy_test.mocks.dart | 68 - .../test/instance_manager_test.dart | 174 - .../test/live_data_test.dart | 162 - .../test/live_data_test.mocks.dart | 89 - .../test/metering_point_test.dart | 94 - .../test/metering_point_test.mocks.dart | 176 - .../test/observer_test.dart | 114 - .../test/observer_test.mocks.dart | 59 - .../test/pending_recording_test.dart | 65 - .../test/pending_recording_test.mocks.dart | 112 - .../test/plane_proxy_test.dart | 46 - .../test/plane_proxy_test.mocks.dart | 40 - .../test/preview_rotation_test.dart | 1332 +- .../test/preview_test.dart | 188 - .../test/preview_test.mocks.dart | 150 - .../test/process_camera_provider_test.dart | 236 - .../process_camera_provider_test.mocks.dart | 129 - .../test/quality_selector_test.dart | 194 - .../test/quality_selector_test.mocks.dart | 223 - .../test/recorder_test.dart | 167 - .../test/recorder_test.mocks.dart | 253 - .../test/recording_test.dart | 119 - .../test/recording_test.mocks.dart | 86 - .../test/resolution_filter_test.dart | 90 - .../test/resolution_filter_test.mocks.dart | 67 - .../test/resolution_selector_test.dart | 140 - .../test/resolution_selector_test.mocks.dart | 138 - .../test/resolution_strategy_test.dart | 109 - .../test/resolution_strategy_test.mocks.dart | 69 - .../test/system_services_test.dart | 88 - .../test/system_services_test.mocks.dart | 90 - .../test/test_camerax_library.g.dart | 2583 ---- .../test/video_capture_test.dart | 116 - .../test/video_capture_test.mocks.dart | 126 - .../test/zoom_state_test.dart | 40 - .../test/zoom_state_test.mocks.dart | 40 - 292 files changed, 32682 insertions(+), 33772 deletions(-) delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AnalyzerFlutterApiImpl.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AnalyzerHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AnalyzerProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AspectRatioStrategyHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AspectRatioStrategyProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/Camera2CameraControlHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/Camera2CameraControlProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/Camera2CameraInfoFlutterApiImpl.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/Camera2CameraInfoHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/Camera2CameraInfoProxyApi.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraCharacteristicsProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraControlFlutterApiImpl.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraControlHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraControlProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraFlutterApiImpl.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraHostApiImpl.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraInfoFlutterApiImpl.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraInfoHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraInfoProxyApi.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraIntegerRangeProxyApi.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraPermissionsError.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraPermissionsErrorProxyApi.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraSelectorFlutterApiImpl.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraSelectorHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraSelectorProxyApi.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraSizeProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraStateErrorFlutterApiWrapper.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraStateFlutterApiWrapper.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraStateProxyApi.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraStateStateErrorProxyApi.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraXLibrary.g.kt delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraXProxy.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CaptureRequestOptionsHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CaptureRequestOptionsProxyApi.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CaptureRequestProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManagerFlutterApiImpl.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManagerHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManagerProxyApi.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DisplayOrientedMeteringPointFactoryProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ExposureStateFlutterApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ExposureStateProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FallbackStrategyHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FallbackStrategyProxyApi.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringActionBuilderProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringActionHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringActionProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringResultFlutterApiImpl.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringResultHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringResultProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageAnalysisHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageAnalysisProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageCaptureHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageCaptureProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageProxyFlutterApiImpl.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageProxyHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageProxyProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/InstanceManager.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/JavaObjectHostApiImpl.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/LiveDataFlutterApiWrapper.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/LiveDataHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/LiveDataProxyApi.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/MeteringPointFactoryProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/MeteringPointHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/MeteringPointProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ObserverFlutterApiWrapper.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ObserverHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ObserverProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PendingRecordingFlutterApiImpl.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PendingRecordingHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PendingRecordingProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PlaneProxyFlutterApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PlaneProxyProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PreviewHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PreviewProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProcessCameraProviderFlutterApiImpl.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProcessCameraProviderHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProcessCameraProviderProxyApi.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProxyApiRegistrar.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/QualitySelectorHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/QualitySelectorProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecorderFlutterApiImpl.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecorderHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecorderProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecordingFlutterApiImpl.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecordingHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecordingProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionFilterHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionFilterProxyApi.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionInfoProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionSelectorHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionSelectorProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionStrategyHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionStrategyProxyApi.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResultCompat.kt delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesFlutterApiImpl.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesManager.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesManagerProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoCaptureFlutterApiImpl.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoCaptureHostApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoCaptureProxyApi.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoRecordEventListener.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoRecordEventListenerProxyApi.java delete mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ZoomStateFlutterApiImpl.java create mode 100644 packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ZoomStateProxyApi.java create mode 100644 packages/camera/camera_android_camerax/android/src/test/java/android/util/Range.java create mode 100644 packages/camera/camera_android_camerax/android/src/test/java/android/util/Rational.java create mode 100644 packages/camera/camera_android_camerax/android/src/test/java/android/util/Size.java create mode 100644 packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraIntegerRangeTest.java create mode 100644 packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraPermissionsErrorTest.java create mode 100644 packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraSizeTest.java delete mode 100644 packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraStateErrorTest.java create mode 100644 packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraStateStateErrorTest.java create mode 100644 packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/DeviceOrientationManagerApiTest.java delete mode 100644 packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/DeviceOrientationManagerWrapperTest.java create mode 100644 packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/FocusMeteringActionBuilderTest.java delete mode 100644 packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/InstanceManagerTest.java delete mode 100644 packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/JavaObjectHostApiTest.java create mode 100644 packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/MeteringPointFactoryTest.java create mode 100644 packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ResolutionInfoTest.java create mode 100644 packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/TestProxyApiRegistrar.java create mode 100644 packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/VideoRecordEventListenerTest.java delete mode 100644 packages/camera/camera_android_camerax/example/android/app/src/androidTest/java/io/flutter/plugins/cameraxexample/InstanceManagerTest.java delete mode 100644 packages/camera/camera_android_camerax/lib/src/analyzer.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/android_camera_camerax_flutter_api_impls.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/aspect_ratio_strategy.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/camera.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/camera2_camera_control.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/camera2_camera_info.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/camera_control.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/camera_info.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/camera_metadata.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/camera_selector.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/camera_state.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/camera_state_error.dart create mode 100644 packages/camera/camera_android_camerax/lib/src/camerax_library.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/capture_request_options.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/device_orientation_manager.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/exposure_state.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/fallback_strategy.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/focus_metering_action.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/focus_metering_result.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/image_analysis.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/image_capture.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/image_proxy.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/instance_manager.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/java_object.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/live_data.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/metering_point.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/observer.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/pending_recording.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/plane_proxy.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/preview.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/process_camera_provider.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/quality_selector.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/recorder.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/recording.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/resolution_filter.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/resolution_selector.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/resolution_strategy.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/surface.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/system_services.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/use_case.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/video_capture.dart delete mode 100644 packages/camera/camera_android_camerax/lib/src/zoom_state.dart create mode 100644 packages/camera/camera_android_camerax/pigeons/copyright.txt delete mode 100644 packages/camera/camera_android_camerax/test/analyzer_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/analyzer_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/aspect_ratio_strategy_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/aspect_ratio_strategy_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/camera2_camera_control_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/camera2_camera_control_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/camera2_camera_info_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/camera2_camera_info_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/camera_control_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/camera_control_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/camera_info_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/camera_info_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/camera_selector_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/camera_selector_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/camera_state_error_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/camera_state_error_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/camera_state_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/camera_state_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/camera_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/camera_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/capture_request_options_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/capture_request_options_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/device_orientation_manager_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/device_orientation_manager_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/exposure_state_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/exposure_state_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/fallback_strategy_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/fallback_strategy_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/focus_metering_action_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/focus_metering_action_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/focus_metering_result_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/focus_metering_result_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/image_analysis_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/image_analysis_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/image_capture_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/image_capture_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/image_proxy_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/image_proxy_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/instance_manager_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/live_data_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/live_data_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/metering_point_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/metering_point_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/observer_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/observer_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/pending_recording_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/pending_recording_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/plane_proxy_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/plane_proxy_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/preview_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/preview_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/process_camera_provider_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/process_camera_provider_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/quality_selector_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/quality_selector_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/recorder_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/recorder_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/recording_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/recording_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/resolution_filter_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/resolution_filter_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/resolution_selector_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/resolution_selector_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/resolution_strategy_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/resolution_strategy_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/system_services_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/system_services_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/test_camerax_library.g.dart delete mode 100644 packages/camera/camera_android_camerax/test/video_capture_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/video_capture_test.mocks.dart delete mode 100644 packages/camera/camera_android_camerax/test/zoom_state_test.dart delete mode 100644 packages/camera/camera_android_camerax/test/zoom_state_test.mocks.dart diff --git a/packages/camera/camera_android_camerax/CHANGELOG.md b/packages/camera/camera_android_camerax/CHANGELOG.md index f678aeef8d33..d6bfb8b94c9d 100644 --- a/packages/camera/camera_android_camerax/CHANGELOG.md +++ b/packages/camera/camera_android_camerax/CHANGELOG.md @@ -1,3 +1,7 @@ +## 0.6.15 + +* Updates internal API wrapper to use ProxyApis. + ## 0.6.14+1 * Updates compileSdk 34 to flutter.compileSdkVersion. diff --git a/packages/camera/camera_android_camerax/android/build.gradle b/packages/camera/camera_android_camerax/android/build.gradle index 8685e8481d05..b9970ae697e6 100644 --- a/packages/camera/camera_android_camerax/android/build.gradle +++ b/packages/camera/camera_android_camerax/android/build.gradle @@ -2,6 +2,7 @@ group 'io.flutter.plugins.camerax' version '1.0' buildscript { + ext.kotlin_version = '1.9.10' repositories { google() mavenCentral() @@ -9,6 +10,7 @@ buildscript { dependencies { classpath 'com.android.tools.build:gradle:8.5.0' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } @@ -20,6 +22,7 @@ rootProject.allprojects { } apply plugin: 'com.android.library' +apply plugin: 'kotlin-android' android { namespace 'io.flutter.plugins.camerax' @@ -31,6 +34,11 @@ android { targetCompatibility JavaVersion.VERSION_11 } + kotlinOptions { + // This must match the Java version provided in compileOptions. + jvmTarget = '11' + } + defaultConfig { // Many of the CameraX APIs require API 21. minSdkVersion 21 @@ -65,7 +73,8 @@ dependencies { implementation "androidx.camera:camera-video:${camerax_version}" implementation 'com.google.guava:guava:33.4.0-android' testImplementation 'junit:junit:4.13.2' - testImplementation 'org.mockito:mockito-inline:5.0.0' + testImplementation "org.mockito:mockito-core:5.15.2" + testImplementation 'org.mockito:mockito-inline:5.1.0' testImplementation 'androidx.test:core:1.4.0' testImplementation 'org.robolectric:robolectric:4.10.3' } diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AnalyzerFlutterApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AnalyzerFlutterApiImpl.java deleted file mode 100644 index 7bdb8626469a..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AnalyzerFlutterApiImpl.java +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.annotation.VisibleForTesting; -import androidx.camera.core.ImageAnalysis; -import androidx.camera.core.ImageProxy; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.AnalyzerFlutterApi; -import java.util.Objects; - -/** - * Flutter API implementation for {@link ImageAnalysis.Analyzer}. - * - *

This class may handle adding native instances that are attached to a Dart instance or passing - * arguments of callbacks methods to a Dart instance. - */ -public class AnalyzerFlutterApiImpl { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - private AnalyzerFlutterApi api; - - /** - * Constructs a {@link AnalyzerFlutterApiImpl}. - * - * @param binaryMessenger used to communicate with Dart over asynchronous messages - * @param instanceManager maintains instances stored to communicate with attached Dart objects - */ - public AnalyzerFlutterApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - api = new AnalyzerFlutterApi(binaryMessenger); - } - - /** - * Stores the {@link ImageAnalysis.Analyzer} instance and notifies Dart to create and store a new - * {@code Analyzer} instance that is attached to this one. If {@code instance} has already been - * added, this method does nothing. - */ - public void create( - @NonNull ImageAnalysis.Analyzer instance, @NonNull AnalyzerFlutterApi.Reply callback) { - if (!instanceManager.containsInstance(instance)) { - api.create(instanceManager.addHostCreatedInstance(instance), callback); - } - } - - /** - * Sends a message to Dart to call {@code Analyzer.analyze} on the Dart object representing - * `instance`. - */ - public void analyze( - @NonNull ImageAnalysis.Analyzer analyzerInstance, - @NonNull ImageProxy imageProxyInstance, - @NonNull AnalyzerFlutterApi.Reply callback) { - api.analyze( - Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(analyzerInstance)), - Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(imageProxyInstance)), - callback); - } - - /** - * Sets the Flutter API used to send messages to Dart. - * - *

This is only visible for testing. - */ - @VisibleForTesting - void setApi(@NonNull AnalyzerFlutterApi api) { - this.api = api; - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AnalyzerHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AnalyzerHostApiImpl.java deleted file mode 100644 index fa788a244f97..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AnalyzerHostApiImpl.java +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.annotation.VisibleForTesting; -import androidx.camera.core.ImageAnalysis; -import androidx.camera.core.ImageProxy; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.AnalyzerHostApi; - -/** - * Host API implementation for {@link ImageAnalysis.Analyzer}. - * - *

This class may handle instantiating and adding native object instances that are attached to a - * Dart instance or handle method calls on the associated native class or an instance of the class. - */ -public class AnalyzerHostApiImpl implements AnalyzerHostApi { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - private final AnalyzerProxy proxy; - - /** Proxy for constructor of {@link ImageAnalysis.Analyzer}. */ - @VisibleForTesting - public static class AnalyzerProxy { - - /** Creates an instance of {@link AnalyzerImpl}. */ - @NonNull - public AnalyzerImpl create( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - return new AnalyzerImpl(binaryMessenger, instanceManager); - } - } - - /** - * Implementation of {@link ImageAnalysis.Analyzer} that passes arguments of callback methods to - * Dart. - */ - public static class AnalyzerImpl implements ImageAnalysis.Analyzer { - private BinaryMessenger binaryMessenger; - private InstanceManager instanceManager; - private AnalyzerFlutterApiImpl api; - - @VisibleForTesting @NonNull public ImageProxyFlutterApiImpl imageProxyApi; - - /** - * Constructs an instance of {@link ImageAnalysis.Analyzer} that passes arguments of callbacks - * methods to Dart. - */ - public AnalyzerImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - super(); - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - api = new AnalyzerFlutterApiImpl(binaryMessenger, instanceManager); - imageProxyApi = new ImageProxyFlutterApiImpl(binaryMessenger, instanceManager); - } - - @Override - public void analyze(@NonNull ImageProxy imageProxy) { - Long imageFormat = Long.valueOf(imageProxy.getFormat()); - Long imageHeight = Long.valueOf(imageProxy.getHeight()); - Long imageWidth = Long.valueOf(imageProxy.getWidth()); - imageProxyApi.create(imageProxy, imageFormat, imageHeight, imageWidth, reply -> {}); - - api.analyze(this, imageProxy, reply -> {}); - } - - /** - * Flutter API used to send messages back to Dart. - * - *

This is only visible for testing. - */ - @VisibleForTesting - void setApi(@NonNull AnalyzerFlutterApiImpl api) { - this.api = api; - } - } - - /** - * Constructs a {@link AnalyzerHostApiImpl}. - * - * @param binaryMessenger used to communicate with Dart over asynchronous messages - * @param instanceManager maintains instances stored to communicate with attached Dart objects - */ - public AnalyzerHostApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - this(binaryMessenger, instanceManager, new AnalyzerProxy()); - } - - /** - * Constructs a {@link AnalyzerHostApiImpl}. - * - * @param binaryMessenger used to communicate with Dart over asynchronous messages - * @param instanceManager maintains instances stored to communicate with attached Dart objects - * @param proxy proxy for constructor of {@link ImageAnalysis.Analyzer} - */ - @VisibleForTesting - AnalyzerHostApiImpl( - @NonNull BinaryMessenger binaryMessenger, - @NonNull InstanceManager instanceManager, - @NonNull AnalyzerProxy proxy) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - this.proxy = proxy; - } - - /** - * Creates an {@link AnalyzerProxy} that represents an {@link ImageAnalysis.Analyzer} instance - * with the specified identifier. - */ - @Override - public void create(@NonNull Long identifier) { - instanceManager.addDartCreatedInstance( - proxy.create(binaryMessenger, instanceManager), identifier); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AnalyzerProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AnalyzerProxyApi.java new file mode 100644 index 000000000000..61a217393fde --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AnalyzerProxyApi.java @@ -0,0 +1,64 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.camera.core.ImageAnalysis.Analyzer; +import java.util.Objects; + +/** + * ProxyApi implementation for {@link Analyzer}. This class may handle instantiating native object + * instances that are attached to a Dart instance or handle method calls on the associated native + * class or an instance of that class. + */ +class AnalyzerProxyApi extends PigeonApiAnalyzer { + AnalyzerProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public ProxyApiRegistrar getPigeonRegistrar() { + return (ProxyApiRegistrar) super.getPigeonRegistrar(); + } + + /** Implementation of {@link Analyzer} that passes arguments of callback methods to Dart. */ + static class AnalyzerImpl implements Analyzer { + final AnalyzerProxyApi api; + + AnalyzerImpl(@NonNull AnalyzerProxyApi api) { + this.api = api; + } + + @Override + public void analyze(@NonNull androidx.camera.core.ImageProxy image) { + api.getPigeonRegistrar() + .runOnMainThread( + new ProxyApiRegistrar.FlutterMethodRunnable() { + @Override + public void run() { + api.analyze( + AnalyzerImpl.this, + image, + ResultCompat.asCompatCallback( + result -> { + if (result.isFailure()) { + onFailure( + "Analyzer.analyze", + Objects.requireNonNull(result.exceptionOrNull())); + } + return null; + })); + } + }); + } + } + + @NonNull + @Override + public Analyzer pigeon_defaultConstructor() { + return new AnalyzerImpl(this); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AspectRatioStrategyHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AspectRatioStrategyHostApiImpl.java deleted file mode 100644 index 7775ffe598db..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AspectRatioStrategyHostApiImpl.java +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.annotation.VisibleForTesting; -import androidx.camera.core.resolutionselector.AspectRatioStrategy; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.AspectRatioStrategyHostApi; - -/** - * Host API implementation for {@link AspectRatioStrategy}. - * - *

This class handles instantiating and adding native object instances that are attached to a - * Dart instance or handle method calls on the associated native class or an instance of the class. - */ -public class AspectRatioStrategyHostApiImpl implements AspectRatioStrategyHostApi { - private final InstanceManager instanceManager; - private final AspectRatioStrategyProxy proxy; - - /** Proxy for constructor of {@link AspectRatioStrategy}. */ - @VisibleForTesting - public static class AspectRatioStrategyProxy { - /** Creates an instance of {@link AspectRatioStrategy}. */ - @NonNull - public AspectRatioStrategy create( - @NonNull Long preferredAspectRatio, @NonNull Long fallbackRule) { - return new AspectRatioStrategy(preferredAspectRatio.intValue(), fallbackRule.intValue()); - } - } - - /** - * Constructs an {@link AspectRatioStrategyHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - */ - public AspectRatioStrategyHostApiImpl(@NonNull InstanceManager instanceManager) { - this(instanceManager, new AspectRatioStrategyProxy()); - } - - /** - * Constructs an {@link AspectRatioStrategyHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - * @param proxy proxy for constructor of {@link AspectRatioStrategy} - */ - @VisibleForTesting - AspectRatioStrategyHostApiImpl( - @NonNull InstanceManager instanceManager, @NonNull AspectRatioStrategyProxy proxy) { - this.instanceManager = instanceManager; - this.proxy = proxy; - } - - /** - * Creates an {@link AspectRatioStrategy} instance with the preferred aspect ratio and fallback - * rule specified. - */ - @Override - public void create( - @NonNull Long identifier, @NonNull Long preferredAspectRatio, @NonNull Long fallbackRule) { - instanceManager.addDartCreatedInstance( - proxy.create(preferredAspectRatio, fallbackRule), identifier); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AspectRatioStrategyProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AspectRatioStrategyProxyApi.java new file mode 100644 index 000000000000..942c2682ecb8 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/AspectRatioStrategyProxyApi.java @@ -0,0 +1,88 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.camera.core.resolutionselector.AspectRatioStrategy; + +/** + * ProxyApi implementation for {@link AspectRatioStrategy}. This class may handle instantiating + * native object instances that are attached to a Dart instance or handle method calls on the + * associated native class or an instance of that class. + */ +class AspectRatioStrategyProxyApi extends PigeonApiAspectRatioStrategy { + AspectRatioStrategyProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public AspectRatioStrategy pigeon_defaultConstructor( + @NonNull AspectRatio preferredAspectRatio, + @NonNull AspectRatioStrategyFallbackRule fallbackRule) { + int nativeAspectRatio = -2; + switch (preferredAspectRatio) { + case RATIO16TO9: + nativeAspectRatio = androidx.camera.core.AspectRatio.RATIO_16_9; + break; + case RATIO4TO3: + nativeAspectRatio = androidx.camera.core.AspectRatio.RATIO_4_3; + break; + case RATIO_DEFAULT: + nativeAspectRatio = androidx.camera.core.AspectRatio.RATIO_DEFAULT; + } + int nativeFallbackRule = -1; + switch (fallbackRule) { + case AUTO: + nativeFallbackRule = AspectRatioStrategy.FALLBACK_RULE_AUTO; + break; + case NONE: + nativeFallbackRule = AspectRatioStrategy.FALLBACK_RULE_NONE; + break; + } + return new AspectRatioStrategy(nativeAspectRatio, nativeFallbackRule); + } + + @NonNull + @Override + public AspectRatioStrategy ratio_16_9FallbackAutoStrategy() { + return AspectRatioStrategy.RATIO_16_9_FALLBACK_AUTO_STRATEGY; + } + + @NonNull + @Override + public AspectRatioStrategy ratio_4_3FallbackAutoStrategy() { + return AspectRatioStrategy.RATIO_4_3_FALLBACK_AUTO_STRATEGY; + } + + @NonNull + @Override + public AspectRatioStrategyFallbackRule getFallbackRule( + @NonNull AspectRatioStrategy pigeonInstance) { + switch (pigeonInstance.getFallbackRule()) { + case AspectRatioStrategy.FALLBACK_RULE_AUTO: + return AspectRatioStrategyFallbackRule.AUTO; + case AspectRatioStrategy.FALLBACK_RULE_NONE: + return AspectRatioStrategyFallbackRule.NONE; + } + + return AspectRatioStrategyFallbackRule.UNKNOWN; + } + + @NonNull + @Override + public AspectRatio getPreferredAspectRatio(@NonNull AspectRatioStrategy pigeonInstance) { + switch (pigeonInstance.getPreferredAspectRatio()) { + case androidx.camera.core.AspectRatio.RATIO_16_9: + return AspectRatio.RATIO16TO9; + case androidx.camera.core.AspectRatio.RATIO_4_3: + return AspectRatio.RATIO4TO3; + case androidx.camera.core.AspectRatio.RATIO_DEFAULT: + return AspectRatio.RATIO_DEFAULT; + } + + return AspectRatio.UNKNOWN; + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/Camera2CameraControlHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/Camera2CameraControlHostApiImpl.java deleted file mode 100644 index 300310d6c9d4..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/Camera2CameraControlHostApiImpl.java +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import android.content.Context; -import androidx.annotation.NonNull; -import androidx.annotation.OptIn; -import androidx.annotation.VisibleForTesting; -import androidx.camera.camera2.interop.Camera2CameraControl; -import androidx.camera.camera2.interop.CaptureRequestOptions; -import androidx.camera.camera2.interop.ExperimentalCamera2Interop; -import androidx.camera.core.CameraControl; -import androidx.core.content.ContextCompat; -import com.google.common.util.concurrent.FutureCallback; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.Camera2CameraControlHostApi; -import java.util.Objects; - -/** - * Host API implementation for {@link Camera2CameraControl}. - * - *

This class may handle instantiating and adding native object instances that are attached to a - * Dart instance or handle method calls on the associated native class or an instance of the class. - */ -public class Camera2CameraControlHostApiImpl implements Camera2CameraControlHostApi { - private final InstanceManager instanceManager; - private final Camera2CameraControlProxy proxy; - - /** Proxy for constructor and methods of {@link Camera2CameraControl}. */ - @VisibleForTesting - public static class Camera2CameraControlProxy { - Context context; - - /** - * Creates an instance of {@link Camera2CameraControl} derived from specified {@link - * CameraControl} instance. - */ - @OptIn(markerClass = androidx.camera.camera2.interop.ExperimentalCamera2Interop.class) - public @NonNull Camera2CameraControl create(@NonNull CameraControl cameraControl) { - return Camera2CameraControl.from(cameraControl); - } - - /** - * Adds a {@link CaptureRequestOptions} to update the capture session with the options it - * contains. - */ - @OptIn(markerClass = androidx.camera.camera2.interop.ExperimentalCamera2Interop.class) - public void addCaptureRequestOptions( - @NonNull Camera2CameraControl camera2CameraControl, - @NonNull CaptureRequestOptions bundle, - @NonNull GeneratedCameraXLibrary.Result result) { - if (context == null) { - throw new IllegalStateException("Context must be set to add capture request options."); - } - - ListenableFuture addCaptureRequestOptionsFuture = - camera2CameraControl.addCaptureRequestOptions(bundle); - - Futures.addCallback( - addCaptureRequestOptionsFuture, - new FutureCallback() { - public void onSuccess(Void voidResult) { - result.success(null); - } - - public void onFailure(Throwable t) { - result.error(t); - } - }, - ContextCompat.getMainExecutor(context)); - } - } - - /** - * Constructs a {@link Camera2CameraControlHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - * @param context {@link Context} used to retrieve {@code Executor} - */ - public Camera2CameraControlHostApiImpl( - @NonNull InstanceManager instanceManager, @NonNull Context context) { - this(instanceManager, new Camera2CameraControlProxy(), context); - } - - /** - * Constructs a {@link Camera2CameraControlHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - * @param proxy proxy for constructor and methods of {@link Camera2CameraControl} - * @param context {@link Context} used to retrieve {@code Executor} - */ - @VisibleForTesting - Camera2CameraControlHostApiImpl( - @NonNull InstanceManager instanceManager, - @NonNull Camera2CameraControlProxy proxy, - @NonNull Context context) { - this.instanceManager = instanceManager; - this.proxy = proxy; - proxy.context = context; - } - - /** - * Sets the context that the {@code Camera2CameraControl} will use to listen for the result of - * setting capture request options. - * - *

If using the camera plugin in an add-to-app context, ensure that this is called anytime that - * the context changes. - */ - public void setContext(@NonNull Context context) { - this.proxy.context = context; - } - - @Override - public void create(@NonNull Long identifier, @NonNull Long cameraControlIdentifier) { - instanceManager.addDartCreatedInstance( - proxy.create(Objects.requireNonNull(instanceManager.getInstance(cameraControlIdentifier))), - identifier); - } - - @Override - public void addCaptureRequestOptions( - @NonNull Long identifier, - @NonNull Long captureRequestOptionsIdentifier, - @NonNull GeneratedCameraXLibrary.Result result) { - proxy.addCaptureRequestOptions( - getCamera2CameraControlInstance(identifier), - Objects.requireNonNull(instanceManager.getInstance(captureRequestOptionsIdentifier)), - result); - } - - /** - * Retrieves the {@link Camera2CameraControl} instance associated with the specified {@code - * identifier}. - */ - @OptIn(markerClass = ExperimentalCamera2Interop.class) - private Camera2CameraControl getCamera2CameraControlInstance(@NonNull Long identifier) { - return Objects.requireNonNull(instanceManager.getInstance(identifier)); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/Camera2CameraControlProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/Camera2CameraControlProxyApi.java new file mode 100644 index 000000000000..4d41de7e4e97 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/Camera2CameraControlProxyApi.java @@ -0,0 +1,65 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.annotation.OptIn; +import androidx.camera.camera2.interop.Camera2CameraControl; +import androidx.camera.camera2.interop.CaptureRequestOptions; +import androidx.camera.camera2.interop.ExperimentalCamera2Interop; +import androidx.camera.core.CameraControl; +import androidx.core.content.ContextCompat; +import com.google.common.util.concurrent.FutureCallback; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import kotlin.Result; +import kotlin.Unit; +import kotlin.jvm.functions.Function1; + +/** + * ProxyApi implementation for {@link Camera2CameraControl}. This class may handle instantiating + * native object instances that are attached to a Dart instance or handle method calls on the + * associated native class or an instance of that class. + */ +@OptIn(markerClass = ExperimentalCamera2Interop.class) +class Camera2CameraControlProxyApi extends PigeonApiCamera2CameraControl { + Camera2CameraControlProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public ProxyApiRegistrar getPigeonRegistrar() { + return (ProxyApiRegistrar) super.getPigeonRegistrar(); + } + + @NonNull + @Override + public Camera2CameraControl from(@NonNull CameraControl cameraControl) { + return Camera2CameraControl.from(cameraControl); + } + + @Override + public void addCaptureRequestOptions( + @NonNull Camera2CameraControl pigeonInstance, + @NonNull CaptureRequestOptions bundle, + @NonNull Function1, Unit> callback) { + final ListenableFuture addCaptureRequestOptionsFuture = + pigeonInstance.addCaptureRequestOptions(bundle); + + Futures.addCallback( + addCaptureRequestOptionsFuture, + new FutureCallback<>() { + public void onSuccess(Void voidResult) { + ResultCompat.success(null, callback); + } + + public void onFailure(@NonNull Throwable t) { + ResultCompat.failure(t, callback); + } + }, + ContextCompat.getMainExecutor(getPigeonRegistrar().getContext())); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/Camera2CameraInfoFlutterApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/Camera2CameraInfoFlutterApiImpl.java deleted file mode 100644 index 58769ab400fa..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/Camera2CameraInfoFlutterApiImpl.java +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.OptIn; -import androidx.camera.camera2.interop.Camera2CameraInfo; -import androidx.camera.camera2.interop.ExperimentalCamera2Interop; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.Camera2CameraInfoFlutterApi; - -public class Camera2CameraInfoFlutterApiImpl extends Camera2CameraInfoFlutterApi { - private final InstanceManager instanceManager; - - public Camera2CameraInfoFlutterApiImpl( - @Nullable BinaryMessenger binaryMessenger, @Nullable InstanceManager instanceManager) { - super(binaryMessenger); - this.instanceManager = instanceManager; - } - - @OptIn(markerClass = ExperimentalCamera2Interop.class) - void create(@NonNull Camera2CameraInfo camera2CameraInfo, @Nullable Reply reply) { - if (!instanceManager.containsInstance(camera2CameraInfo)) { - create(instanceManager.addHostCreatedInstance(camera2CameraInfo), reply); - } - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/Camera2CameraInfoHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/Camera2CameraInfoHostApiImpl.java deleted file mode 100644 index 983e9e0c674c..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/Camera2CameraInfoHostApiImpl.java +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import android.content.Context; -import android.hardware.camera2.CameraCharacteristics; -import androidx.annotation.NonNull; -import androidx.annotation.OptIn; -import androidx.annotation.VisibleForTesting; -import androidx.camera.camera2.interop.Camera2CameraInfo; -import androidx.camera.camera2.interop.ExperimentalCamera2Interop; -import androidx.camera.core.CameraInfo; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.Camera2CameraInfoHostApi; -import java.util.Objects; - -/** - * Host API implementation for {@link Camera2CameraInfo}. - * - *

This class handles instantiating and adding native object instances that are attached to a - * Dart instance or handle method calls on the associated native class or an instance of the class. - */ -public class Camera2CameraInfoHostApiImpl implements Camera2CameraInfoHostApi { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - private final Camera2CameraInfoProxy proxy; - - /** Proxy for methods of {@link Camera2CameraInfo}. */ - @VisibleForTesting - @OptIn(markerClass = ExperimentalCamera2Interop.class) - public static class Camera2CameraInfoProxy { - - @NonNull - public Camera2CameraInfo createFrom(@NonNull CameraInfo cameraInfo) { - return Camera2CameraInfo.from(cameraInfo); - } - - @NonNull - public Integer getSupportedHardwareLevel(@NonNull Camera2CameraInfo camera2CameraInfo) { - return camera2CameraInfo.getCameraCharacteristic( - CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL); - } - - @NonNull - public String getCameraId(@NonNull Camera2CameraInfo camera2CameraInfo) { - return camera2CameraInfo.getCameraId(); - } - - @NonNull - public Long getSensorOrientation(@NonNull Camera2CameraInfo camera2CameraInfo) { - return Long.valueOf( - camera2CameraInfo.getCameraCharacteristic(CameraCharacteristics.SENSOR_ORIENTATION)); - } - } - - /** - * Constructs an {@link Camera2CameraInfoHostApiImpl}. - * - * @param binaryMessenger used to communicate with Dart over asynchronous messages - * @param instanceManager maintains instances stored to communicate with attached Dart objects - * @param context {@link Context} used to retrieve {@code Executor} - */ - public Camera2CameraInfoHostApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - this(binaryMessenger, instanceManager, new Camera2CameraInfoProxy()); - } - - /** - * Constructs an {@link Camera2CameraInfoHostApiImpl}. - * - * @param binaryMessenger used to communicate with Dart over asynchronous messages - * @param instanceManager maintains instances stored to communicate with attached Dart objects - * @param proxy proxy for methods of {@link Camera2CameraInfo} - */ - @VisibleForTesting - Camera2CameraInfoHostApiImpl( - @NonNull BinaryMessenger binaryMessenger, - @NonNull InstanceManager instanceManager, - @NonNull Camera2CameraInfoProxy proxy) { - this.instanceManager = instanceManager; - this.binaryMessenger = binaryMessenger; - this.proxy = proxy; - } - - @OptIn(markerClass = ExperimentalCamera2Interop.class) - @Override - @NonNull - public Long createFrom(@NonNull Long cameraInfoIdentifier) { - final CameraInfo cameraInfo = - Objects.requireNonNull(instanceManager.getInstance(cameraInfoIdentifier)); - final Camera2CameraInfo camera2CameraInfo = proxy.createFrom(cameraInfo); - final Camera2CameraInfoFlutterApiImpl flutterApi = - new Camera2CameraInfoFlutterApiImpl(binaryMessenger, instanceManager); - - flutterApi.create(camera2CameraInfo, reply -> {}); - return instanceManager.getIdentifierForStrongReference(camera2CameraInfo); - } - - @Override - @NonNull - public Long getSupportedHardwareLevel(@NonNull Long identifier) { - return Long.valueOf(proxy.getSupportedHardwareLevel(getCamera2CameraInfoInstance(identifier))); - } - - @Override - @NonNull - public String getCameraId(@NonNull Long identifier) { - return proxy.getCameraId(getCamera2CameraInfoInstance(identifier)); - } - - @Override - @NonNull - public Long getSensorOrientation(@NonNull Long identifier) { - return proxy.getSensorOrientation(getCamera2CameraInfoInstance(identifier)); - } - - @OptIn(markerClass = ExperimentalCamera2Interop.class) - private Camera2CameraInfo getCamera2CameraInfoInstance(@NonNull Long identifier) { - return Objects.requireNonNull(instanceManager.getInstance(identifier)); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/Camera2CameraInfoProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/Camera2CameraInfoProxyApi.java new file mode 100644 index 000000000000..f9ee09c07b85 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/Camera2CameraInfoProxyApi.java @@ -0,0 +1,65 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import android.hardware.camera2.CameraCharacteristics; +import android.hardware.camera2.CameraMetadata; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.OptIn; +import androidx.camera.camera2.interop.Camera2CameraInfo; +import androidx.camera.camera2.interop.ExperimentalCamera2Interop; +import androidx.camera.core.CameraInfo; + +/** + * ProxyApi implementation for {@link Camera2CameraInfo}. This class may handle instantiating native + * object instances that are attached to a Dart instance or handle method calls on the associated + * native class or an instance of that class. + */ +@OptIn(markerClass = ExperimentalCamera2Interop.class) +class Camera2CameraInfoProxyApi extends PigeonApiCamera2CameraInfo { + Camera2CameraInfoProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public Camera2CameraInfo from(@NonNull CameraInfo cameraInfo) { + return Camera2CameraInfo.from(cameraInfo); + } + + @NonNull + @Override + public String getCameraId(Camera2CameraInfo pigeonInstance) { + return pigeonInstance.getCameraId(); + } + + @Nullable + @Override + public Object getCameraCharacteristic( + Camera2CameraInfo pigeonInstance, @NonNull CameraCharacteristics.Key key) { + final Object result = pigeonInstance.getCameraCharacteristic(key); + if (result == null) { + return null; + } + + if (key == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL) { + switch ((Integer) result) { + case CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_3: + return InfoSupportedHardwareLevel.LEVEL3; + case CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_EXTERNAL: + return InfoSupportedHardwareLevel.EXTERNAL; + case CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_FULL: + return InfoSupportedHardwareLevel.FULL; + case CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY: + return InfoSupportedHardwareLevel.LEGACY; + case CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED: + return InfoSupportedHardwareLevel.LIMITED; + } + } + + return result; + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraAndroidCameraxPlugin.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraAndroidCameraxPlugin.java index 42e5df0f32c1..b1f5c4f1893e 100644 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraAndroidCameraxPlugin.java +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraAndroidCameraxPlugin.java @@ -4,41 +4,17 @@ package io.flutter.plugins.camerax; -import android.app.Activity; -import android.content.Context; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; -import androidx.lifecycle.LifecycleOwner; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.embedding.engine.plugins.activity.ActivityAware; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.view.TextureRegistry; /** Platform implementation of the camera_plugin implemented with the CameraX library. */ public final class CameraAndroidCameraxPlugin implements FlutterPlugin, ActivityAware { - private InstanceManager instanceManager; private FlutterPluginBinding pluginBinding; - @VisibleForTesting @Nullable public PendingRecordingHostApiImpl pendingRecordingHostApiImpl; - @VisibleForTesting @Nullable public RecorderHostApiImpl recorderHostApiImpl; - @VisibleForTesting @Nullable public VideoCaptureHostApiImpl videoCaptureHostApiImpl; - @VisibleForTesting @Nullable public ImageAnalysisHostApiImpl imageAnalysisHostApiImpl; - @VisibleForTesting @Nullable public ImageCaptureHostApiImpl imageCaptureHostApiImpl; - @VisibleForTesting @Nullable public CameraControlHostApiImpl cameraControlHostApiImpl; - @VisibleForTesting @Nullable public SystemServicesHostApiImpl systemServicesHostApiImpl; - @VisibleForTesting @Nullable public MeteringPointHostApiImpl meteringPointHostApiImpl; - - @VisibleForTesting @Nullable - public Camera2CameraControlHostApiImpl camera2CameraControlHostApiImpl; - - @VisibleForTesting - public @Nullable DeviceOrientationManagerHostApiImpl deviceOrientationManagerHostApiImpl; - - @VisibleForTesting - public @Nullable ProcessCameraProviderHostApiImpl processCameraProviderHostApiImpl; - - @VisibleForTesting public @Nullable LiveDataHostApiImpl liveDataHostApiImpl; + @VisibleForTesting @Nullable ProxyApiRegistrar proxyApiRegistrar; /** * Initialize this within the {@code #configureFlutterEngine} of a Flutter activity or fragment. @@ -47,108 +23,25 @@ public final class CameraAndroidCameraxPlugin implements FlutterPlugin, Activity */ public CameraAndroidCameraxPlugin() {} - @VisibleForTesting - public void setUp( - @NonNull BinaryMessenger binaryMessenger, - @NonNull Context context, - @NonNull TextureRegistry textureRegistry) { - // Set up instance manager. - instanceManager = - InstanceManager.create( - identifier -> { - new GeneratedCameraXLibrary.JavaObjectFlutterApi(binaryMessenger) - .dispose(identifier, reply -> {}); - }); - - // Set up Host APIs. - GeneratedCameraXLibrary.InstanceManagerHostApi.setup( - binaryMessenger, () -> instanceManager.clear()); - GeneratedCameraXLibrary.CameraHostApi.setup( - binaryMessenger, new CameraHostApiImpl(binaryMessenger, instanceManager)); - GeneratedCameraXLibrary.CameraInfoHostApi.setup( - binaryMessenger, new CameraInfoHostApiImpl(binaryMessenger, instanceManager)); - GeneratedCameraXLibrary.CameraSelectorHostApi.setup( - binaryMessenger, new CameraSelectorHostApiImpl(binaryMessenger, instanceManager)); - GeneratedCameraXLibrary.JavaObjectHostApi.setup( - binaryMessenger, new JavaObjectHostApiImpl(instanceManager)); - processCameraProviderHostApiImpl = - new ProcessCameraProviderHostApiImpl(binaryMessenger, instanceManager, context); - GeneratedCameraXLibrary.ProcessCameraProviderHostApi.setup( - binaryMessenger, processCameraProviderHostApiImpl); - systemServicesHostApiImpl = - new SystemServicesHostApiImpl(binaryMessenger, instanceManager, context); - GeneratedCameraXLibrary.SystemServicesHostApi.setup(binaryMessenger, systemServicesHostApiImpl); - deviceOrientationManagerHostApiImpl = - new DeviceOrientationManagerHostApiImpl(binaryMessenger, instanceManager); - GeneratedCameraXLibrary.DeviceOrientationManagerHostApi.setup( - binaryMessenger, deviceOrientationManagerHostApiImpl); - GeneratedCameraXLibrary.PreviewHostApi.setup( - binaryMessenger, new PreviewHostApiImpl(binaryMessenger, instanceManager, textureRegistry)); - imageCaptureHostApiImpl = - new ImageCaptureHostApiImpl(binaryMessenger, instanceManager, context); - GeneratedCameraXLibrary.ImageCaptureHostApi.setup(binaryMessenger, imageCaptureHostApiImpl); - GeneratedCameraXLibrary.CameraHostApi.setup( - binaryMessenger, new CameraHostApiImpl(binaryMessenger, instanceManager)); - liveDataHostApiImpl = new LiveDataHostApiImpl(binaryMessenger, instanceManager); - GeneratedCameraXLibrary.LiveDataHostApi.setup(binaryMessenger, liveDataHostApiImpl); - GeneratedCameraXLibrary.ObserverHostApi.setup( - binaryMessenger, new ObserverHostApiImpl(binaryMessenger, instanceManager)); - imageAnalysisHostApiImpl = - new ImageAnalysisHostApiImpl(binaryMessenger, instanceManager, context); - GeneratedCameraXLibrary.ImageAnalysisHostApi.setup(binaryMessenger, imageAnalysisHostApiImpl); - GeneratedCameraXLibrary.AnalyzerHostApi.setup( - binaryMessenger, new AnalyzerHostApiImpl(binaryMessenger, instanceManager)); - GeneratedCameraXLibrary.ImageProxyHostApi.setup( - binaryMessenger, new ImageProxyHostApiImpl(binaryMessenger, instanceManager)); - GeneratedCameraXLibrary.RecordingHostApi.setup( - binaryMessenger, new RecordingHostApiImpl(binaryMessenger, instanceManager)); - recorderHostApiImpl = new RecorderHostApiImpl(binaryMessenger, instanceManager, context); - GeneratedCameraXLibrary.RecorderHostApi.setup(binaryMessenger, recorderHostApiImpl); - pendingRecordingHostApiImpl = - new PendingRecordingHostApiImpl(binaryMessenger, instanceManager, context); - GeneratedCameraXLibrary.PendingRecordingHostApi.setup( - binaryMessenger, pendingRecordingHostApiImpl); - videoCaptureHostApiImpl = new VideoCaptureHostApiImpl(binaryMessenger, instanceManager); - GeneratedCameraXLibrary.VideoCaptureHostApi.setup(binaryMessenger, videoCaptureHostApiImpl); - GeneratedCameraXLibrary.ResolutionSelectorHostApi.setup( - binaryMessenger, new ResolutionSelectorHostApiImpl(instanceManager)); - GeneratedCameraXLibrary.ResolutionStrategyHostApi.setup( - binaryMessenger, new ResolutionStrategyHostApiImpl(instanceManager)); - GeneratedCameraXLibrary.AspectRatioStrategyHostApi.setup( - binaryMessenger, new AspectRatioStrategyHostApiImpl(instanceManager)); - GeneratedCameraXLibrary.FallbackStrategyHostApi.setup( - binaryMessenger, new FallbackStrategyHostApiImpl(instanceManager)); - GeneratedCameraXLibrary.QualitySelectorHostApi.setup( - binaryMessenger, new QualitySelectorHostApiImpl(instanceManager)); - cameraControlHostApiImpl = - new CameraControlHostApiImpl(binaryMessenger, instanceManager, context); - GeneratedCameraXLibrary.CameraControlHostApi.setup(binaryMessenger, cameraControlHostApiImpl); - camera2CameraControlHostApiImpl = new Camera2CameraControlHostApiImpl(instanceManager, context); - GeneratedCameraXLibrary.Camera2CameraControlHostApi.setup( - binaryMessenger, camera2CameraControlHostApiImpl); - GeneratedCameraXLibrary.CaptureRequestOptionsHostApi.setup( - binaryMessenger, new CaptureRequestOptionsHostApiImpl(instanceManager)); - GeneratedCameraXLibrary.FocusMeteringActionHostApi.setup( - binaryMessenger, new FocusMeteringActionHostApiImpl(instanceManager)); - GeneratedCameraXLibrary.FocusMeteringResultHostApi.setup( - binaryMessenger, new FocusMeteringResultHostApiImpl(instanceManager)); - meteringPointHostApiImpl = new MeteringPointHostApiImpl(instanceManager); - GeneratedCameraXLibrary.MeteringPointHostApi.setup(binaryMessenger, meteringPointHostApiImpl); - GeneratedCameraXLibrary.ResolutionFilterHostApi.setup( - binaryMessenger, new ResolutionFilterHostApiImpl(instanceManager)); - GeneratedCameraXLibrary.Camera2CameraInfoHostApi.setup( - binaryMessenger, new Camera2CameraInfoHostApiImpl(binaryMessenger, instanceManager)); - } - @Override - public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) { - pluginBinding = flutterPluginBinding; + public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) { + pluginBinding = binding; + + proxyApiRegistrar = + new ProxyApiRegistrar( + binding.getBinaryMessenger(), + binding.getApplicationContext(), + binding.getTextureRegistry()); + proxyApiRegistrar.setUp(); } @Override public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { - if (instanceManager != null) { - instanceManager.stopFinalizationListener(); + if (proxyApiRegistrar != null) { + proxyApiRegistrar.setIgnoreCallsToDart(true); + proxyApiRegistrar.tearDown(); + proxyApiRegistrar.getInstanceManager().stopFinalizationListener(); + proxyApiRegistrar = null; } } @@ -156,112 +49,37 @@ public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { @Override public void onAttachedToActivity(@NonNull ActivityPluginBinding activityPluginBinding) { - Activity activity = activityPluginBinding.getActivity(); - - // Set up Host API implementations based on the context that `activity` provides. - setUp(pluginBinding.getBinaryMessenger(), activity, pluginBinding.getTextureRegistry()); - - // Set any needed references to `activity` itself. - updateLifecycleOwner(activity); - updateActivity(activity); - - // Set permissions registry reference. - systemServicesHostApiImpl.setPermissionsRegistry( - activityPluginBinding::addRequestPermissionsResultListener); + if (proxyApiRegistrar != null) { + proxyApiRegistrar.setContext(activityPluginBinding.getActivity()); + proxyApiRegistrar.setPermissionsRegistry( + activityPluginBinding::addRequestPermissionsResultListener); + } } @Override public void onDetachedFromActivityForConfigChanges() { - // Clear any references to previously attached `ActivityPluginBinding`/`Activity`. - updateContext(pluginBinding.getApplicationContext()); - updateLifecycleOwner(null); - updateActivity(null); - systemServicesHostApiImpl.setPermissionsRegistry(null); + if (proxyApiRegistrar != null) { + proxyApiRegistrar.setContext(pluginBinding.getApplicationContext()); + proxyApiRegistrar.setPermissionsRegistry(null); + } } @Override public void onReattachedToActivityForConfigChanges( @NonNull ActivityPluginBinding activityPluginBinding) { - Activity activity = activityPluginBinding.getActivity(); - - // Set any needed references to `activity` itself or its context. - updateContext(activity); - updateLifecycleOwner(activity); - updateActivity(activity); - - // Set permissions registry reference. - systemServicesHostApiImpl.setPermissionsRegistry( - activityPluginBinding::addRequestPermissionsResultListener); + if (proxyApiRegistrar != null) { + proxyApiRegistrar.setContext(activityPluginBinding.getActivity()); + proxyApiRegistrar.setPermissionsRegistry( + activityPluginBinding::addRequestPermissionsResultListener); + } } @Override public void onDetachedFromActivity() { // Clear any references to previously attached `ActivityPluginBinding`/`Activity`. - updateContext(pluginBinding.getApplicationContext()); - updateLifecycleOwner(null); - updateActivity(null); - systemServicesHostApiImpl.setPermissionsRegistry(null); - } - - /** - * Updates context that is used to fetch the corresponding instance of a {@code - * ProcessCameraProvider} to each of the relevant camera controls. - */ - public void updateContext(@NonNull Context context) { - if (processCameraProviderHostApiImpl != null) { - processCameraProviderHostApiImpl.setContext(context); - } - if (recorderHostApiImpl != null) { - recorderHostApiImpl.setContext(context); - } - if (pendingRecordingHostApiImpl != null) { - pendingRecordingHostApiImpl.setContext(context); - } - if (systemServicesHostApiImpl != null) { - systemServicesHostApiImpl.setContext(context); - } - if (imageCaptureHostApiImpl != null) { - imageCaptureHostApiImpl.setContext(context); - } - if (imageAnalysisHostApiImpl != null) { - imageAnalysisHostApiImpl.setContext(context); - } - if (cameraControlHostApiImpl != null) { - cameraControlHostApiImpl.setContext(context); - } - if (camera2CameraControlHostApiImpl != null) { - camera2CameraControlHostApiImpl.setContext(context); - } - } - - /** Sets {@code LifecycleOwner} that is used to control the lifecycle of the camera by CameraX. */ - public void updateLifecycleOwner(@Nullable Activity activity) { - if (activity == null) { - processCameraProviderHostApiImpl.setLifecycleOwner(null); - liveDataHostApiImpl.setLifecycleOwner(null); - } else if (activity instanceof LifecycleOwner) { - processCameraProviderHostApiImpl.setLifecycleOwner((LifecycleOwner) activity); - liveDataHostApiImpl.setLifecycleOwner((LifecycleOwner) activity); - } else { - ProxyLifecycleProvider proxyLifecycleProvider = new ProxyLifecycleProvider(activity); - processCameraProviderHostApiImpl.setLifecycleOwner(proxyLifecycleProvider); - liveDataHostApiImpl.setLifecycleOwner(proxyLifecycleProvider); - } - } - - /** - * Updates {@code Activity} that is used for requesting camera permissions and tracking the - * orientation of the device. - */ - public void updateActivity(@Nullable Activity activity) { - if (systemServicesHostApiImpl != null) { - systemServicesHostApiImpl.setActivity(activity); - } - if (deviceOrientationManagerHostApiImpl != null) { - deviceOrientationManagerHostApiImpl.setActivity(activity); - } - if (meteringPointHostApiImpl != null) { - meteringPointHostApiImpl.setActivity(activity); + if (proxyApiRegistrar != null) { + proxyApiRegistrar.setContext(pluginBinding.getApplicationContext()); + proxyApiRegistrar.setPermissionsRegistry(null); } } } diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraCharacteristicsProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraCharacteristicsProxyApi.java new file mode 100644 index 000000000000..5cab2f35e691 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraCharacteristicsProxyApi.java @@ -0,0 +1,31 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import android.hardware.camera2.CameraCharacteristics; +import androidx.annotation.NonNull; + +/** + * ProxyApi implementation for {@link CameraCharacteristics}. This class may handle instantiating + * native object instances that are attached to a Dart instance or handle method calls on the + * associated native class or an instance of that class. + */ +class CameraCharacteristicsProxyApi extends PigeonApiCameraCharacteristics { + CameraCharacteristicsProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public CameraCharacteristics.Key infoSupportedHardwareLevel() { + return CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL; + } + + @NonNull + @Override + public android.hardware.camera2.CameraCharacteristics.Key sensorOrientation() { + return CameraCharacteristics.SENSOR_ORIENTATION; + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraControlFlutterApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraControlFlutterApiImpl.java deleted file mode 100644 index 1b616180ec73..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraControlFlutterApiImpl.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.camera.core.CameraControl; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraControlFlutterApi; - -public class CameraControlFlutterApiImpl extends CameraControlFlutterApi { - private final @NonNull InstanceManager instanceManager; - - public CameraControlFlutterApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - super(binaryMessenger); - this.instanceManager = instanceManager; - } - - /** - * Creates a {@link CameraControl} instance in Dart. {@code reply} is not used so it can be empty. - */ - void create(CameraControl cameraControl, Reply reply) { - if (!instanceManager.containsInstance(cameraControl)) { - create(instanceManager.addHostCreatedInstance(cameraControl), reply); - } - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraControlHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraControlHostApiImpl.java deleted file mode 100644 index ba4318a8927f..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraControlHostApiImpl.java +++ /dev/null @@ -1,284 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import android.content.Context; -import androidx.annotation.NonNull; -import androidx.annotation.VisibleForTesting; -import androidx.camera.core.CameraControl; -import androidx.camera.core.FocusMeteringAction; -import androidx.camera.core.FocusMeteringResult; -import androidx.core.content.ContextCompat; -import com.google.common.util.concurrent.FutureCallback; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.ListenableFuture; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraControlHostApi; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.Result; -import java.util.Objects; - -/** - * Host API implementation for {@link CameraControl}. - * - *

This class handles instantiating and adding native object instances that are attached to a - * Dart instance or handle method calls on the associated native class or an instance of the class. - */ -public class CameraControlHostApiImpl implements CameraControlHostApi { - private final InstanceManager instanceManager; - private final CameraControlProxy proxy; - - /** Proxy for methods of {@link CameraControl}. */ - @VisibleForTesting - public static class CameraControlProxy { - Context context; - BinaryMessenger binaryMessenger; - InstanceManager instanceManager; - - /** Enables or disables the torch of the specified {@link CameraControl} instance. */ - @NonNull - public void enableTorch( - @NonNull CameraControl cameraControl, - @NonNull Boolean torch, - @NonNull GeneratedCameraXLibrary.Result result) { - if (context == null) { - throw new IllegalStateException("Context must be set to enable the torch."); - } - - ListenableFuture enableTorchFuture = cameraControl.enableTorch(torch); - - Futures.addCallback( - enableTorchFuture, - new FutureCallback() { - public void onSuccess(Void voidResult) { - result.success(null); - } - - public void onFailure(Throwable t) { - result.error(t); - } - }, - ContextCompat.getMainExecutor(context)); - } - - /** Sets the zoom ratio of the specified {@link CameraControl} instance. */ - @NonNull - public void setZoomRatio( - @NonNull CameraControl cameraControl, - @NonNull Double ratio, - @NonNull GeneratedCameraXLibrary.Result result) { - if (context == null) { - throw new IllegalStateException("Context must be set to set zoom ratio."); - } - - float ratioAsFloat = ratio.floatValue(); - ListenableFuture setZoomRatioFuture = cameraControl.setZoomRatio(ratioAsFloat); - - Futures.addCallback( - setZoomRatioFuture, - new FutureCallback() { - public void onSuccess(Void voidResult) { - result.success(null); - } - - public void onFailure(Throwable t) { - if (t instanceof CameraControl.OperationCanceledException) { - // Operation was canceled due to camera being closed or a new request was submitted, which - // is not actionable and should not block a new value from potentially being submitted. - result.success(null); - return; - } - result.error(t); - } - }, - ContextCompat.getMainExecutor(context)); - } - - /** - * Starts a focus and metering action configured by the {@code FocusMeteringAction}. - * - *

Will trigger an auto focus action and enable auto focus/auto exposure/auto white balance - * metering regions. - * - *

Will send a {@link GeneratedCameraXLibrary.Result} with a null result if operation was - * canceled. - */ - public void startFocusAndMetering( - @NonNull CameraControl cameraControl, - @NonNull FocusMeteringAction focusMeteringAction, - @NonNull GeneratedCameraXLibrary.Result result) { - if (context == null) { - throw new IllegalStateException("Context must be set to set zoom ratio."); - } - - ListenableFuture focusMeteringResultFuture = - cameraControl.startFocusAndMetering(focusMeteringAction); - - Futures.addCallback( - focusMeteringResultFuture, - new FutureCallback() { - public void onSuccess(FocusMeteringResult focusMeteringResult) { - final FocusMeteringResultFlutterApiImpl flutterApi = - new FocusMeteringResultFlutterApiImpl(binaryMessenger, instanceManager); - flutterApi.create(focusMeteringResult, reply -> {}); - result.success(instanceManager.getIdentifierForStrongReference(focusMeteringResult)); - } - - public void onFailure(Throwable t) { - if (t instanceof CameraControl.OperationCanceledException) { - // Operation was canceled due to camera being closed or a new request was submitted, which - // is not actionable and should not block a new value from potentially being submitted. - result.success(null); - return; - } - result.error(t); - } - }, - ContextCompat.getMainExecutor(context)); - } - - /** - * Cancels current {@code FocusMeteringAction} and clears auto focus/auto exposure/auto white - * balance regions. - */ - public void cancelFocusAndMetering( - @NonNull CameraControl cameraControl, @NonNull Result result) { - ListenableFuture cancelFocusAndMeteringFuture = cameraControl.cancelFocusAndMetering(); - - Futures.addCallback( - cancelFocusAndMeteringFuture, - new FutureCallback() { - public void onSuccess(Void voidResult) { - result.success(null); - } - - public void onFailure(Throwable t) { - result.error(t); - } - }, - ContextCompat.getMainExecutor(context)); - } - - /** - * Sets the exposure compensation index for the specified {@link CameraControl} instance and - * returns the new target exposure value. - * - *

The exposure compensation value set on the camera must be within the range of {@code - * ExposureState#getExposureCompensationRange()} for the current {@code ExposureState} for the - * call to succeed. - * - *

Will send a {@link GeneratedCameraXLibrary.Result} with a null result if operation was - * canceled. - */ - public void setExposureCompensationIndex( - @NonNull CameraControl cameraControl, @NonNull Long index, @NonNull Result result) { - ListenableFuture setExposureCompensationIndexFuture = - cameraControl.setExposureCompensationIndex(index.intValue()); - - Futures.addCallback( - setExposureCompensationIndexFuture, - new FutureCallback() { - public void onSuccess(Integer integerResult) { - result.success(integerResult.longValue()); - } - - public void onFailure(Throwable t) { - if (t instanceof CameraControl.OperationCanceledException) { - // Operation was canceled due to camera being closed or a new request was submitted, which - // is not actionable and should not block a new value from potentially being submitted. - result.success(null); - return; - } - result.error(t); - } - }, - ContextCompat.getMainExecutor(context)); - } - } - - /** - * Constructs an {@link CameraControlHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - * @param context {@link Context} used to retrieve {@code Executor} - */ - public CameraControlHostApiImpl( - @NonNull BinaryMessenger binaryMessenger, - @NonNull InstanceManager instanceManager, - @NonNull Context context) { - this(binaryMessenger, instanceManager, new CameraControlProxy(), context); - } - - /** - * Constructs an {@link CameraControlHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - * @param proxy proxy for methods of {@link CameraControl} - * @param context {@link Context} used to retrieve {@code Executor} - */ - @VisibleForTesting - CameraControlHostApiImpl( - @NonNull BinaryMessenger binaryMessenger, - @NonNull InstanceManager instanceManager, - @NonNull CameraControlProxy proxy, - @NonNull Context context) { - this.instanceManager = instanceManager; - this.proxy = proxy; - proxy.context = context; - // proxy.startFocusAndMetering needs to access these to create a FocusMeteringResult when it becomes available: - proxy.instanceManager = instanceManager; - proxy.binaryMessenger = binaryMessenger; - } - - /** - * Sets the context that the {@code CameraControl} will use to enable/disable torch mode and set - * the zoom ratio. - * - *

If using the camera plugin in an add-to-app context, ensure that this is called anytime that - * the context changes. - */ - public void setContext(@NonNull Context context) { - this.proxy.context = context; - } - - @Override - public void enableTorch( - @NonNull Long identifier, - @NonNull Boolean torch, - @NonNull GeneratedCameraXLibrary.Result result) { - proxy.enableTorch(getCameraControlInstance(identifier), torch, result); - } - - @Override - public void setZoomRatio( - @NonNull Long identifier, - @NonNull Double ratio, - @NonNull GeneratedCameraXLibrary.Result result) { - proxy.setZoomRatio(getCameraControlInstance(identifier), ratio, result); - } - - @Override - public void startFocusAndMetering( - @NonNull Long identifier, @NonNull Long focusMeteringActionId, @NonNull Result result) { - proxy.startFocusAndMetering( - getCameraControlInstance(identifier), - Objects.requireNonNull(instanceManager.getInstance(focusMeteringActionId)), - result); - } - - @Override - public void cancelFocusAndMetering(@NonNull Long identifier, @NonNull Result result) { - proxy.cancelFocusAndMetering(getCameraControlInstance(identifier), result); - } - - @Override - public void setExposureCompensationIndex( - @NonNull Long identifier, @NonNull Long index, @NonNull Result result) { - proxy.setExposureCompensationIndex(getCameraControlInstance(identifier), index, result); - } - - private CameraControl getCameraControlInstance(@NonNull Long identifier) { - return Objects.requireNonNull(instanceManager.getInstance(identifier)); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraControlProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraControlProxyApi.java new file mode 100644 index 000000000000..cee3178df808 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraControlProxyApi.java @@ -0,0 +1,161 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.camera.core.CameraControl; +import androidx.camera.core.FocusMeteringAction; +import androidx.camera.core.FocusMeteringResult; +import androidx.core.content.ContextCompat; +import com.google.common.util.concurrent.FutureCallback; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import kotlin.Result; +import kotlin.Unit; +import kotlin.jvm.functions.Function1; + +/** + * ProxyApi implementation for {@link CameraControl}. This class may handle instantiating native + * object instances that are attached to a Dart instance or handle method calls on the associated + * native class or an instance of that class. + */ +class CameraControlProxyApi extends PigeonApiCameraControl { + CameraControlProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public ProxyApiRegistrar getPigeonRegistrar() { + return (ProxyApiRegistrar) super.getPigeonRegistrar(); + } + + @Override + public void enableTorch( + @NonNull CameraControl pigeonInstance, + boolean torch, + @NonNull Function1, Unit> callback) { + final ListenableFuture enableTorchFuture = pigeonInstance.enableTorch(torch); + + Futures.addCallback( + enableTorchFuture, + new FutureCallback<>() { + public void onSuccess(Void voidResult) { + ResultCompat.success(null, callback); + } + + public void onFailure(@NonNull Throwable t) { + ResultCompat.failure(t, callback); + } + }, + ContextCompat.getMainExecutor(getPigeonRegistrar().getContext())); + } + + @Override + public void setZoomRatio( + @NonNull CameraControl pigeonInstance, + double ratio, + @NonNull Function1, Unit> callback) { + float ratioAsFloat = (float) ratio; + final ListenableFuture setZoomRatioFuture = pigeonInstance.setZoomRatio(ratioAsFloat); + + Futures.addCallback( + setZoomRatioFuture, + new FutureCallback<>() { + public void onSuccess(Void voidResult) { + ResultCompat.success(null, callback); + } + + public void onFailure(@NonNull Throwable t) { + if (t instanceof CameraControl.OperationCanceledException) { + // Operation was canceled due to camera being closed or a new request was submitted, which + // is not actionable and should not block a new value from potentially being submitted. + ResultCompat.success(null, callback); + return; + } + + ResultCompat.failure(t, callback); + } + }, + ContextCompat.getMainExecutor(getPigeonRegistrar().getContext())); + } + + @Override + public void startFocusAndMetering( + @NonNull CameraControl pigeonInstance, + @NonNull FocusMeteringAction action, + @NonNull Function1, Unit> callback) { + ListenableFuture focusMeteringResultFuture = + pigeonInstance.startFocusAndMetering(action); + + Futures.addCallback( + focusMeteringResultFuture, + new FutureCallback<>() { + public void onSuccess(FocusMeteringResult focusMeteringResult) { + ResultCompat.success(focusMeteringResult, callback); + } + + public void onFailure(@NonNull Throwable t) { + if (t instanceof CameraControl.OperationCanceledException) { + // Operation was canceled due to camera being closed or a new request was submitted, which + // is not actionable and should not block a new value from potentially being submitted. + ResultCompat.success(null, callback); + return; + } + ResultCompat.failure(t, callback); + } + }, + ContextCompat.getMainExecutor(getPigeonRegistrar().getContext())); + } + + @Override + public void cancelFocusAndMetering( + @NonNull CameraControl pigeonInstance, + @NonNull Function1, Unit> callback) { + final ListenableFuture cancelFocusAndMeteringFuture = + pigeonInstance.cancelFocusAndMetering(); + + Futures.addCallback( + cancelFocusAndMeteringFuture, + new FutureCallback<>() { + public void onSuccess(Void voidResult) { + ResultCompat.success(null, callback); + } + + public void onFailure(@NonNull Throwable t) { + ResultCompat.failure(t, callback); + } + }, + ContextCompat.getMainExecutor(getPigeonRegistrar().getContext())); + } + + @Override + public void setExposureCompensationIndex( + @NonNull CameraControl pigeonInstance, + long index, + @NonNull Function1, Unit> callback) { + final ListenableFuture setExposureCompensationIndexFuture = + pigeonInstance.setExposureCompensationIndex((int) index); + + Futures.addCallback( + setExposureCompensationIndexFuture, + new FutureCallback<>() { + public void onSuccess(Integer integerResult) { + ResultCompat.success(integerResult.longValue(), callback); + } + + public void onFailure(@NonNull Throwable t) { + if (t instanceof CameraControl.OperationCanceledException) { + // Operation was canceled due to camera being closed or a new request was submitted, which + // is not actionable and should not block a new value from potentially being submitted. + ResultCompat.success(null, callback); + return; + } + ResultCompat.failure(t, callback); + } + }, + ContextCompat.getMainExecutor(getPigeonRegistrar().getContext())); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraFlutterApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraFlutterApiImpl.java deleted file mode 100644 index cfc40be1819a..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraFlutterApiImpl.java +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.camera.core.Camera; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraFlutterApi; - -public class CameraFlutterApiImpl extends CameraFlutterApi { - private final @NonNull InstanceManager instanceManager; - - public CameraFlutterApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - super(binaryMessenger); - this.instanceManager = instanceManager; - } - - void create(Camera camera, Reply reply) { - create(instanceManager.addHostCreatedInstance(camera), reply); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraHostApiImpl.java deleted file mode 100644 index 603cc62edf83..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraHostApiImpl.java +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.camera.core.Camera; -import androidx.camera.core.CameraControl; -import androidx.camera.core.CameraInfo; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraHostApi; -import java.util.Objects; - -public class CameraHostApiImpl implements CameraHostApi { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - - public CameraHostApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - } - - /** - * Retrieves the {@link CameraInfo} instance that contains information about the {@link Camera} - * instance with the specified identifier. - */ - @Override - @NonNull - public Long getCameraInfo(@NonNull Long identifier) { - Camera camera = getCameraInstance(identifier); - CameraInfo cameraInfo = camera.getCameraInfo(); - - CameraInfoFlutterApiImpl cameraInfoFlutterApiImpl = - new CameraInfoFlutterApiImpl(binaryMessenger, instanceManager); - cameraInfoFlutterApiImpl.create(cameraInfo, reply -> {}); - return instanceManager.getIdentifierForStrongReference(cameraInfo); - } - - /** - * Retrieves the {@link CameraControl} instance that provides access to asynchronous operations - * like zoom and focus & metering on the {@link Camera} instance with the specified identifier. - */ - @Override - @NonNull - public Long getCameraControl(@NonNull Long identifier) { - Camera camera = getCameraInstance(identifier); - CameraControl cameraControl = camera.getCameraControl(); - - CameraControlFlutterApiImpl cameraControlFlutterApiImpl = - new CameraControlFlutterApiImpl(binaryMessenger, instanceManager); - cameraControlFlutterApiImpl.create(cameraControl, reply -> {}); - return instanceManager.getIdentifierForStrongReference(cameraControl); - } - - /** Retrieives the {@link Camera} instance associated with the specified {@code identifier}. */ - private Camera getCameraInstance(@NonNull Long identifier) { - return (Camera) Objects.requireNonNull(instanceManager.getInstance(identifier)); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraInfoFlutterApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraInfoFlutterApiImpl.java deleted file mode 100644 index 8b0e1ff6b3e2..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraInfoFlutterApiImpl.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.camera.core.CameraInfo; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraInfoFlutterApi; - -public class CameraInfoFlutterApiImpl extends CameraInfoFlutterApi { - private final @NonNull InstanceManager instanceManager; - - public CameraInfoFlutterApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - super(binaryMessenger); - this.instanceManager = instanceManager; - } - - /** - * Creates a {@link CameraInfo} instance in Dart. {@code reply} is not used so it can be empty. - */ - void create(CameraInfo cameraInfo, Reply reply) { - if (!instanceManager.containsInstance(cameraInfo)) { - create(instanceManager.addHostCreatedInstance(cameraInfo), reply); - } - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraInfoHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraInfoHostApiImpl.java deleted file mode 100644 index 83eb359cdb5e..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraInfoHostApiImpl.java +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.annotation.VisibleForTesting; -import androidx.camera.core.CameraInfo; -import androidx.camera.core.CameraState; -import androidx.camera.core.ExposureState; -import androidx.camera.core.ZoomState; -import androidx.lifecycle.LiveData; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraInfoHostApi; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.LiveDataSupportedType; -import java.util.Objects; - -public class CameraInfoHostApiImpl implements CameraInfoHostApi { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - - @VisibleForTesting public @NonNull LiveDataFlutterApiWrapper liveDataFlutterApiWrapper; - - public CameraInfoHostApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - this.liveDataFlutterApiWrapper = - new LiveDataFlutterApiWrapper(binaryMessenger, instanceManager); - } - - /** - * Retrieves the sensor rotation degrees of the {@link androidx.camera.core.Camera} that is - * represented by the {@link CameraInfo} with the specified identifier. - */ - @Override - @NonNull - public Long getSensorRotationDegrees(@NonNull Long identifier) { - CameraInfo cameraInfo = - (CameraInfo) Objects.requireNonNull(instanceManager.getInstance(identifier)); - return Long.valueOf(cameraInfo.getSensorRotationDegrees()); - } - - /** - * Retrieves the {@link LiveData} of the {@link CameraState} that is tied to the {@link - * androidx.camera.core.Camera} that is represented by the {@link CameraInfo} with the specified - * identifier. - */ - @Override - @NonNull - public Long getCameraState(@NonNull Long identifier) { - CameraInfo cameraInfo = - (CameraInfo) Objects.requireNonNull(instanceManager.getInstance(identifier)); - LiveData liveCameraState = cameraInfo.getCameraState(); - liveDataFlutterApiWrapper.create( - liveCameraState, LiveDataSupportedType.CAMERA_STATE, reply -> {}); - return instanceManager.getIdentifierForStrongReference(liveCameraState); - } - - /** - * Retrieves the {@link ExposureState} of the {@link CameraInfo} with the specified identifier. - */ - @Override - @NonNull - public Long getExposureState(@NonNull Long identifier) { - CameraInfo cameraInfo = - (CameraInfo) Objects.requireNonNull(instanceManager.getInstance(identifier)); - ExposureState exposureState = cameraInfo.getExposureState(); - - ExposureStateFlutterApiImpl exposureStateFlutterApiImpl = - new ExposureStateFlutterApiImpl(binaryMessenger, instanceManager); - exposureStateFlutterApiImpl.create(exposureState, result -> {}); - - return instanceManager.getIdentifierForStrongReference(exposureState); - } - - /** - * Retrieves the {@link LiveData} of the {@link ZoomState} of the {@link CameraInfo} with the - * specified identifier. - */ - @NonNull - @Override - public Long getZoomState(@NonNull Long identifier) { - CameraInfo cameraInfo = - (CameraInfo) Objects.requireNonNull(instanceManager.getInstance(identifier)); - LiveData zoomState = cameraInfo.getZoomState(); - - LiveDataFlutterApiWrapper liveDataFlutterApiWrapper = - new LiveDataFlutterApiWrapper(binaryMessenger, instanceManager); - liveDataFlutterApiWrapper.create(zoomState, LiveDataSupportedType.ZOOM_STATE, reply -> {}); - - return instanceManager.getIdentifierForStrongReference(zoomState); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraInfoProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraInfoProxyApi.java new file mode 100644 index 000000000000..9b168dc52fdf --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraInfoProxyApi.java @@ -0,0 +1,45 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.camera.core.CameraInfo; +import androidx.camera.core.ExposureState; + +/** + * ProxyApi implementation for {@link CameraInfo}. This class may handle instantiating native object + * instances that are attached to a Dart instance or handle method calls on the associated native + * class or an instance of that class. + */ +class CameraInfoProxyApi extends PigeonApiCameraInfo { + CameraInfoProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @Override + public long sensorRotationDegrees(CameraInfo pigeonInstance) { + return pigeonInstance.getSensorRotationDegrees(); + } + + @NonNull + @Override + public ExposureState exposureState(CameraInfo pigeonInstance) { + return pigeonInstance.getExposureState(); + } + + @NonNull + @Override + public LiveDataProxyApi.LiveDataWrapper getCameraState(CameraInfo pigeonInstance) { + return new LiveDataProxyApi.LiveDataWrapper( + pigeonInstance.getCameraState(), LiveDataSupportedType.CAMERA_STATE); + } + + @NonNull + @Override + public LiveDataProxyApi.LiveDataWrapper getZoomState(CameraInfo pigeonInstance) { + return new LiveDataProxyApi.LiveDataWrapper( + pigeonInstance.getZoomState(), LiveDataSupportedType.ZOOM_STATE); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraIntegerRangeProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraIntegerRangeProxyApi.java new file mode 100644 index 000000000000..6ed0428990ed --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraIntegerRangeProxyApi.java @@ -0,0 +1,35 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import android.util.Range; +import androidx.annotation.NonNull; + +/** + * ProxyApi implementation for {@link android.util.Range}. This class may handle + * instantiating native object instances that are attached to a Dart instance or handle method calls + * on the associated native class or an instance of that class. + */ +class CameraIntegerRangeProxyApi extends PigeonApiCameraIntegerRange { + CameraIntegerRangeProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public Range pigeon_defaultConstructor(long lower, long upper) { + return new Range<>((int) lower, (int) upper); + } + + @Override + public long lower(android.util.Range pigeonInstance) { + return (Integer) pigeonInstance.getLower(); + } + + @Override + public long upper(android.util.Range pigeonInstance) { + return (Integer) pigeonInstance.getUpper(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraPermissionsError.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraPermissionsError.java new file mode 100644 index 000000000000..09b62227716d --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraPermissionsError.java @@ -0,0 +1,45 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import java.util.Objects; + +/** Contains data when an attempt to retrieve camera permissions fails. */ +public class CameraPermissionsError { + private final String errorCode; + private final String description; + + public CameraPermissionsError(@NonNull String errorCode, @NonNull String description) { + this.errorCode = errorCode; + this.description = description; + } + + @NonNull + public String getErrorCode() { + return errorCode; + } + + @NonNull + public String getDescription() { + return description; + } + + @Override + public boolean equals(@Nullable Object obj) { + if (obj instanceof CameraPermissionsError) { + return Objects.equals(((CameraPermissionsError) obj).errorCode, errorCode) + && Objects.equals(((CameraPermissionsError) obj).description, description); + } + + return false; + } + + @Override + public int hashCode() { + return Objects.hash(errorCode, description); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraPermissionsErrorProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraPermissionsErrorProxyApi.java new file mode 100644 index 000000000000..83d20dae7559 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraPermissionsErrorProxyApi.java @@ -0,0 +1,31 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; + +/** + * ProxyApi implementation for {@link CameraPermissionsError}. This class may handle instantiating + * native object instances that are attached to a Dart instance or handle method calls on the + * associated native class or an instance of that class. + */ +public class CameraPermissionsErrorProxyApi extends PigeonApiCameraPermissionsError { + public CameraPermissionsErrorProxyApi( + @NonNull CameraXLibraryPigeonProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public String errorCode(@NonNull CameraPermissionsError pigeonInstance) { + return pigeonInstance.getErrorCode(); + } + + @NonNull + @Override + public String description(@NonNull CameraPermissionsError pigeonInstance) { + return pigeonInstance.getDescription(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraPermissionsManager.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraPermissionsManager.java index 28093ec43711..ed80da9ea2c0 100644 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraPermissionsManager.java +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraPermissionsManager.java @@ -9,11 +9,12 @@ import android.app.Activity; import android.content.pm.PackageManager; import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; -final class CameraPermissionsManager { +public final class CameraPermissionsManager { interface PermissionsRegistry { @SuppressWarnings("deprecation") void addListener( @@ -21,7 +22,7 @@ void addListener( } interface ResultCallback { - void onResult(String errorCode, String errorDescription); + void onResult(@Nullable CameraPermissionsError error); } /** @@ -48,15 +49,16 @@ void requestPermissions( ResultCallback callback) { if (ongoing) { callback.onResult( - CAMERA_PERMISSIONS_REQUEST_ONGOING, CAMERA_PERMISSIONS_REQUEST_ONGOING_MESSAGE); + new CameraPermissionsError( + CAMERA_PERMISSIONS_REQUEST_ONGOING, CAMERA_PERMISSIONS_REQUEST_ONGOING_MESSAGE)); return; } if (!hasCameraPermission(activity) || (enableAudio && !hasAudioPermission(activity))) { permissionsRegistry.addListener( new CameraRequestPermissionsListener( - (String errorCode, String errorDescription) -> { + (CameraPermissionsError error) -> { ongoing = false; - callback.onResult(errorCode, errorDescription); + callback.onResult(error); })); ongoing = true; ActivityCompat.requestPermissions( @@ -67,7 +69,7 @@ void requestPermissions( CAMERA_REQUEST_ID); } else { // Permissions already exist. Call the callback with success. - callback.onResult(null, null); + callback.onResult(null); } } @@ -110,11 +112,13 @@ public boolean onRequestPermissionsResult( // grantResults could be empty if the permissions request with the user is interrupted // https://developer.android.com/reference/android/app/Activity#onRequestPermissionsResult(int,%20java.lang.String[],%20int[]) if (grantResults.length == 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) { - callback.onResult(CAMERA_ACCESS_DENIED, CAMERA_ACCESS_DENIED_MESSAGE); + callback.onResult( + new CameraPermissionsError(CAMERA_ACCESS_DENIED, CAMERA_ACCESS_DENIED_MESSAGE)); } else if (grantResults.length > 1 && grantResults[1] != PackageManager.PERMISSION_GRANTED) { - callback.onResult(AUDIO_ACCESS_DENIED, AUDIO_ACCESS_DENIED_MESSAGE); + callback.onResult( + new CameraPermissionsError(AUDIO_ACCESS_DENIED, AUDIO_ACCESS_DENIED_MESSAGE)); } else { - callback.onResult(null, null); + callback.onResult(null); } return true; } diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraProxyApi.java new file mode 100644 index 000000000000..3d9158f7ea11 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraProxyApi.java @@ -0,0 +1,33 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.camera.core.Camera; +import androidx.camera.core.CameraControl; +import androidx.camera.core.CameraInfo; + +/** + * ProxyApi implementation for {@link Camera}. This class may handle instantiating native object + * instances that are attached to a Dart instance or handle method calls on the associated native + * class or an instance of that class. + */ +class CameraProxyApi extends PigeonApiCamera { + CameraProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public CameraControl cameraControl(Camera pigeonInstance) { + return pigeonInstance.getCameraControl(); + } + + @NonNull + @Override + public CameraInfo getCameraInfo(Camera pigeonInstance) { + return pigeonInstance.getCameraInfo(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraSelectorFlutterApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraSelectorFlutterApiImpl.java deleted file mode 100644 index a0b30fa25417..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraSelectorFlutterApiImpl.java +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.camera.core.CameraSelector; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraSelectorFlutterApi; - -public class CameraSelectorFlutterApiImpl extends CameraSelectorFlutterApi { - private final InstanceManager instanceManager; - - public CameraSelectorFlutterApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - super(binaryMessenger); - this.instanceManager = instanceManager; - } - - void create(CameraSelector cameraSelector, Long lensFacing, Reply reply) { - create(instanceManager.addHostCreatedInstance(cameraSelector), lensFacing, reply); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraSelectorHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraSelectorHostApiImpl.java deleted file mode 100644 index bbd747342def..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraSelectorHostApiImpl.java +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.VisibleForTesting; -import androidx.camera.core.CameraInfo; -import androidx.camera.core.CameraSelector; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraSelectorHostApi; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -public class CameraSelectorHostApiImpl implements CameraSelectorHostApi { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - - @VisibleForTesting public @NonNull CameraXProxy cameraXProxy = new CameraXProxy(); - - public CameraSelectorHostApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - } - - @Override - public void create(@NonNull Long identifier, @Nullable Long lensFacing) { - CameraSelector.Builder cameraSelectorBuilder = cameraXProxy.createCameraSelectorBuilder(); - if (lensFacing != null) { - cameraSelectorBuilder = cameraSelectorBuilder.requireLensFacing(lensFacing.intValue()); - } - instanceManager.addDartCreatedInstance(cameraSelectorBuilder.build(), identifier); - } - - @Override - public @NonNull List filter(@NonNull Long identifier, @NonNull List cameraInfoIds) { - CameraSelector cameraSelector = - (CameraSelector) Objects.requireNonNull(instanceManager.getInstance(identifier)); - List cameraInfosForFilter = new ArrayList<>(); - - for (Number cameraInfoAsNumber : cameraInfoIds) { - Long cameraInfoId = cameraInfoAsNumber.longValue(); - - CameraInfo cameraInfo = - (CameraInfo) Objects.requireNonNull(instanceManager.getInstance(cameraInfoId)); - cameraInfosForFilter.add(cameraInfo); - } - - List filteredCameraInfos = cameraSelector.filter(cameraInfosForFilter); - List filteredCameraInfosIds = new ArrayList<>(); - - for (CameraInfo cameraInfo : filteredCameraInfos) { - Long filteredCameraInfoId = instanceManager.getIdentifierForStrongReference(cameraInfo); - filteredCameraInfosIds.add(filteredCameraInfoId); - } - - return filteredCameraInfosIds; - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraSelectorProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraSelectorProxyApi.java new file mode 100644 index 000000000000..b1eb41210607 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraSelectorProxyApi.java @@ -0,0 +1,68 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.camera.core.CameraInfo; +import androidx.camera.core.CameraSelector; +import androidx.camera.core.ExperimentalLensFacing; +import java.util.List; + +/** + * ProxyApi implementation for {@link CameraSelector}. This class may handle instantiating native + * object instances that are attached to a Dart instance or handle method calls on the associated + * native class or an instance of that class. + */ +class CameraSelectorProxyApi extends PigeonApiCameraSelector { + CameraSelectorProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @ExperimentalLensFacing + @NonNull + @Override + public CameraSelector pigeon_defaultConstructor(@Nullable LensFacing requireLensFacing) { + final CameraSelector.Builder builder = new CameraSelector.Builder(); + if (requireLensFacing != null) { + switch (requireLensFacing) { + case FRONT: + builder.requireLensFacing(CameraSelector.LENS_FACING_FRONT); + break; + case BACK: + builder.requireLensFacing(CameraSelector.LENS_FACING_BACK); + break; + case EXTERNAL: + builder.requireLensFacing(CameraSelector.LENS_FACING_EXTERNAL); + break; + case UNKNOWN: + builder.requireLensFacing(CameraSelector.LENS_FACING_UNKNOWN); + break; + } + } + return builder.build(); + } + + @NonNull + @Override + public androidx.camera.core.CameraSelector defaultBackCamera() { + return CameraSelector.DEFAULT_BACK_CAMERA; + } + + @NonNull + @Override + public androidx.camera.core.CameraSelector defaultFrontCamera() { + return CameraSelector.DEFAULT_FRONT_CAMERA; + } + + // List can be considered the same as List. + @SuppressWarnings("unchecked") + @NonNull + @Override + public List filter( + @NonNull CameraSelector pigeonInstance, @NonNull List cameraInfos) { + return pigeonInstance.filter((List) cameraInfos); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraSizeProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraSizeProxyApi.java new file mode 100644 index 000000000000..3294467fcd92 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraSizeProxyApi.java @@ -0,0 +1,35 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import android.util.Size; +import androidx.annotation.NonNull; + +/** + * ProxyApi implementation for {@link Size}. This class may handle instantiating native object + * instances that are attached to a Dart instance or handle method calls on the associated native + * class or an instance of that class. + */ +class CameraSizeProxyApi extends PigeonApiCameraSize { + CameraSizeProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public Size pigeon_defaultConstructor(long width, long height) { + return new Size((int) width, (int) height); + } + + @Override + public long width(@NonNull Size pigeonInstance) { + return pigeonInstance.getWidth(); + } + + @Override + public long height(Size pigeonInstance) { + return pigeonInstance.getHeight(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraStateErrorFlutterApiWrapper.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraStateErrorFlutterApiWrapper.java deleted file mode 100644 index f4c8d6ee4afd..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraStateErrorFlutterApiWrapper.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.annotation.VisibleForTesting; -import androidx.camera.core.CameraState; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraStateErrorFlutterApi; - -/** - * Flutter API implementation for {@link CameraStateError}. - * - *

This class may handle adding native instances that are attached to a Dart instance or passing - * arguments of callbacks methods to a Dart instance. - */ -public class CameraStateErrorFlutterApiWrapper { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - private CameraStateErrorFlutterApi cameraStateErrorFlutterApi; - - /** - * Constructs a {@link CameraStateErrorFlutterApiWrapper}. - * - * @param binaryMessenger used to communicate with Dart over asynchronous messages - * @param instanceManager maintains instances stored to communicate with attached Dart objects - */ - public CameraStateErrorFlutterApiWrapper( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - cameraStateErrorFlutterApi = new CameraStateErrorFlutterApi(binaryMessenger); - } - - /** - * Stores the {@link CameraStateError} instance and notifies Dart to create and store a new {@link - * CameraStateError} instance that is attached to this one. If {@code instance} has already been - * added, this method does nothing. - */ - public void create( - @NonNull CameraState.StateError instance, - @NonNull Long code, - @NonNull CameraStateErrorFlutterApi.Reply callback) { - if (!instanceManager.containsInstance(instance)) { - cameraStateErrorFlutterApi.create( - instanceManager.addHostCreatedInstance(instance), code, callback); - } - } - - /** Sets the Flutter API used to send messages to Dart. */ - @VisibleForTesting - void setApi(@NonNull CameraStateErrorFlutterApi api) { - this.cameraStateErrorFlutterApi = api; - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraStateFlutterApiWrapper.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraStateFlutterApiWrapper.java deleted file mode 100644 index cb1c30ad424e..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraStateFlutterApiWrapper.java +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.VisibleForTesting; -import androidx.camera.core.CameraState; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraStateFlutterApi; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraStateType; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraStateTypeData; - -/** - * Flutter API implementation for {@link CameraState}. - * - *

This class may handle adding native instances that are attached to a Dart instance or passing - * arguments of callbacks methods to a Dart instance. - */ -public class CameraStateFlutterApiWrapper { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - private CameraStateFlutterApi cameraStateFlutterApi; - - /** - * Constructs a {@link CameraStateFlutterApiWrapper}. - * - * @param binaryMessenger used to communicate with Dart over asynchronous messages - * @param instanceManager maintains instances stored to communicate with attached Dart objects - */ - public CameraStateFlutterApiWrapper( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - cameraStateFlutterApi = new CameraStateFlutterApi(binaryMessenger); - } - - /** - * Stores the {@link CameraState} instance and notifies Dart to create and store a new {@link - * CameraState} instance that is attached to this one. If {@code instance} has already been added, - * this method does nothing. - */ - public void create( - @NonNull CameraState instance, - @NonNull CameraStateType type, - @Nullable CameraState.StateError error, - @NonNull CameraStateFlutterApi.Reply callback) { - if (instanceManager.containsInstance(instance)) { - return; - } - - if (error != null) { - // if there is a problem with the current camera state, we need to create a CameraStateError - // to send to the Dart side. - new CameraStateErrorFlutterApiWrapper(binaryMessenger, instanceManager) - .create(error, Long.valueOf(error.getCode()), reply -> {}); - } - - cameraStateFlutterApi.create( - instanceManager.addHostCreatedInstance(instance), - new CameraStateTypeData.Builder().setValue(type).build(), - instanceManager.getIdentifierForStrongReference(error), - callback); - } - - /** Converts CameraX CameraState.Type to CameraStateType that the Dart side understands. */ - @NonNull - public static CameraStateType getCameraStateType(@NonNull CameraState.Type type) { - CameraStateType cameraStateType = null; - switch (type) { - case CLOSED: - cameraStateType = CameraStateType.CLOSED; - break; - case CLOSING: - cameraStateType = CameraStateType.CLOSING; - break; - case OPEN: - cameraStateType = CameraStateType.OPEN; - break; - case OPENING: - cameraStateType = CameraStateType.OPENING; - break; - case PENDING_OPEN: - cameraStateType = CameraStateType.PENDING_OPEN; - break; - } - - if (cameraStateType == null) { - throw new IllegalArgumentException( - "The CameraState.Type passed to this method was not recognized."); - } - return cameraStateType; - } - - /** Sets the Flutter API used to send messages to Dart. */ - @VisibleForTesting - void setApi(@NonNull CameraStateFlutterApi api) { - this.cameraStateFlutterApi = api; - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraStateProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraStateProxyApi.java new file mode 100644 index 000000000000..33f164a0193b --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraStateProxyApi.java @@ -0,0 +1,46 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.camera.core.CameraState; +import androidx.camera.core.CameraState.StateError; + +/** + * ProxyApi implementation for {@link CameraState}. This class may handle instantiating native + * object instances that are attached to a Dart instance or handle method calls on the associated + * native class or an instance of that class. + */ +class CameraStateProxyApi extends PigeonApiCameraState { + CameraStateProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public CameraStateType type(CameraState pigeonInstance) { + switch (pigeonInstance.getType()) { + case PENDING_OPEN: + return CameraStateType.PENDING_OPEN; + case OPENING: + return CameraStateType.OPENING; + case OPEN: + return CameraStateType.OPEN; + case CLOSING: + return CameraStateType.CLOSING; + case CLOSED: + return CameraStateType.CLOSED; + default: + return CameraStateType.UNKNOWN; + } + } + + @Nullable + @Override + public StateError error(CameraState pigeonInstance) { + return pigeonInstance.getError(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraStateStateErrorProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraStateStateErrorProxyApi.java new file mode 100644 index 000000000000..6864a3dd549a --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraStateStateErrorProxyApi.java @@ -0,0 +1,42 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.camera.core.CameraState; + +/** + * ProxyApi implementation for {@link CameraState.StateError}. This class may handle instantiating + * native object instances that are attached to a Dart instance or handle method calls on the + * associated native class or an instance of that class. + */ +class CameraStateStateErrorProxyApi extends PigeonApiCameraStateStateError { + CameraStateStateErrorProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public CameraStateErrorCode code(CameraState.StateError pigeonInstance) { + switch (pigeonInstance.getCode()) { + case CameraState.ERROR_CAMERA_DISABLED: + return CameraStateErrorCode.CAMERA_DISABLED; + case CameraState.ERROR_CAMERA_FATAL_ERROR: + return CameraStateErrorCode.CAMERA_FATAL_ERROR; + case CameraState.ERROR_CAMERA_IN_USE: + return CameraStateErrorCode.CAMERA_IN_USE; + case CameraState.ERROR_DO_NOT_DISTURB_MODE_ENABLED: + return CameraStateErrorCode.DO_NOT_DISTURB_MODE_ENABLED; + case CameraState.ERROR_MAX_CAMERAS_IN_USE: + return CameraStateErrorCode.MAX_CAMERAS_IN_USE; + case CameraState.ERROR_OTHER_RECOVERABLE_ERROR: + return CameraStateErrorCode.OTHER_RECOVERABLE_ERROR; + case CameraState.ERROR_STREAM_CONFIG: + return CameraStateErrorCode.STREAM_CONFIG; + default: + return io.flutter.plugins.camerax.CameraStateErrorCode.UNKNOWN; + } + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraXLibrary.g.kt b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraXLibrary.g.kt new file mode 100644 index 000000000000..ab1ed726680d --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraXLibrary.g.kt @@ -0,0 +1,7207 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +// Autogenerated from Pigeon (v25.2.0), do not edit directly. +// See also: https://pub.dev/packages/pigeon +@file:Suppress("UNCHECKED_CAST", "ArrayInDataClass", "UnsafeOptInUsageError", "SyntheticAccessor") + +package io.flutter.plugins.camerax + +import android.util.Log +import io.flutter.plugin.common.BasicMessageChannel +import io.flutter.plugin.common.BinaryMessenger +import io.flutter.plugin.common.MessageCodec +import io.flutter.plugin.common.StandardMessageCodec +import java.io.ByteArrayOutputStream +import java.nio.ByteBuffer + +private fun wrapResult(result: Any?): List { + return listOf(result) +} + +private fun wrapError(exception: Throwable): List { + return if (exception is CameraXError) { + listOf(exception.code, exception.message, exception.details) + } else { + listOf( + exception.javaClass.simpleName, + exception.toString(), + "Cause: " + exception.cause + ", Stacktrace: " + Log.getStackTraceString(exception)) + } +} + +private fun createConnectionError(channelName: String): CameraXError { + return CameraXError( + "channel-error", "Unable to establish connection on channel: '$channelName'.", "") +} + +/** + * Error class for passing custom error details to Flutter via a thrown PlatformException. + * + * @property code The error code. + * @property message The error message. + * @property details The error details. Must be a datatype supported by the api codec. + */ +class CameraXError( + val code: String, + override val message: String? = null, + val details: Any? = null +) : Throwable() +/** + * Maintains instances used to communicate with the corresponding objects in Dart. + * + * Objects stored in this container are represented by an object in Dart that is also stored in an + * InstanceManager with the same identifier. + * + * When an instance is added with an identifier, either can be used to retrieve the other. + * + * Added instances are added as a weak reference and a strong reference. When the strong reference + * is removed with [remove] and the weak reference is deallocated, the + * `finalizationListener.onFinalize` is called with the instance's identifier. However, if the + * strong reference is removed and then the identifier is retrieved with the intention to pass the + * identifier to Dart (e.g. calling [getIdentifierForStrongReference]), the strong reference to the + * instance is recreated. The strong reference will then need to be removed manually again. + */ +@Suppress("UNCHECKED_CAST", "MemberVisibilityCanBePrivate") +class CameraXLibraryPigeonInstanceManager( + private val finalizationListener: PigeonFinalizationListener +) { + /** Interface for listening when a weak reference of an instance is removed from the manager. */ + interface PigeonFinalizationListener { + fun onFinalize(identifier: Long) + } + + private val identifiers = java.util.WeakHashMap() + private val weakInstances = HashMap>() + private val strongInstances = HashMap() + private val referenceQueue = java.lang.ref.ReferenceQueue() + private val weakReferencesToIdentifiers = HashMap, Long>() + private val handler = android.os.Handler(android.os.Looper.getMainLooper()) + private var nextIdentifier: Long = minHostCreatedIdentifier + private var hasFinalizationListenerStopped = false + + /** + * Modifies the time interval used to define how often this instance removes garbage collected + * weak references to native Android objects that this instance was managing. + */ + var clearFinalizedWeakReferencesInterval: Long = 3000 + set(value) { + handler.removeCallbacks { this.releaseAllFinalizedInstances() } + field = value + releaseAllFinalizedInstances() + } + + init { + handler.postDelayed({ releaseAllFinalizedInstances() }, clearFinalizedWeakReferencesInterval) + } + + companion object { + // Identifiers are locked to a specific range to avoid collisions with objects + // created simultaneously from Dart. + // Host uses identifiers >= 2^16 and Dart is expected to use values n where, + // 0 <= n < 2^16. + private const val minHostCreatedIdentifier: Long = 65536 + private const val tag = "PigeonInstanceManager" + + /** + * Instantiate a new manager with a listener for garbage collected weak references. + * + * When the manager is no longer needed, [stopFinalizationListener] must be called. + */ + fun create( + finalizationListener: PigeonFinalizationListener + ): CameraXLibraryPigeonInstanceManager { + return CameraXLibraryPigeonInstanceManager(finalizationListener) + } + } + + /** + * Removes `identifier` and return its associated strongly referenced instance, if present, from + * the manager. + */ + fun remove(identifier: Long): T? { + logWarningIfFinalizationListenerHasStopped() + return strongInstances.remove(identifier) as T? + } + + /** + * Retrieves the identifier paired with an instance, if present, otherwise `null`. + * + * If the manager contains a strong reference to `instance`, it will return the identifier + * associated with `instance`. If the manager contains only a weak reference to `instance`, a new + * strong reference to `instance` will be added and will need to be removed again with [remove]. + * + * If this method returns a nonnull identifier, this method also expects the Dart + * `CameraXLibraryPigeonInstanceManager` to have, or recreate, a weak reference to the Dart + * instance the identifier is associated with. + */ + fun getIdentifierForStrongReference(instance: Any?): Long? { + logWarningIfFinalizationListenerHasStopped() + val identifier = identifiers[instance] + if (identifier != null) { + strongInstances[identifier] = instance!! + } + return identifier + } + + /** + * Adds a new instance that was instantiated from Dart. + * + * The same instance can be added multiple times, but each identifier must be unique. This allows + * two objects that are equivalent (e.g. the `equals` method returns true and their hashcodes are + * equal) to both be added. + * + * [identifier] must be >= 0 and unique. + */ + fun addDartCreatedInstance(instance: Any, identifier: Long) { + logWarningIfFinalizationListenerHasStopped() + addInstance(instance, identifier) + } + + /** + * Adds a new unique instance that was instantiated from the host platform. + * + * [identifier] must be >= 0 and unique. + */ + fun addHostCreatedInstance(instance: Any): Long { + logWarningIfFinalizationListenerHasStopped() + require(!containsInstance(instance)) { + "Instance of ${instance.javaClass} has already been added." + } + val identifier = nextIdentifier++ + addInstance(instance, identifier) + return identifier + } + + /** Retrieves the instance associated with identifier, if present, otherwise `null`. */ + fun getInstance(identifier: Long): T? { + logWarningIfFinalizationListenerHasStopped() + val instance = weakInstances[identifier] as java.lang.ref.WeakReference? + return instance?.get() + } + + /** Returns whether this manager contains the given `instance`. */ + fun containsInstance(instance: Any?): Boolean { + logWarningIfFinalizationListenerHasStopped() + return identifiers.containsKey(instance) + } + + /** + * Stops the periodic run of the [PigeonFinalizationListener] for instances that have been garbage + * collected. + * + * The InstanceManager can continue to be used, but the [PigeonFinalizationListener] will no + * longer be called and methods will log a warning. + */ + fun stopFinalizationListener() { + handler.removeCallbacks { this.releaseAllFinalizedInstances() } + hasFinalizationListenerStopped = true + } + + /** + * Removes all of the instances from this manager. + * + * The manager will be empty after this call returns. + */ + fun clear() { + identifiers.clear() + weakInstances.clear() + strongInstances.clear() + weakReferencesToIdentifiers.clear() + } + + /** + * Whether the [PigeonFinalizationListener] is still being called for instances that are garbage + * collected. + * + * See [stopFinalizationListener]. + */ + fun hasFinalizationListenerStopped(): Boolean { + return hasFinalizationListenerStopped + } + + private fun releaseAllFinalizedInstances() { + if (hasFinalizationListenerStopped()) { + return + } + var reference: java.lang.ref.WeakReference? + while ((referenceQueue.poll() as java.lang.ref.WeakReference?).also { reference = it } != + null) { + val identifier = weakReferencesToIdentifiers.remove(reference) + if (identifier != null) { + weakInstances.remove(identifier) + strongInstances.remove(identifier) + finalizationListener.onFinalize(identifier) + } + } + handler.postDelayed({ releaseAllFinalizedInstances() }, clearFinalizedWeakReferencesInterval) + } + + private fun addInstance(instance: Any, identifier: Long) { + require(identifier >= 0) { "Identifier must be >= 0: $identifier" } + require(!weakInstances.containsKey(identifier)) { + "Identifier has already been added: $identifier" + } + val weakReference = java.lang.ref.WeakReference(instance, referenceQueue) + identifiers[instance] = identifier + weakInstances[identifier] = weakReference + weakReferencesToIdentifiers[weakReference] = identifier + strongInstances[identifier] = instance + } + + private fun logWarningIfFinalizationListenerHasStopped() { + if (hasFinalizationListenerStopped()) { + Log.w( + tag, + "The manager was used after calls to the PigeonFinalizationListener has been stopped.") + } + } +} + +/** Generated API for managing the Dart and native `InstanceManager`s. */ +private class CameraXLibraryPigeonInstanceManagerApi(val binaryMessenger: BinaryMessenger) { + companion object { + /** The codec used by CameraXLibraryPigeonInstanceManagerApi. */ + val codec: MessageCodec by lazy { CameraXLibraryPigeonCodec() } + + /** + * Sets up an instance of `CameraXLibraryPigeonInstanceManagerApi` to handle messages from the + * `binaryMessenger`. + */ + fun setUpMessageHandlers( + binaryMessenger: BinaryMessenger, + instanceManager: CameraXLibraryPigeonInstanceManager? + ) { + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.PigeonInternalInstanceManager.removeStrongReference", + codec) + if (instanceManager != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val identifierArg = args[0] as Long + val wrapped: List = + try { + instanceManager.remove(identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.PigeonInternalInstanceManager.clear", + codec) + if (instanceManager != null) { + channel.setMessageHandler { _, reply -> + val wrapped: List = + try { + instanceManager.clear() + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + fun removeStrongReference(identifierArg: Long, callback: (Result) -> Unit) { + val channelName = + "dev.flutter.pigeon.camera_android_camerax.PigeonInternalInstanceManager.removeStrongReference" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback(Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } +} +/** + * Provides implementations for each ProxyApi implementation and provides access to resources needed + * by any implementation. + */ +abstract class CameraXLibraryPigeonProxyApiRegistrar(val binaryMessenger: BinaryMessenger) { + /** Whether APIs should ignore calling to Dart. */ + public var ignoreCallsToDart = false + val instanceManager: CameraXLibraryPigeonInstanceManager + private var _codec: MessageCodec? = null + val codec: MessageCodec + get() { + if (_codec == null) { + _codec = CameraXLibraryPigeonProxyApiBaseCodec(this) + } + return _codec!! + } + + init { + val api = CameraXLibraryPigeonInstanceManagerApi(binaryMessenger) + instanceManager = + CameraXLibraryPigeonInstanceManager.create( + object : CameraXLibraryPigeonInstanceManager.PigeonFinalizationListener { + override fun onFinalize(identifier: Long) { + api.removeStrongReference(identifier) { + if (it.isFailure) { + Log.e( + "PigeonProxyApiRegistrar", + "Failed to remove Dart strong reference with identifier: $identifier") + } + } + } + }) + } + /** + * An implementation of [PigeonApiCameraSize] used to add a new Dart instance of `CameraSize` to + * the Dart `InstanceManager`. + */ + abstract fun getPigeonApiCameraSize(): PigeonApiCameraSize + + /** + * An implementation of [PigeonApiResolutionInfo] used to add a new Dart instance of + * `ResolutionInfo` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiResolutionInfo(): PigeonApiResolutionInfo + + /** + * An implementation of [PigeonApiCameraIntegerRange] used to add a new Dart instance of + * `CameraIntegerRange` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiCameraIntegerRange(): PigeonApiCameraIntegerRange + + /** + * An implementation of [PigeonApiVideoRecordEvent] used to add a new Dart instance of + * `VideoRecordEvent` to the Dart `InstanceManager`. + */ + open fun getPigeonApiVideoRecordEvent(): PigeonApiVideoRecordEvent { + return PigeonApiVideoRecordEvent(this) + } + + /** + * An implementation of [PigeonApiVideoRecordEventStart] used to add a new Dart instance of + * `VideoRecordEventStart` to the Dart `InstanceManager`. + */ + open fun getPigeonApiVideoRecordEventStart(): PigeonApiVideoRecordEventStart { + return PigeonApiVideoRecordEventStart(this) + } + + /** + * An implementation of [PigeonApiVideoRecordEventFinalize] used to add a new Dart instance of + * `VideoRecordEventFinalize` to the Dart `InstanceManager`. + */ + open fun getPigeonApiVideoRecordEventFinalize(): PigeonApiVideoRecordEventFinalize { + return PigeonApiVideoRecordEventFinalize(this) + } + + /** + * An implementation of [PigeonApiMeteringPoint] used to add a new Dart instance of + * `MeteringPoint` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiMeteringPoint(): PigeonApiMeteringPoint + + /** + * An implementation of [PigeonApiObserver] used to add a new Dart instance of `Observer` to the + * Dart `InstanceManager`. + */ + abstract fun getPigeonApiObserver(): PigeonApiObserver + + /** + * An implementation of [PigeonApiCameraInfo] used to add a new Dart instance of `CameraInfo` to + * the Dart `InstanceManager`. + */ + abstract fun getPigeonApiCameraInfo(): PigeonApiCameraInfo + + /** + * An implementation of [PigeonApiCameraSelector] used to add a new Dart instance of + * `CameraSelector` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiCameraSelector(): PigeonApiCameraSelector + + /** + * An implementation of [PigeonApiProcessCameraProvider] used to add a new Dart instance of + * `ProcessCameraProvider` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiProcessCameraProvider(): PigeonApiProcessCameraProvider + + /** + * An implementation of [PigeonApiUseCase] used to add a new Dart instance of `UseCase` to the + * Dart `InstanceManager`. + */ + open fun getPigeonApiUseCase(): PigeonApiUseCase { + return PigeonApiUseCase(this) + } + + /** + * An implementation of [PigeonApiCamera] used to add a new Dart instance of `Camera` to the Dart + * `InstanceManager`. + */ + abstract fun getPigeonApiCamera(): PigeonApiCamera + + /** + * An implementation of [PigeonApiSystemServicesManager] used to add a new Dart instance of + * `SystemServicesManager` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiSystemServicesManager(): PigeonApiSystemServicesManager + + /** + * An implementation of [PigeonApiCameraPermissionsError] used to add a new Dart instance of + * `CameraPermissionsError` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiCameraPermissionsError(): PigeonApiCameraPermissionsError + + /** + * An implementation of [PigeonApiDeviceOrientationManager] used to add a new Dart instance of + * `DeviceOrientationManager` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiDeviceOrientationManager(): PigeonApiDeviceOrientationManager + + /** + * An implementation of [PigeonApiPreview] used to add a new Dart instance of `Preview` to the + * Dart `InstanceManager`. + */ + abstract fun getPigeonApiPreview(): PigeonApiPreview + + /** + * An implementation of [PigeonApiVideoCapture] used to add a new Dart instance of `VideoCapture` + * to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiVideoCapture(): PigeonApiVideoCapture + + /** + * An implementation of [PigeonApiVideoOutput] used to add a new Dart instance of `VideoOutput` to + * the Dart `InstanceManager`. + */ + open fun getPigeonApiVideoOutput(): PigeonApiVideoOutput { + return PigeonApiVideoOutput(this) + } + + /** + * An implementation of [PigeonApiRecorder] used to add a new Dart instance of `Recorder` to the + * Dart `InstanceManager`. + */ + abstract fun getPigeonApiRecorder(): PigeonApiRecorder + + /** + * An implementation of [PigeonApiVideoRecordEventListener] used to add a new Dart instance of + * `VideoRecordEventListener` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiVideoRecordEventListener(): PigeonApiVideoRecordEventListener + + /** + * An implementation of [PigeonApiPendingRecording] used to add a new Dart instance of + * `PendingRecording` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiPendingRecording(): PigeonApiPendingRecording + + /** + * An implementation of [PigeonApiRecording] used to add a new Dart instance of `Recording` to the + * Dart `InstanceManager`. + */ + abstract fun getPigeonApiRecording(): PigeonApiRecording + + /** + * An implementation of [PigeonApiImageCapture] used to add a new Dart instance of `ImageCapture` + * to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiImageCapture(): PigeonApiImageCapture + + /** + * An implementation of [PigeonApiResolutionStrategy] used to add a new Dart instance of + * `ResolutionStrategy` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiResolutionStrategy(): PigeonApiResolutionStrategy + + /** + * An implementation of [PigeonApiResolutionSelector] used to add a new Dart instance of + * `ResolutionSelector` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiResolutionSelector(): PigeonApiResolutionSelector + + /** + * An implementation of [PigeonApiAspectRatioStrategy] used to add a new Dart instance of + * `AspectRatioStrategy` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiAspectRatioStrategy(): PigeonApiAspectRatioStrategy + + /** + * An implementation of [PigeonApiCameraState] used to add a new Dart instance of `CameraState` to + * the Dart `InstanceManager`. + */ + abstract fun getPigeonApiCameraState(): PigeonApiCameraState + + /** + * An implementation of [PigeonApiExposureState] used to add a new Dart instance of + * `ExposureState` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiExposureState(): PigeonApiExposureState + + /** + * An implementation of [PigeonApiZoomState] used to add a new Dart instance of `ZoomState` to the + * Dart `InstanceManager`. + */ + abstract fun getPigeonApiZoomState(): PigeonApiZoomState + + /** + * An implementation of [PigeonApiImageAnalysis] used to add a new Dart instance of + * `ImageAnalysis` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiImageAnalysis(): PigeonApiImageAnalysis + + /** + * An implementation of [PigeonApiAnalyzer] used to add a new Dart instance of `Analyzer` to the + * Dart `InstanceManager`. + */ + abstract fun getPigeonApiAnalyzer(): PigeonApiAnalyzer + + /** + * An implementation of [PigeonApiCameraStateStateError] used to add a new Dart instance of + * `CameraStateStateError` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiCameraStateStateError(): PigeonApiCameraStateStateError + + /** + * An implementation of [PigeonApiLiveData] used to add a new Dart instance of `LiveData` to the + * Dart `InstanceManager`. + */ + abstract fun getPigeonApiLiveData(): PigeonApiLiveData + + /** + * An implementation of [PigeonApiImageProxy] used to add a new Dart instance of `ImageProxy` to + * the Dart `InstanceManager`. + */ + abstract fun getPigeonApiImageProxy(): PigeonApiImageProxy + + /** + * An implementation of [PigeonApiPlaneProxy] used to add a new Dart instance of `PlaneProxy` to + * the Dart `InstanceManager`. + */ + abstract fun getPigeonApiPlaneProxy(): PigeonApiPlaneProxy + + /** + * An implementation of [PigeonApiQualitySelector] used to add a new Dart instance of + * `QualitySelector` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiQualitySelector(): PigeonApiQualitySelector + + /** + * An implementation of [PigeonApiFallbackStrategy] used to add a new Dart instance of + * `FallbackStrategy` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiFallbackStrategy(): PigeonApiFallbackStrategy + + /** + * An implementation of [PigeonApiCameraControl] used to add a new Dart instance of + * `CameraControl` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiCameraControl(): PigeonApiCameraControl + + /** + * An implementation of [PigeonApiFocusMeteringActionBuilder] used to add a new Dart instance of + * `FocusMeteringActionBuilder` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiFocusMeteringActionBuilder(): PigeonApiFocusMeteringActionBuilder + + /** + * An implementation of [PigeonApiFocusMeteringAction] used to add a new Dart instance of + * `FocusMeteringAction` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiFocusMeteringAction(): PigeonApiFocusMeteringAction + + /** + * An implementation of [PigeonApiFocusMeteringResult] used to add a new Dart instance of + * `FocusMeteringResult` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiFocusMeteringResult(): PigeonApiFocusMeteringResult + + /** + * An implementation of [PigeonApiCaptureRequest] used to add a new Dart instance of + * `CaptureRequest` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiCaptureRequest(): PigeonApiCaptureRequest + + /** + * An implementation of [PigeonApiCaptureRequestKey] used to add a new Dart instance of + * `CaptureRequestKey` to the Dart `InstanceManager`. + */ + open fun getPigeonApiCaptureRequestKey(): PigeonApiCaptureRequestKey { + return PigeonApiCaptureRequestKey(this) + } + + /** + * An implementation of [PigeonApiCaptureRequestOptions] used to add a new Dart instance of + * `CaptureRequestOptions` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiCaptureRequestOptions(): PigeonApiCaptureRequestOptions + + /** + * An implementation of [PigeonApiCamera2CameraControl] used to add a new Dart instance of + * `Camera2CameraControl` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiCamera2CameraControl(): PigeonApiCamera2CameraControl + + /** + * An implementation of [PigeonApiResolutionFilter] used to add a new Dart instance of + * `ResolutionFilter` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiResolutionFilter(): PigeonApiResolutionFilter + + /** + * An implementation of [PigeonApiCameraCharacteristicsKey] used to add a new Dart instance of + * `CameraCharacteristicsKey` to the Dart `InstanceManager`. + */ + open fun getPigeonApiCameraCharacteristicsKey(): PigeonApiCameraCharacteristicsKey { + return PigeonApiCameraCharacteristicsKey(this) + } + + /** + * An implementation of [PigeonApiCameraCharacteristics] used to add a new Dart instance of + * `CameraCharacteristics` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiCameraCharacteristics(): PigeonApiCameraCharacteristics + + /** + * An implementation of [PigeonApiCamera2CameraInfo] used to add a new Dart instance of + * `Camera2CameraInfo` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiCamera2CameraInfo(): PigeonApiCamera2CameraInfo + + /** + * An implementation of [PigeonApiMeteringPointFactory] used to add a new Dart instance of + * `MeteringPointFactory` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiMeteringPointFactory(): PigeonApiMeteringPointFactory + + /** + * An implementation of [PigeonApiDisplayOrientedMeteringPointFactory] used to add a new Dart + * instance of `DisplayOrientedMeteringPointFactory` to the Dart `InstanceManager`. + */ + abstract fun getPigeonApiDisplayOrientedMeteringPointFactory(): + PigeonApiDisplayOrientedMeteringPointFactory + + fun setUp() { + CameraXLibraryPigeonInstanceManagerApi.setUpMessageHandlers(binaryMessenger, instanceManager) + PigeonApiCameraSize.setUpMessageHandlers(binaryMessenger, getPigeonApiCameraSize()) + PigeonApiCameraIntegerRange.setUpMessageHandlers( + binaryMessenger, getPigeonApiCameraIntegerRange()) + PigeonApiMeteringPoint.setUpMessageHandlers(binaryMessenger, getPigeonApiMeteringPoint()) + PigeonApiObserver.setUpMessageHandlers(binaryMessenger, getPigeonApiObserver()) + PigeonApiCameraInfo.setUpMessageHandlers(binaryMessenger, getPigeonApiCameraInfo()) + PigeonApiCameraSelector.setUpMessageHandlers(binaryMessenger, getPigeonApiCameraSelector()) + PigeonApiProcessCameraProvider.setUpMessageHandlers( + binaryMessenger, getPigeonApiProcessCameraProvider()) + PigeonApiCamera.setUpMessageHandlers(binaryMessenger, getPigeonApiCamera()) + PigeonApiSystemServicesManager.setUpMessageHandlers( + binaryMessenger, getPigeonApiSystemServicesManager()) + PigeonApiDeviceOrientationManager.setUpMessageHandlers( + binaryMessenger, getPigeonApiDeviceOrientationManager()) + PigeonApiPreview.setUpMessageHandlers(binaryMessenger, getPigeonApiPreview()) + PigeonApiVideoCapture.setUpMessageHandlers(binaryMessenger, getPigeonApiVideoCapture()) + PigeonApiRecorder.setUpMessageHandlers(binaryMessenger, getPigeonApiRecorder()) + PigeonApiVideoRecordEventListener.setUpMessageHandlers( + binaryMessenger, getPigeonApiVideoRecordEventListener()) + PigeonApiPendingRecording.setUpMessageHandlers(binaryMessenger, getPigeonApiPendingRecording()) + PigeonApiRecording.setUpMessageHandlers(binaryMessenger, getPigeonApiRecording()) + PigeonApiImageCapture.setUpMessageHandlers(binaryMessenger, getPigeonApiImageCapture()) + PigeonApiResolutionStrategy.setUpMessageHandlers( + binaryMessenger, getPigeonApiResolutionStrategy()) + PigeonApiResolutionSelector.setUpMessageHandlers( + binaryMessenger, getPigeonApiResolutionSelector()) + PigeonApiAspectRatioStrategy.setUpMessageHandlers( + binaryMessenger, getPigeonApiAspectRatioStrategy()) + PigeonApiImageAnalysis.setUpMessageHandlers(binaryMessenger, getPigeonApiImageAnalysis()) + PigeonApiAnalyzer.setUpMessageHandlers(binaryMessenger, getPigeonApiAnalyzer()) + PigeonApiLiveData.setUpMessageHandlers(binaryMessenger, getPigeonApiLiveData()) + PigeonApiImageProxy.setUpMessageHandlers(binaryMessenger, getPigeonApiImageProxy()) + PigeonApiQualitySelector.setUpMessageHandlers(binaryMessenger, getPigeonApiQualitySelector()) + PigeonApiFallbackStrategy.setUpMessageHandlers(binaryMessenger, getPigeonApiFallbackStrategy()) + PigeonApiCameraControl.setUpMessageHandlers(binaryMessenger, getPigeonApiCameraControl()) + PigeonApiFocusMeteringActionBuilder.setUpMessageHandlers( + binaryMessenger, getPigeonApiFocusMeteringActionBuilder()) + PigeonApiCaptureRequest.setUpMessageHandlers(binaryMessenger, getPigeonApiCaptureRequest()) + PigeonApiCaptureRequestOptions.setUpMessageHandlers( + binaryMessenger, getPigeonApiCaptureRequestOptions()) + PigeonApiCamera2CameraControl.setUpMessageHandlers( + binaryMessenger, getPigeonApiCamera2CameraControl()) + PigeonApiResolutionFilter.setUpMessageHandlers(binaryMessenger, getPigeonApiResolutionFilter()) + PigeonApiCameraCharacteristics.setUpMessageHandlers( + binaryMessenger, getPigeonApiCameraCharacteristics()) + PigeonApiCamera2CameraInfo.setUpMessageHandlers( + binaryMessenger, getPigeonApiCamera2CameraInfo()) + PigeonApiMeteringPointFactory.setUpMessageHandlers( + binaryMessenger, getPigeonApiMeteringPointFactory()) + PigeonApiDisplayOrientedMeteringPointFactory.setUpMessageHandlers( + binaryMessenger, getPigeonApiDisplayOrientedMeteringPointFactory()) + } + + fun tearDown() { + CameraXLibraryPigeonInstanceManagerApi.setUpMessageHandlers(binaryMessenger, null) + PigeonApiCameraSize.setUpMessageHandlers(binaryMessenger, null) + PigeonApiCameraIntegerRange.setUpMessageHandlers(binaryMessenger, null) + PigeonApiMeteringPoint.setUpMessageHandlers(binaryMessenger, null) + PigeonApiObserver.setUpMessageHandlers(binaryMessenger, null) + PigeonApiCameraInfo.setUpMessageHandlers(binaryMessenger, null) + PigeonApiCameraSelector.setUpMessageHandlers(binaryMessenger, null) + PigeonApiProcessCameraProvider.setUpMessageHandlers(binaryMessenger, null) + PigeonApiCamera.setUpMessageHandlers(binaryMessenger, null) + PigeonApiSystemServicesManager.setUpMessageHandlers(binaryMessenger, null) + PigeonApiDeviceOrientationManager.setUpMessageHandlers(binaryMessenger, null) + PigeonApiPreview.setUpMessageHandlers(binaryMessenger, null) + PigeonApiVideoCapture.setUpMessageHandlers(binaryMessenger, null) + PigeonApiRecorder.setUpMessageHandlers(binaryMessenger, null) + PigeonApiVideoRecordEventListener.setUpMessageHandlers(binaryMessenger, null) + PigeonApiPendingRecording.setUpMessageHandlers(binaryMessenger, null) + PigeonApiRecording.setUpMessageHandlers(binaryMessenger, null) + PigeonApiImageCapture.setUpMessageHandlers(binaryMessenger, null) + PigeonApiResolutionStrategy.setUpMessageHandlers(binaryMessenger, null) + PigeonApiResolutionSelector.setUpMessageHandlers(binaryMessenger, null) + PigeonApiAspectRatioStrategy.setUpMessageHandlers(binaryMessenger, null) + PigeonApiImageAnalysis.setUpMessageHandlers(binaryMessenger, null) + PigeonApiAnalyzer.setUpMessageHandlers(binaryMessenger, null) + PigeonApiLiveData.setUpMessageHandlers(binaryMessenger, null) + PigeonApiImageProxy.setUpMessageHandlers(binaryMessenger, null) + PigeonApiQualitySelector.setUpMessageHandlers(binaryMessenger, null) + PigeonApiFallbackStrategy.setUpMessageHandlers(binaryMessenger, null) + PigeonApiCameraControl.setUpMessageHandlers(binaryMessenger, null) + PigeonApiFocusMeteringActionBuilder.setUpMessageHandlers(binaryMessenger, null) + PigeonApiCaptureRequest.setUpMessageHandlers(binaryMessenger, null) + PigeonApiCaptureRequestOptions.setUpMessageHandlers(binaryMessenger, null) + PigeonApiCamera2CameraControl.setUpMessageHandlers(binaryMessenger, null) + PigeonApiResolutionFilter.setUpMessageHandlers(binaryMessenger, null) + PigeonApiCameraCharacteristics.setUpMessageHandlers(binaryMessenger, null) + PigeonApiCamera2CameraInfo.setUpMessageHandlers(binaryMessenger, null) + PigeonApiMeteringPointFactory.setUpMessageHandlers(binaryMessenger, null) + PigeonApiDisplayOrientedMeteringPointFactory.setUpMessageHandlers(binaryMessenger, null) + } +} + +private class CameraXLibraryPigeonProxyApiBaseCodec( + val registrar: CameraXLibraryPigeonProxyApiRegistrar +) : CameraXLibraryPigeonCodec() { + override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { + return when (type) { + 128.toByte() -> { + val identifier: Long = readValue(buffer) as Long + val instance: Any? = registrar.instanceManager.getInstance(identifier) + if (instance == null) { + Log.e("PigeonProxyApiBaseCodec", "Failed to find instance with identifier: $identifier") + } + return instance + } + else -> super.readValueOfType(type, buffer) + } + } + + override fun writeValue(stream: ByteArrayOutputStream, value: Any?) { + if (value is Boolean || + value is ByteArray || + value is Double || + value is DoubleArray || + value is FloatArray || + value is Int || + value is IntArray || + value is List<*> || + value is Long || + value is LongArray || + value is Map<*, *> || + value is String || + value is InfoSupportedHardwareLevel || + value is AspectRatio || + value is CameraStateType || + value is LiveDataSupportedType || + value is VideoQuality || + value is MeteringMode || + value is LensFacing || + value is CameraXFlashMode || + value is ResolutionStrategyFallbackRule || + value is AspectRatioStrategyFallbackRule || + value is CameraStateErrorCode || + value == null) { + super.writeValue(stream, value) + return + } + + if (value is android.util.Size) { + registrar.getPigeonApiCameraSize().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.ResolutionInfo) { + registrar.getPigeonApiResolutionInfo().pigeon_newInstance(value) {} + } else if (value is android.util.Range<*>) { + registrar.getPigeonApiCameraIntegerRange().pigeon_newInstance(value) {} + } else if (value is androidx.camera.video.VideoRecordEvent.Start) { + registrar.getPigeonApiVideoRecordEventStart().pigeon_newInstance(value) {} + } else if (value is androidx.camera.video.VideoRecordEvent.Finalize) { + registrar.getPigeonApiVideoRecordEventFinalize().pigeon_newInstance(value) {} + } else if (value is androidx.camera.video.VideoRecordEvent) { + registrar.getPigeonApiVideoRecordEvent().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.MeteringPoint) { + registrar.getPigeonApiMeteringPoint().pigeon_newInstance(value) {} + } else if (value is androidx.lifecycle.Observer<*>) { + registrar.getPigeonApiObserver().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.CameraInfo) { + registrar.getPigeonApiCameraInfo().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.CameraSelector) { + registrar.getPigeonApiCameraSelector().pigeon_newInstance(value) {} + } else if (value is androidx.camera.lifecycle.ProcessCameraProvider) { + registrar.getPigeonApiProcessCameraProvider().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.Camera) { + registrar.getPigeonApiCamera().pigeon_newInstance(value) {} + } else if (value is SystemServicesManager) { + registrar.getPigeonApiSystemServicesManager().pigeon_newInstance(value) {} + } else if (value is CameraPermissionsError) { + registrar.getPigeonApiCameraPermissionsError().pigeon_newInstance(value) {} + } else if (value is DeviceOrientationManager) { + registrar.getPigeonApiDeviceOrientationManager().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.Preview) { + registrar.getPigeonApiPreview().pigeon_newInstance(value) {} + } else if (value is androidx.camera.video.VideoCapture<*>) { + registrar.getPigeonApiVideoCapture().pigeon_newInstance(value) {} + } else if (value is androidx.camera.video.Recorder) { + registrar.getPigeonApiRecorder().pigeon_newInstance(value) {} + } else if (value is androidx.camera.video.VideoOutput) { + registrar.getPigeonApiVideoOutput().pigeon_newInstance(value) {} + } else if (value is VideoRecordEventListener) { + registrar.getPigeonApiVideoRecordEventListener().pigeon_newInstance(value) {} + } else if (value is androidx.camera.video.PendingRecording) { + registrar.getPigeonApiPendingRecording().pigeon_newInstance(value) {} + } else if (value is androidx.camera.video.Recording) { + registrar.getPigeonApiRecording().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.ImageCapture) { + registrar.getPigeonApiImageCapture().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.resolutionselector.ResolutionStrategy) { + registrar.getPigeonApiResolutionStrategy().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.resolutionselector.ResolutionSelector) { + registrar.getPigeonApiResolutionSelector().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.resolutionselector.AspectRatioStrategy) { + registrar.getPigeonApiAspectRatioStrategy().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.CameraState) { + registrar.getPigeonApiCameraState().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.ExposureState) { + registrar.getPigeonApiExposureState().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.ZoomState) { + registrar.getPigeonApiZoomState().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.ImageAnalysis) { + registrar.getPigeonApiImageAnalysis().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.UseCase) { + registrar.getPigeonApiUseCase().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.ImageAnalysis.Analyzer) { + registrar.getPigeonApiAnalyzer().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.CameraState.StateError) { + registrar.getPigeonApiCameraStateStateError().pigeon_newInstance(value) {} + } else if (value is io.flutter.plugins.camerax.LiveDataProxyApi.LiveDataWrapper) { + registrar.getPigeonApiLiveData().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.ImageProxy) { + registrar.getPigeonApiImageProxy().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.ImageProxy.PlaneProxy) { + registrar.getPigeonApiPlaneProxy().pigeon_newInstance(value) {} + } else if (value is androidx.camera.video.QualitySelector) { + registrar.getPigeonApiQualitySelector().pigeon_newInstance(value) {} + } else if (value is androidx.camera.video.FallbackStrategy) { + registrar.getPigeonApiFallbackStrategy().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.CameraControl) { + registrar.getPigeonApiCameraControl().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.FocusMeteringAction.Builder) { + registrar.getPigeonApiFocusMeteringActionBuilder().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.FocusMeteringAction) { + registrar.getPigeonApiFocusMeteringAction().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.FocusMeteringResult) { + registrar.getPigeonApiFocusMeteringResult().pigeon_newInstance(value) {} + } else if (value is android.hardware.camera2.CaptureRequest) { + registrar.getPigeonApiCaptureRequest().pigeon_newInstance(value) {} + } else if (value is android.hardware.camera2.CaptureRequest.Key<*>) { + registrar.getPigeonApiCaptureRequestKey().pigeon_newInstance(value) {} + } else if (value is androidx.camera.camera2.interop.CaptureRequestOptions) { + registrar.getPigeonApiCaptureRequestOptions().pigeon_newInstance(value) {} + } else if (value is androidx.camera.camera2.interop.Camera2CameraControl) { + registrar.getPigeonApiCamera2CameraControl().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.resolutionselector.ResolutionFilter) { + registrar.getPigeonApiResolutionFilter().pigeon_newInstance(value) {} + } else if (value is android.hardware.camera2.CameraCharacteristics.Key<*>) { + registrar.getPigeonApiCameraCharacteristicsKey().pigeon_newInstance(value) {} + } else if (value is android.hardware.camera2.CameraCharacteristics) { + registrar.getPigeonApiCameraCharacteristics().pigeon_newInstance(value) {} + } else if (value is androidx.camera.camera2.interop.Camera2CameraInfo) { + registrar.getPigeonApiCamera2CameraInfo().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.DisplayOrientedMeteringPointFactory) { + registrar.getPigeonApiDisplayOrientedMeteringPointFactory().pigeon_newInstance(value) {} + } else if (value is androidx.camera.core.MeteringPointFactory) { + registrar.getPigeonApiMeteringPointFactory().pigeon_newInstance(value) {} + } + + when { + registrar.instanceManager.containsInstance(value) -> { + stream.write(128) + writeValue(stream, registrar.instanceManager.getIdentifierForStrongReference(value)) + } + else -> + throw IllegalArgumentException( + "Unsupported value: '$value' of type '${value.javaClass.name}'") + } + } +} + +/** + * Generally classifies the overall set of the camera device functionality. + * + * See + * https://developer.android.com/reference/android/hardware/camera2/CameraMetadata#INFO_SUPPORTED_HARDWARE_LEVEL_3. + */ +enum class InfoSupportedHardwareLevel(val raw: Int) { + /** + * This camera device is capable of YUV reprocessing and RAW data capture, in addition to + * FULL-level capabilities. + */ + LEVEL3(0), + /** This camera device is backed by an external camera connected to this Android device. */ + EXTERNAL(1), + /** This camera device is capable of supporting advanced imaging applications. */ + FULL(2), + /** This camera device is running in backward compatibility mode. */ + LEGACY(3), + /** This camera device does not have enough capabilities to qualify as a FULL device or better. */ + LIMITED(4); + + companion object { + fun ofRaw(raw: Int): InfoSupportedHardwareLevel? { + return values().firstOrNull { it.raw == raw } + } + } +} + +/** + * The aspect ratio of the use case. + * + * See https://developer.android.com/reference/kotlin/androidx/camera/core/AspectRatio. + */ +enum class AspectRatio(val raw: Int) { + /** 16:9 standard aspect ratio. */ + RATIO16TO9(0), + /** 4:3 standard aspect ratio. */ + RATIO4TO3(1), + /** The aspect ratio representing no preference for aspect ratio. */ + RATIO_DEFAULT(2), + /** The value is not recognized by the wrapper. */ + UNKNOWN(3); + + companion object { + fun ofRaw(raw: Int): AspectRatio? { + return values().firstOrNull { it.raw == raw } + } + } +} + +/** + * The states the camera can be in. + * + * See https://developer.android.com/reference/androidx/camera/core/CameraState.Type. + */ +enum class CameraStateType(val raw: Int) { + /** Represents a state where the camera device is closed. */ + CLOSED(0), + /** Represents a state where the camera device is currently closing. */ + CLOSING(1), + /** Represents a state where the camera device is open. */ + OPEN(2), + /** Represents a state where the camera device is currently opening. */ + OPENING(3), + /** + * Represents a state where the camera is waiting for a signal to attempt to open the camera + * device. + */ + PENDING_OPEN(4), + /** This value is not recognized by this wrapper. */ + UNKNOWN(5); + + companion object { + fun ofRaw(raw: Int): CameraStateType? { + return values().firstOrNull { it.raw == raw } + } + } +} + +/** The types (T) properly wrapped to be used as a LiveData. */ +enum class LiveDataSupportedType(val raw: Int) { + CAMERA_STATE(0), + ZOOM_STATE(1); + + companion object { + fun ofRaw(raw: Int): LiveDataSupportedType? { + return values().firstOrNull { it.raw == raw } + } + } +} + +/** + * Video quality constraints that will be used by a QualitySelector to choose an appropriate video + * resolution. + * + * These are pre-defined quality constants that are universally used for video. + * + * See https://developer.android.com/reference/androidx/camera/video/Quality. + */ +enum class VideoQuality(val raw: Int) { + /** Standard Definition (SD) 480p video quality. */ + SD(0), + /** High Definition (HD) 720p video quality. */ + HD(1), + /** Full High Definition (FHD) 1080p video quality. */ + FHD(2), + /** Ultra High Definition (UHD) 2160p video quality. */ + UHD(3), + /** The lowest video quality supported by the video frame producer. */ + LOWEST(4), + /** The highest video quality supported by the video frame producer. */ + HIGHEST(5); + + companion object { + fun ofRaw(raw: Int): VideoQuality? { + return values().firstOrNull { it.raw == raw } + } + } +} + +/** + * A flag used for indicating metering mode regions. + * + * See + * https://developer.android.com/reference/kotlin/androidx/camera/core/FocusMeteringAction#FLAG_AF(). + */ +enum class MeteringMode(val raw: Int) { + /** A flag used in metering mode indicating the AE (Auto Exposure) region is enabled. */ + AE(0), + /** A flag used in metering mode indicating the AF (Auto Focus) region is enabled. */ + AF(1), + /** A flag used in metering mode indicating the AWB (Auto White Balance) region is enabled. */ + AWB(2); + + companion object { + fun ofRaw(raw: Int): MeteringMode? { + return values().firstOrNull { it.raw == raw } + } + } +} + +/** + * Direction of lens of a camera. + * + * See + * https://developer.android.com/reference/androidx/camera/core/CameraSelector#LENS_FACING_BACK(). + */ +enum class LensFacing(val raw: Int) { + /** A camera on the device facing the same direction as the device's screen. */ + FRONT(0), + /** A camera on the device facing the opposite direction as the device's screen. */ + BACK(1), + /** An external camera that has no fixed facing relative to the device's screen. */ + EXTERNAL(2), + /** A camera on the devices that its lens facing is resolved. */ + UNKNOWN(3); + + companion object { + fun ofRaw(raw: Int): LensFacing? { + return values().firstOrNull { it.raw == raw } + } + } +} + +/** + * FlashModes for image capture. + * + * See + * https://developer.android.com/reference/kotlin/androidx/camera/core/ImageCapture#FLASH_MODE_AUTO(). + */ +enum class CameraXFlashMode(val raw: Int) { + /** + * Auto flash. + * + * The flash will be used according to the camera system's determination when taking a picture. + */ + AUTO(0), + /** + * No flash. + * + * The flash will never be used when taking a picture. + */ + OFF(1), + /** + * Always flash. + * + * The flash will always be used when taking a picture. + */ + ON(2); + + companion object { + fun ofRaw(raw: Int): CameraXFlashMode? { + return values().firstOrNull { it.raw == raw } + } + } +} + +/** + * Fallback rule for choosing an alternate size when the specified bound size is unavailable. + * + * See + * https://developer.android.com/reference/kotlin/androidx/camera/core/resolutionselector/ResolutionStrategy. + */ +enum class ResolutionStrategyFallbackRule(val raw: Int) { + /** + * When the specified bound size is unavailable, CameraX falls back to the closest higher + * resolution size. + */ + CLOSEST_HIGHER(0), + /** + * When the specified bound size is unavailable, CameraX falls back to select the closest higher + * resolution size. + */ + CLOSEST_HIGHER_THEN_LOWER(1), + /** + * When the specified bound size is unavailable, CameraX falls back to the closest lower + * resolution size. + */ + CLOSEST_LOWER(2), + /** + * When the specified bound size is unavailable, CameraX falls back to select the closest lower + * resolution size. + * + * If CameraX still cannot find any available resolution, it will fallback to select other higher + * resolutions. + */ + CLOSEST_LOWER_THEN_HIGHER(3), + /** CameraX doesn't select an alternate size when the specified bound size is unavailable. */ + NONE(4), + /** The value is not recognized by the wrapper. */ + UNKNOWN(5); + + companion object { + fun ofRaw(raw: Int): ResolutionStrategyFallbackRule? { + return values().firstOrNull { it.raw == raw } + } + } +} + +/** + * Fallback rule for choosing the aspect ratio when the preferred aspect ratio is not available. + * + * See + * https://developer.android.com/reference/kotlin/androidx/camera/core/resolutionselector/AspectRatioStrategy#FALLBACK_RULE_AUTO(). + */ +enum class AspectRatioStrategyFallbackRule(val raw: Int) { + /** + * CameraX automatically chooses the next best aspect ratio which contains the closest field of + * view (FOV) of the camera sensor, from the remaining options. + */ + AUTO(0), + /** + * CameraX doesn't fall back to select sizes of any other aspect ratio when this fallback rule is + * used. + */ + NONE(1), + /** The value is not recognized by the wrapper. */ + UNKNOWN(2); + + companion object { + fun ofRaw(raw: Int): AspectRatioStrategyFallbackRule? { + return values().firstOrNull { it.raw == raw } + } + } +} + +/** + * Code for a `CameraState` error. + * + * https://developer.android.com/reference/androidx/camera/core/CameraState#ERROR_CAMERA_DISABLED() + */ +enum class CameraStateErrorCode(val raw: Int) { + /** An error indicating that the camera device could not be opened due to a device policy. */ + CAMERA_DISABLED(0), + /** An error indicating that the camera device was closed due to a fatal error. */ + CAMERA_FATAL_ERROR(1), + /** An error indicating that the camera device is already in use. */ + CAMERA_IN_USE(2), + /** + * An error indicating that the camera could not be opened because "Do Not Disturb" mode is + * enabled on devices affected by a bug in Android 9 (API level 28). + */ + DO_NOT_DISTURB_MODE_ENABLED(3), + /** + * An error indicating that the limit number of open cameras has been reached, and more cameras + * cannot be opened until other instances are closed. + */ + MAX_CAMERAS_IN_USE(4), + /** An error indicating that the camera device has encountered a recoverable error. */ + OTHER_RECOVERABLE_ERROR(5), + /** An error indicating that configuring the camera has failed. */ + STREAM_CONFIG(6), + /** The value is not recognized by this wrapper. */ + UNKNOWN(7); + + companion object { + fun ofRaw(raw: Int): CameraStateErrorCode? { + return values().firstOrNull { it.raw == raw } + } + } +} + +private open class CameraXLibraryPigeonCodec : StandardMessageCodec() { + override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { + return when (type) { + 129.toByte() -> { + return (readValue(buffer) as Long?)?.let { InfoSupportedHardwareLevel.ofRaw(it.toInt()) } + } + 130.toByte() -> { + return (readValue(buffer) as Long?)?.let { AspectRatio.ofRaw(it.toInt()) } + } + 131.toByte() -> { + return (readValue(buffer) as Long?)?.let { CameraStateType.ofRaw(it.toInt()) } + } + 132.toByte() -> { + return (readValue(buffer) as Long?)?.let { LiveDataSupportedType.ofRaw(it.toInt()) } + } + 133.toByte() -> { + return (readValue(buffer) as Long?)?.let { VideoQuality.ofRaw(it.toInt()) } + } + 134.toByte() -> { + return (readValue(buffer) as Long?)?.let { MeteringMode.ofRaw(it.toInt()) } + } + 135.toByte() -> { + return (readValue(buffer) as Long?)?.let { LensFacing.ofRaw(it.toInt()) } + } + 136.toByte() -> { + return (readValue(buffer) as Long?)?.let { CameraXFlashMode.ofRaw(it.toInt()) } + } + 137.toByte() -> { + return (readValue(buffer) as Long?)?.let { + ResolutionStrategyFallbackRule.ofRaw(it.toInt()) + } + } + 138.toByte() -> { + return (readValue(buffer) as Long?)?.let { + AspectRatioStrategyFallbackRule.ofRaw(it.toInt()) + } + } + 139.toByte() -> { + return (readValue(buffer) as Long?)?.let { CameraStateErrorCode.ofRaw(it.toInt()) } + } + else -> super.readValueOfType(type, buffer) + } + } + + override fun writeValue(stream: ByteArrayOutputStream, value: Any?) { + when (value) { + is InfoSupportedHardwareLevel -> { + stream.write(129) + writeValue(stream, value.raw) + } + is AspectRatio -> { + stream.write(130) + writeValue(stream, value.raw) + } + is CameraStateType -> { + stream.write(131) + writeValue(stream, value.raw) + } + is LiveDataSupportedType -> { + stream.write(132) + writeValue(stream, value.raw) + } + is VideoQuality -> { + stream.write(133) + writeValue(stream, value.raw) + } + is MeteringMode -> { + stream.write(134) + writeValue(stream, value.raw) + } + is LensFacing -> { + stream.write(135) + writeValue(stream, value.raw) + } + is CameraXFlashMode -> { + stream.write(136) + writeValue(stream, value.raw) + } + is ResolutionStrategyFallbackRule -> { + stream.write(137) + writeValue(stream, value.raw) + } + is AspectRatioStrategyFallbackRule -> { + stream.write(138) + writeValue(stream, value.raw) + } + is CameraStateErrorCode -> { + stream.write(139) + writeValue(stream, value.raw) + } + else -> super.writeValue(stream, value) + } + } +} + +/** + * Immutable class for describing width and height dimensions in pixels. + * + * See https://developer.android.com/reference/android/util/Size.html. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiCameraSize( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + abstract fun pigeon_defaultConstructor(width: Long, height: Long): android.util.Size + + /** The width of the size (in pixels). */ + abstract fun width(pigeon_instance: android.util.Size): Long + + /** The height of the size (in pixels). */ + abstract fun height(pigeon_instance: android.util.Size): Long + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiCameraSize?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.CameraSize.pigeon_defaultConstructor", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val widthArg = args[1] as Long + val heightArg = args[2] as Long + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.pigeon_defaultConstructor(widthArg, heightArg), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of CameraSize and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance(pigeon_instanceArg: android.util.Size, callback: (Result) -> Unit) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val widthArg = width(pigeon_instanceArg) + val heightArg = height(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.camera_android_camerax.CameraSize.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, widthArg, heightArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * A `ResolutionInfo` allows the application to know the resolution information of a specific use + * case. + * + * See https://developer.android.com/reference/androidx/camera/core/ResolutionInfo. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiResolutionInfo( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** Returns the output resolution used for the use case. */ + abstract fun resolution(pigeon_instance: androidx.camera.core.ResolutionInfo): android.util.Size + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of ResolutionInfo and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.ResolutionInfo, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val resolutionArg = resolution(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.ResolutionInfo.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, resolutionArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * Immutable class for describing the range of two integer values. + * + * This is the equivalent to `android.util.Range`. + * + * See https://developer.android.com/reference/android/util/Range.html. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiCameraIntegerRange( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + abstract fun pigeon_defaultConstructor(lower: Long, upper: Long): android.util.Range<*> + + /** The lower endpoint. */ + abstract fun lower(pigeon_instance: android.util.Range<*>): Long + + /** The upper endpoint. */ + abstract fun upper(pigeon_instance: android.util.Range<*>): Long + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiCameraIntegerRange?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.CameraIntegerRange.pigeon_defaultConstructor", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val lowerArg = args[1] as Long + val upperArg = args[2] as Long + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.pigeon_defaultConstructor(lowerArg, upperArg), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of CameraIntegerRange and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: android.util.Range<*>, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val lowerArg = lower(pigeon_instanceArg) + val upperArg = upper(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.CameraIntegerRange.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, lowerArg, upperArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * VideoRecordEvent is used to report video recording events and status. + * + * See https://developer.android.com/reference/androidx/camera/video/VideoRecordEvent. + */ +@Suppress("UNCHECKED_CAST") +open class PigeonApiVideoRecordEvent( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of VideoRecordEvent and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.video.VideoRecordEvent, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.VideoRecordEvent.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * Indicates the start of recording. + * + * See https://developer.android.com/reference/androidx/camera/video/VideoRecordEvent.Start. + */ +@Suppress("UNCHECKED_CAST") +open class PigeonApiVideoRecordEventStart( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of VideoRecordEventStart and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.video.VideoRecordEvent.Start, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.VideoRecordEventStart.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } + + @Suppress("FunctionName") + /** An implementation of [PigeonApiVideoRecordEvent] used to access callback methods */ + fun pigeon_getPigeonApiVideoRecordEvent(): PigeonApiVideoRecordEvent { + return pigeonRegistrar.getPigeonApiVideoRecordEvent() + } +} +/** + * Indicates the finalization of recording. + * + * See https://developer.android.com/reference/androidx/camera/video/VideoRecordEvent.Finalize. + */ +@Suppress("UNCHECKED_CAST") +open class PigeonApiVideoRecordEventFinalize( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + @Suppress("LocalVariableName", "FunctionName") + /** + * Creates a Dart instance of VideoRecordEventFinalize and attaches it to [pigeon_instanceArg]. + */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.video.VideoRecordEvent.Finalize, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.VideoRecordEventFinalize.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } + + @Suppress("FunctionName") + /** An implementation of [PigeonApiVideoRecordEvent] used to access callback methods */ + fun pigeon_getPigeonApiVideoRecordEvent(): PigeonApiVideoRecordEvent { + return pigeonRegistrar.getPigeonApiVideoRecordEvent() + } +} +/** + * A MeteringPoint is used to specify a region which can then be converted to sensor coordinate + * system for focus and metering purpose. + * + * See https://developer.android.com/reference/androidx/camera/core/MeteringPoint. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiMeteringPoint( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** + * Size of the MeteringPoint width and height (ranging from 0 to 1). + * + * It is the percentage of the sensor width/height (or crop region width/height if crop region is + * set). + */ + abstract fun getSize(pigeon_instance: androidx.camera.core.MeteringPoint): Double + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiMeteringPoint?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.MeteringPoint.getSize", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.MeteringPoint + val wrapped: List = + try { + listOf(api.getSize(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of MeteringPoint and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.MeteringPoint, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.camera_android_camerax.MeteringPoint.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * A simple callback that can receive from LiveData. + * + * See https://developer.android.com/reference/androidx/lifecycle/Observer. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiObserver(open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar) { + abstract fun pigeon_defaultConstructor(): androidx.lifecycle.Observer<*> + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiObserver?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.Observer.pigeon_defaultConstructor", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.pigeon_defaultConstructor(), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of Observer and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.lifecycle.Observer<*>, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + callback( + Result.failure( + CameraXError( + "new-instance-error", + "Attempting to create a new Dart instance of Observer, but the class has a nonnull callback method.", + ""))) + } + } + + /** Called when the data is changed to value. */ + fun onChanged( + pigeon_instanceArg: androidx.lifecycle.Observer<*>, + valueArg: Any, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + return + } + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.camera_android_camerax.Observer.onChanged" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_instanceArg, valueArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback(Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } +} +/** + * An interface for retrieving camera information. + * + * See https://developer.android.com/reference/androidx/camera/core/CameraInfo. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiCameraInfo( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** + * Returns the sensor rotation in degrees, relative to the device's "natural" (default) + * orientation. + */ + abstract fun sensorRotationDegrees(pigeon_instance: androidx.camera.core.CameraInfo): Long + + /** Returns a ExposureState. */ + abstract fun exposureState( + pigeon_instance: androidx.camera.core.CameraInfo + ): androidx.camera.core.ExposureState + + /** A LiveData of the camera's state. */ + abstract fun getCameraState( + pigeon_instance: androidx.camera.core.CameraInfo + ): io.flutter.plugins.camerax.LiveDataProxyApi.LiveDataWrapper + + /** A LiveData of ZoomState. */ + abstract fun getZoomState( + pigeon_instance: androidx.camera.core.CameraInfo + ): io.flutter.plugins.camerax.LiveDataProxyApi.LiveDataWrapper + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiCameraInfo?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.CameraInfo.getCameraState", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.CameraInfo + val wrapped: List = + try { + listOf(api.getCameraState(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.CameraInfo.getZoomState", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.CameraInfo + val wrapped: List = + try { + listOf(api.getZoomState(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of CameraInfo and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.CameraInfo, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val sensorRotationDegreesArg = sensorRotationDegrees(pigeon_instanceArg) + val exposureStateArg = exposureState(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.camera_android_camerax.CameraInfo.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, sensorRotationDegreesArg, exposureStateArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * A set of requirements and priorities used to select a camera or return a filtered set of cameras. + * + * See https://developer.android.com/reference/androidx/camera/core/CameraSelector. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiCameraSelector( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + abstract fun pigeon_defaultConstructor( + requireLensFacing: LensFacing? + ): androidx.camera.core.CameraSelector + + /** A static `CameraSelector` that selects the default back facing camera. */ + abstract fun defaultBackCamera(): androidx.camera.core.CameraSelector + + /** A static `CameraSelector` that selects the default front facing camera. */ + abstract fun defaultFrontCamera(): androidx.camera.core.CameraSelector + + /** Filters the input `CameraInfo`s using the `CameraFilter`s assigned to the selector. */ + abstract fun filter( + pigeon_instance: androidx.camera.core.CameraSelector, + cameraInfos: List + ): List + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiCameraSelector?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.CameraSelector.pigeon_defaultConstructor", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val requireLensFacingArg = args[1] as LensFacing? + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.pigeon_defaultConstructor(requireLensFacingArg), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.CameraSelector.defaultBackCamera", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.defaultBackCamera(), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.CameraSelector.defaultFrontCamera", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.defaultFrontCamera(), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.CameraSelector.filter", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.CameraSelector + val cameraInfosArg = args[1] as List + val wrapped: List = + try { + listOf(api.filter(pigeon_instanceArg, cameraInfosArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of CameraSelector and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.CameraSelector, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.CameraSelector.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * A singleton which can be used to bind the lifecycle of cameras to any `LifecycleOwner` within an + * application's process. + * + * See https://developer.android.com/reference/androidx/camera/lifecycle/ProcessCameraProvider. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiProcessCameraProvider( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** Retrieves the ProcessCameraProvider associated with the current process. */ + abstract fun getInstance( + callback: (Result) -> Unit + ) + + /** The `CameraInfo` instances of the available cameras. */ + abstract fun getAvailableCameraInfos( + pigeon_instance: androidx.camera.lifecycle.ProcessCameraProvider + ): List + + /** Binds the collection of `UseCase` to a `LifecycleOwner`. */ + abstract fun bindToLifecycle( + pigeon_instance: androidx.camera.lifecycle.ProcessCameraProvider, + cameraSelector: androidx.camera.core.CameraSelector, + useCases: List + ): androidx.camera.core.Camera + + /** Returns true if the `UseCase` is bound to a lifecycle. */ + abstract fun isBound( + pigeon_instance: androidx.camera.lifecycle.ProcessCameraProvider, + useCase: androidx.camera.core.UseCase + ): Boolean + + /** Unbinds all specified use cases from the lifecycle provider. */ + abstract fun unbind( + pigeon_instance: androidx.camera.lifecycle.ProcessCameraProvider, + useCases: List + ) + + /** Unbinds all use cases from the lifecycle provider and removes them from CameraX. */ + abstract fun unbindAll(pigeon_instance: androidx.camera.lifecycle.ProcessCameraProvider) + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers( + binaryMessenger: BinaryMessenger, + api: PigeonApiProcessCameraProvider? + ) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.getInstance", + codec) + if (api != null) { + channel.setMessageHandler { _, reply -> + api.getInstance { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.getAvailableCameraInfos", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.lifecycle.ProcessCameraProvider + val wrapped: List = + try { + listOf(api.getAvailableCameraInfos(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.bindToLifecycle", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.lifecycle.ProcessCameraProvider + val cameraSelectorArg = args[1] as androidx.camera.core.CameraSelector + val useCasesArg = args[2] as List + val wrapped: List = + try { + listOf(api.bindToLifecycle(pigeon_instanceArg, cameraSelectorArg, useCasesArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.isBound", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.lifecycle.ProcessCameraProvider + val useCaseArg = args[1] as androidx.camera.core.UseCase + val wrapped: List = + try { + listOf(api.isBound(pigeon_instanceArg, useCaseArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.unbind", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.lifecycle.ProcessCameraProvider + val useCasesArg = args[1] as List + val wrapped: List = + try { + api.unbind(pigeon_instanceArg, useCasesArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.unbindAll", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.lifecycle.ProcessCameraProvider + val wrapped: List = + try { + api.unbindAll(pigeon_instanceArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of ProcessCameraProvider and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.lifecycle.ProcessCameraProvider, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * The use case which all other use cases are built on top of. + * + * See https://developer.android.com/reference/kotlin/androidx/camera/core/UseCase. + */ +@Suppress("UNCHECKED_CAST") +open class PigeonApiUseCase(open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar) { + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of UseCase and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.UseCase, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.camera_android_camerax.UseCase.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * The camera interface is used to control the flow of data to use cases, control the camera via the + * `CameraControl`, and publish the state of the camera via CameraInfo. + * + * See https://developer.android.com/reference/kotlin/androidx/camera/core/Camera. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiCamera(open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar) { + /** The `CameraControl` for the Camera. */ + abstract fun cameraControl( + pigeon_instance: androidx.camera.core.Camera + ): androidx.camera.core.CameraControl + + /** Returns information about this camera. */ + abstract fun getCameraInfo( + pigeon_instance: androidx.camera.core.Camera + ): androidx.camera.core.CameraInfo + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiCamera?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.Camera.getCameraInfo", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.Camera + val wrapped: List = + try { + listOf(api.getCameraInfo(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of Camera and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.Camera, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val cameraControlArg = cameraControl(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.camera_android_camerax.Camera.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, cameraControlArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** Convenience class for accessing system resources. */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiSystemServicesManager( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + abstract fun pigeon_defaultConstructor(): SystemServicesManager + + abstract fun requestCameraPermissions( + pigeon_instance: SystemServicesManager, + enableAudio: Boolean, + callback: (Result) -> Unit + ) + + /** Returns a path to be used to create a temp file in the current cache directory. */ + abstract fun getTempFilePath( + pigeon_instance: SystemServicesManager, + prefix: String, + suffix: String + ): String + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers( + binaryMessenger: BinaryMessenger, + api: PigeonApiSystemServicesManager? + ) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.SystemServicesManager.pigeon_defaultConstructor", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.pigeon_defaultConstructor(), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.SystemServicesManager.requestCameraPermissions", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as SystemServicesManager + val enableAudioArg = args[1] as Boolean + api.requestCameraPermissions(pigeon_instanceArg, enableAudioArg) { + result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.SystemServicesManager.getTempFilePath", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as SystemServicesManager + val prefixArg = args[1] as String + val suffixArg = args[2] as String + val wrapped: List = + try { + listOf(api.getTempFilePath(pigeon_instanceArg, prefixArg, suffixArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of SystemServicesManager and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: SystemServicesManager, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + callback( + Result.failure( + CameraXError( + "new-instance-error", + "Attempting to create a new Dart instance of SystemServicesManager, but the class has a nonnull callback method.", + ""))) + } + } + + fun onCameraError( + pigeon_instanceArg: SystemServicesManager, + errorDescriptionArg: String, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + return + } + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.SystemServicesManager.onCameraError" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_instanceArg, errorDescriptionArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback(Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } +} +/** Contains data when an attempt to retrieve camera permissions fails. */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiCameraPermissionsError( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + abstract fun errorCode(pigeon_instance: CameraPermissionsError): String + + abstract fun description(pigeon_instance: CameraPermissionsError): String + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of CameraPermissionsError and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: CameraPermissionsError, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val errorCodeArg = errorCode(pigeon_instanceArg) + val descriptionArg = description(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.CameraPermissionsError.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, errorCodeArg, descriptionArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * Support class to help to determine the media orientation based on the orientation of the device. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiDeviceOrientationManager( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + abstract fun pigeon_defaultConstructor(): DeviceOrientationManager + + abstract fun startListeningForDeviceOrientationChange(pigeon_instance: DeviceOrientationManager) + + abstract fun stopListeningForDeviceOrientationChange(pigeon_instance: DeviceOrientationManager) + + abstract fun getDefaultDisplayRotation(pigeon_instance: DeviceOrientationManager): Long + + abstract fun getUiOrientation(pigeon_instance: DeviceOrientationManager): String + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers( + binaryMessenger: BinaryMessenger, + api: PigeonApiDeviceOrientationManager? + ) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.pigeon_defaultConstructor", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.pigeon_defaultConstructor(), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.startListeningForDeviceOrientationChange", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as DeviceOrientationManager + val wrapped: List = + try { + api.startListeningForDeviceOrientationChange(pigeon_instanceArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.stopListeningForDeviceOrientationChange", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as DeviceOrientationManager + val wrapped: List = + try { + api.stopListeningForDeviceOrientationChange(pigeon_instanceArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.getDefaultDisplayRotation", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as DeviceOrientationManager + val wrapped: List = + try { + listOf(api.getDefaultDisplayRotation(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.getUiOrientation", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as DeviceOrientationManager + val wrapped: List = + try { + listOf(api.getUiOrientation(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** + * Creates a Dart instance of DeviceOrientationManager and attaches it to [pigeon_instanceArg]. + */ + fun pigeon_newInstance( + pigeon_instanceArg: DeviceOrientationManager, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + callback( + Result.failure( + CameraXError( + "new-instance-error", + "Attempting to create a new Dart instance of DeviceOrientationManager, but the class has a nonnull callback method.", + ""))) + } + } + + fun onDeviceOrientationChanged( + pigeon_instanceArg: DeviceOrientationManager, + orientationArg: String, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + return + } + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.onDeviceOrientationChanged" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_instanceArg, orientationArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback(Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } +} +/** + * A use case that provides a camera preview stream for displaying on-screen. + * + * See https://developer.android.com/reference/kotlin/androidx/camera/core/Preview. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiPreview(open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar) { + abstract fun pigeon_defaultConstructor( + resolutionSelector: androidx.camera.core.resolutionselector.ResolutionSelector?, + targetRotation: Long? + ): androidx.camera.core.Preview + + abstract fun resolutionSelector( + pigeon_instance: androidx.camera.core.Preview + ): androidx.camera.core.resolutionselector.ResolutionSelector? + + /** + * Sets a SurfaceProvider to provide a Surface for Preview. + * + * This is a convenience function that + * 1. Creates a `SurfaceProvider` using the `SurfaceProducer` provided by the Flutter engine. + * 2. Sets this method with the created `SurfaceProvider`. + * 3. Returns the texture id of the `TextureEntry` that provided the `SurfaceProducer`. + */ + abstract fun setSurfaceProvider( + pigeon_instance: androidx.camera.core.Preview, + systemServicesManager: SystemServicesManager + ): Long + + /** Releases the `SurfaceProducer` created in `setSurfaceProvider` if one was created. */ + abstract fun releaseSurfaceProvider(pigeon_instance: androidx.camera.core.Preview) + + /** Gets selected resolution information of the `Preview`. */ + abstract fun getResolutionInfo( + pigeon_instance: androidx.camera.core.Preview + ): androidx.camera.core.ResolutionInfo? + + /** Sets the target rotation. */ + abstract fun setTargetRotation(pigeon_instance: androidx.camera.core.Preview, rotation: Long) + + /** + * Returns whether or not the preview's surface producer handles correctly rotating the camera + * preview automatically. + */ + abstract fun surfaceProducerHandlesCropAndRotation( + pigeon_instance: androidx.camera.core.Preview + ): Boolean + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiPreview?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.Preview.pigeon_defaultConstructor", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val resolutionSelectorArg = + args[1] as androidx.camera.core.resolutionselector.ResolutionSelector? + val targetRotationArg = args[2] as Long? + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.pigeon_defaultConstructor(resolutionSelectorArg, targetRotationArg), + pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.Preview.setSurfaceProvider", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.Preview + val systemServicesManagerArg = args[1] as SystemServicesManager + val wrapped: List = + try { + listOf(api.setSurfaceProvider(pigeon_instanceArg, systemServicesManagerArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.Preview.releaseSurfaceProvider", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.Preview + val wrapped: List = + try { + api.releaseSurfaceProvider(pigeon_instanceArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.Preview.getResolutionInfo", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.Preview + val wrapped: List = + try { + listOf(api.getResolutionInfo(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.Preview.setTargetRotation", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.Preview + val rotationArg = args[1] as Long + val wrapped: List = + try { + api.setTargetRotation(pigeon_instanceArg, rotationArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.Preview.surfaceProducerHandlesCropAndRotation", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.Preview + val wrapped: List = + try { + listOf(api.surfaceProducerHandlesCropAndRotation(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of Preview and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.Preview, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val resolutionSelectorArg = resolutionSelector(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.camera_android_camerax.Preview.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, resolutionSelectorArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } + + @Suppress("FunctionName") + /** An implementation of [PigeonApiUseCase] used to access callback methods */ + fun pigeon_getPigeonApiUseCase(): PigeonApiUseCase { + return pigeonRegistrar.getPigeonApiUseCase() + } +} +/** + * A use case that provides camera stream suitable for video application. + * + * See https://developer.android.com/reference/kotlin/androidx/camera/video/VideoCapture. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiVideoCapture( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** Create a `VideoCapture` associated with the given `VideoOutput`. */ + abstract fun withOutput( + videoOutput: androidx.camera.video.VideoOutput + ): androidx.camera.video.VideoCapture<*> + + /** Gets the VideoOutput associated with this VideoCapture. */ + abstract fun getOutput( + pigeon_instance: androidx.camera.video.VideoCapture<*> + ): androidx.camera.video.VideoOutput + + /** Sets the desired rotation of the output video. */ + abstract fun setTargetRotation( + pigeon_instance: androidx.camera.video.VideoCapture<*>, + rotation: Long + ) + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiVideoCapture?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.VideoCapture.withOutput", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val videoOutputArg = args[1] as androidx.camera.video.VideoOutput + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.withOutput(videoOutputArg), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.VideoCapture.getOutput", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.video.VideoCapture<*> + val wrapped: List = + try { + listOf(api.getOutput(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.VideoCapture.setTargetRotation", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.video.VideoCapture<*> + val rotationArg = args[1] as Long + val wrapped: List = + try { + api.setTargetRotation(pigeon_instanceArg, rotationArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of VideoCapture and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.video.VideoCapture<*>, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.camera_android_camerax.VideoCapture.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } + + @Suppress("FunctionName") + /** An implementation of [PigeonApiUseCase] used to access callback methods */ + fun pigeon_getPigeonApiUseCase(): PigeonApiUseCase { + return pigeonRegistrar.getPigeonApiUseCase() + } +} +/** + * A class that will produce video data from a Surface. + * + * See https://developer.android.com/reference/kotlin/androidx/camera/video/VideoOutput. + */ +@Suppress("UNCHECKED_CAST") +open class PigeonApiVideoOutput(open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar) { + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of VideoOutput and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.video.VideoOutput, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.camera_android_camerax.VideoOutput.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * An implementation of `VideoOutput` for starting video recordings that are saved to a File, + * ParcelFileDescriptor, or MediaStore. + * + * See https://developer.android.com/reference/kotlin/androidx/camera/video/Recorder. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiRecorder(open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar) { + abstract fun pigeon_defaultConstructor( + aspectRatio: Long?, + targetVideoEncodingBitRate: Long?, + qualitySelector: androidx.camera.video.QualitySelector? + ): androidx.camera.video.Recorder + + /** Gets the aspect ratio of this Recorder. */ + abstract fun getAspectRatio(pigeon_instance: androidx.camera.video.Recorder): Long + + /** Gets the target video encoding bitrate of this Recorder. */ + abstract fun getTargetVideoEncodingBitRate(pigeon_instance: androidx.camera.video.Recorder): Long + + /** The quality selector of this Recorder. */ + abstract fun getQualitySelector( + pigeon_instance: androidx.camera.video.Recorder + ): androidx.camera.video.QualitySelector + + /** Prepares a recording that will be saved to a File. */ + abstract fun prepareRecording( + pigeon_instance: androidx.camera.video.Recorder, + path: String + ): androidx.camera.video.PendingRecording + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiRecorder?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.Recorder.pigeon_defaultConstructor", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val aspectRatioArg = args[1] as Long? + val targetVideoEncodingBitRateArg = args[2] as Long? + val qualitySelectorArg = args[3] as androidx.camera.video.QualitySelector? + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.pigeon_defaultConstructor( + aspectRatioArg, targetVideoEncodingBitRateArg, qualitySelectorArg), + pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.Recorder.getAspectRatio", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.video.Recorder + val wrapped: List = + try { + listOf(api.getAspectRatio(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.Recorder.getTargetVideoEncodingBitRate", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.video.Recorder + val wrapped: List = + try { + listOf(api.getTargetVideoEncodingBitRate(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.Recorder.getQualitySelector", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.video.Recorder + val wrapped: List = + try { + listOf(api.getQualitySelector(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.Recorder.prepareRecording", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.video.Recorder + val pathArg = args[1] as String + val wrapped: List = + try { + listOf(api.prepareRecording(pigeon_instanceArg, pathArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of Recorder and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.video.Recorder, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.camera_android_camerax.Recorder.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } + + @Suppress("FunctionName") + /** An implementation of [PigeonApiVideoOutput] used to access callback methods */ + fun pigeon_getPigeonApiVideoOutput(): PigeonApiVideoOutput { + return pigeonRegistrar.getPigeonApiVideoOutput() + } +} +/** Listens for `VideoRecordEvent`s from a `PendingRecording`. */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiVideoRecordEventListener( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + abstract fun pigeon_defaultConstructor(): VideoRecordEventListener + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers( + binaryMessenger: BinaryMessenger, + api: PigeonApiVideoRecordEventListener? + ) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.VideoRecordEventListener.pigeon_defaultConstructor", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.pigeon_defaultConstructor(), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** + * Creates a Dart instance of VideoRecordEventListener and attaches it to [pigeon_instanceArg]. + */ + fun pigeon_newInstance( + pigeon_instanceArg: VideoRecordEventListener, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + callback( + Result.failure( + CameraXError( + "new-instance-error", + "Attempting to create a new Dart instance of VideoRecordEventListener, but the class has a nonnull callback method.", + ""))) + } + } + + fun onEvent( + pigeon_instanceArg: VideoRecordEventListener, + eventArg: androidx.camera.video.VideoRecordEvent, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + return + } + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.camera_android_camerax.VideoRecordEventListener.onEvent" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_instanceArg, eventArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback(Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } +} +/** + * A recording that can be started at a future time. + * + * See https://developer.android.com/reference/kotlin/androidx/camera/video/PendingRecording. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiPendingRecording( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** Starts the recording, making it an active recording. */ + abstract fun start( + pigeon_instance: androidx.camera.video.PendingRecording, + listener: VideoRecordEventListener + ): androidx.camera.video.Recording + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiPendingRecording?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.PendingRecording.start", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.video.PendingRecording + val listenerArg = args[1] as VideoRecordEventListener + val wrapped: List = + try { + listOf(api.start(pigeon_instanceArg, listenerArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of PendingRecording and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.video.PendingRecording, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.PendingRecording.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * Provides controls for the currently active recording. + * + * See https://developer.android.com/reference/kotlin/androidx/camera/video/Recording. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiRecording(open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar) { + /** Close this recording. */ + abstract fun close(pigeon_instance: androidx.camera.video.Recording) + + /** Pauses the current recording if active. */ + abstract fun pause(pigeon_instance: androidx.camera.video.Recording) + + /** Resumes the current recording if paused. */ + abstract fun resume(pigeon_instance: androidx.camera.video.Recording) + + /** + * Stops the recording, as if calling `close`. + * + * This method is equivalent to calling `close`. + */ + abstract fun stop(pigeon_instance: androidx.camera.video.Recording) + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiRecording?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, "dev.flutter.pigeon.camera_android_camerax.Recording.close", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.video.Recording + val wrapped: List = + try { + api.close(pigeon_instanceArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, "dev.flutter.pigeon.camera_android_camerax.Recording.pause", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.video.Recording + val wrapped: List = + try { + api.pause(pigeon_instanceArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.Recording.resume", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.video.Recording + val wrapped: List = + try { + api.resume(pigeon_instanceArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, "dev.flutter.pigeon.camera_android_camerax.Recording.stop", codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.video.Recording + val wrapped: List = + try { + api.stop(pigeon_instanceArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of Recording and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.video.Recording, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.camera_android_camerax.Recording.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * A use case for taking a picture. + * + * See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageCapture. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiImageCapture( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + abstract fun pigeon_defaultConstructor( + resolutionSelector: androidx.camera.core.resolutionselector.ResolutionSelector?, + targetRotation: Long?, + flashMode: CameraXFlashMode? + ): androidx.camera.core.ImageCapture + + abstract fun resolutionSelector( + pigeon_instance: androidx.camera.core.ImageCapture + ): androidx.camera.core.resolutionselector.ResolutionSelector? + + /** Set the flash mode. */ + abstract fun setFlashMode( + pigeon_instance: androidx.camera.core.ImageCapture, + flashMode: CameraXFlashMode + ) + + /** Captures a new still image for in memory access. */ + abstract fun takePicture( + pigeon_instance: androidx.camera.core.ImageCapture, + callback: (Result) -> Unit + ) + + /** Sets the desired rotation of the output image. */ + abstract fun setTargetRotation(pigeon_instance: androidx.camera.core.ImageCapture, rotation: Long) + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiImageCapture?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ImageCapture.pigeon_defaultConstructor", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val resolutionSelectorArg = + args[1] as androidx.camera.core.resolutionselector.ResolutionSelector? + val targetRotationArg = args[2] as Long? + val flashModeArg = args[3] as CameraXFlashMode? + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.pigeon_defaultConstructor( + resolutionSelectorArg, targetRotationArg, flashModeArg), + pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ImageCapture.setFlashMode", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.ImageCapture + val flashModeArg = args[1] as CameraXFlashMode + val wrapped: List = + try { + api.setFlashMode(pigeon_instanceArg, flashModeArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ImageCapture.takePicture", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.ImageCapture + api.takePicture(pigeon_instanceArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ImageCapture.setTargetRotation", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.ImageCapture + val rotationArg = args[1] as Long + val wrapped: List = + try { + api.setTargetRotation(pigeon_instanceArg, rotationArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of ImageCapture and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.ImageCapture, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val resolutionSelectorArg = resolutionSelector(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.camera_android_camerax.ImageCapture.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, resolutionSelectorArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } + + @Suppress("FunctionName") + /** An implementation of [PigeonApiUseCase] used to access callback methods */ + fun pigeon_getPigeonApiUseCase(): PigeonApiUseCase { + return pigeonRegistrar.getPigeonApiUseCase() + } +} +/** + * The resolution strategy defines the resolution selection sequence to select the best size. + * + * See + * https://developer.android.com/reference/kotlin/androidx/camera/core/resolutionselector/ResolutionStrategy. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiResolutionStrategy( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + abstract fun pigeon_defaultConstructor( + boundSize: android.util.Size, + fallbackRule: ResolutionStrategyFallbackRule + ): androidx.camera.core.resolutionselector.ResolutionStrategy + + /** A resolution strategy chooses the highest available resolution. */ + abstract fun highestAvailableStrategy(): + androidx.camera.core.resolutionselector.ResolutionStrategy + + /** The specified bound size. */ + abstract fun getBoundSize( + pigeon_instance: androidx.camera.core.resolutionselector.ResolutionStrategy + ): android.util.Size? + + /** + * The fallback rule for choosing an alternate size when the specified bound size is unavailable. + */ + abstract fun getFallbackRule( + pigeon_instance: androidx.camera.core.resolutionselector.ResolutionStrategy + ): ResolutionStrategyFallbackRule + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiResolutionStrategy?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.pigeon_defaultConstructor", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val boundSizeArg = args[1] as android.util.Size + val fallbackRuleArg = args[2] as ResolutionStrategyFallbackRule + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.pigeon_defaultConstructor(boundSizeArg, fallbackRuleArg), + pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.highestAvailableStrategy", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.highestAvailableStrategy(), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.getBoundSize", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = + args[0] as androidx.camera.core.resolutionselector.ResolutionStrategy + val wrapped: List = + try { + listOf(api.getBoundSize(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.getFallbackRule", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = + args[0] as androidx.camera.core.resolutionselector.ResolutionStrategy + val wrapped: List = + try { + listOf(api.getFallbackRule(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of ResolutionStrategy and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.resolutionselector.ResolutionStrategy, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * A set of requirements and priorities used to select a resolution for the `UseCase`. + * + * See + * https://developer.android.com/reference/kotlin/androidx/camera/core/resolutionselector/ResolutionSelector. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiResolutionSelector( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + abstract fun pigeon_defaultConstructor( + resolutionFilter: androidx.camera.core.resolutionselector.ResolutionFilter?, + resolutionStrategy: androidx.camera.core.resolutionselector.ResolutionStrategy?, + aspectRatioStrategy: androidx.camera.core.resolutionselector.AspectRatioStrategy? + ): androidx.camera.core.resolutionselector.ResolutionSelector + + /** The resolution filter to output the final desired sizes list. */ + abstract fun resolutionFilter( + pigeon_instance: androidx.camera.core.resolutionselector.ResolutionSelector + ): androidx.camera.core.resolutionselector.ResolutionFilter? + + /** The resolution selection strategy for the `UseCase`. */ + abstract fun resolutionStrategy( + pigeon_instance: androidx.camera.core.resolutionselector.ResolutionSelector + ): androidx.camera.core.resolutionselector.ResolutionStrategy? + + /** + * Returns the specified `AspectRatioStrategy`, or + * `AspectRatioStrategy.ratio_4_3FallbackAutoStrategy` if none is specified when creating the + * ResolutionSelector. + */ + abstract fun getAspectRatioStrategy( + pigeon_instance: androidx.camera.core.resolutionselector.ResolutionSelector + ): androidx.camera.core.resolutionselector.AspectRatioStrategy + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiResolutionSelector?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ResolutionSelector.pigeon_defaultConstructor", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val resolutionFilterArg = + args[1] as androidx.camera.core.resolutionselector.ResolutionFilter? + val resolutionStrategyArg = + args[2] as androidx.camera.core.resolutionselector.ResolutionStrategy? + val aspectRatioStrategyArg = + args[3] as androidx.camera.core.resolutionselector.AspectRatioStrategy? + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.pigeon_defaultConstructor( + resolutionFilterArg, resolutionStrategyArg, aspectRatioStrategyArg), + pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ResolutionSelector.getAspectRatioStrategy", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = + args[0] as androidx.camera.core.resolutionselector.ResolutionSelector + val wrapped: List = + try { + listOf(api.getAspectRatioStrategy(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of ResolutionSelector and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.resolutionselector.ResolutionSelector, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val resolutionFilterArg = resolutionFilter(pigeon_instanceArg) + val resolutionStrategyArg = resolutionStrategy(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.ResolutionSelector.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, resolutionFilterArg, resolutionStrategyArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * The aspect ratio strategy defines the sequence of aspect ratios that are used to select the best + * size for a particular image. + * + * See + * https://developer.android.com/reference/kotlin/androidx/camera/core/resolutionselector/AspectRatioStrategy. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiAspectRatioStrategy( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** + * Creates a new AspectRatioStrategy instance, configured with the specified preferred aspect + * ratio and fallback rule. + */ + abstract fun pigeon_defaultConstructor( + preferredAspectRatio: AspectRatio, + fallbackRule: AspectRatioStrategyFallbackRule + ): androidx.camera.core.resolutionselector.AspectRatioStrategy + + /** The pre-defined aspect ratio strategy that selects sizes with RATIO_16_9 in priority. */ + abstract fun ratio_16_9FallbackAutoStrategy(): + androidx.camera.core.resolutionselector.AspectRatioStrategy + + /** + * The pre-defined default aspect ratio strategy that selects sizes with RATIO_4_3 in priority. + */ + abstract fun ratio_4_3FallbackAutoStrategy(): + androidx.camera.core.resolutionselector.AspectRatioStrategy + + /** + * The specified fallback rule for choosing the aspect ratio when the preferred aspect ratio is + * not available. + */ + abstract fun getFallbackRule( + pigeon_instance: androidx.camera.core.resolutionselector.AspectRatioStrategy + ): AspectRatioStrategyFallbackRule + + /** The specified preferred aspect ratio. */ + abstract fun getPreferredAspectRatio( + pigeon_instance: androidx.camera.core.resolutionselector.AspectRatioStrategy + ): AspectRatio + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiAspectRatioStrategy?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.pigeon_defaultConstructor", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val preferredAspectRatioArg = args[1] as AspectRatio + val fallbackRuleArg = args[2] as AspectRatioStrategyFallbackRule + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.pigeon_defaultConstructor(preferredAspectRatioArg, fallbackRuleArg), + pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.ratio_16_9FallbackAutoStrategy", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.ratio_16_9FallbackAutoStrategy(), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.ratio_4_3FallbackAutoStrategy", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.ratio_4_3FallbackAutoStrategy(), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.getFallbackRule", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = + args[0] as androidx.camera.core.resolutionselector.AspectRatioStrategy + val wrapped: List = + try { + listOf(api.getFallbackRule(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.getPreferredAspectRatio", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = + args[0] as androidx.camera.core.resolutionselector.AspectRatioStrategy + val wrapped: List = + try { + listOf(api.getPreferredAspectRatio(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of AspectRatioStrategy and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.resolutionselector.AspectRatioStrategy, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * Represents the different states the camera can be in. + * + * See https://developer.android.com/reference/androidx/camera/core/CameraState. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiCameraState( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** The camera's state. */ + abstract fun type(pigeon_instance: androidx.camera.core.CameraState): CameraStateType + + /** Potentially returns an error the camera encountered. */ + abstract fun error( + pigeon_instance: androidx.camera.core.CameraState + ): androidx.camera.core.CameraState.StateError? + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of CameraState and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.CameraState, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val typeArg = type(pigeon_instanceArg) + val errorArg = error(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.camera_android_camerax.CameraState.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, typeArg, errorArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * An interface which contains the camera exposure related information. + * + * See https://developer.android.com/reference/androidx/camera/core/ExposureState. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiExposureState( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** + * Get the maximum and minimum exposure compensation values for + * `CameraControl.setExposureCompensationIndex`. + */ + abstract fun exposureCompensationRange( + pigeon_instance: androidx.camera.core.ExposureState + ): android.util.Range<*> + + /** Get the smallest step by which the exposure compensation can be changed. */ + abstract fun exposureCompensationStep(pigeon_instance: androidx.camera.core.ExposureState): Double + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of ExposureState and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.ExposureState, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val exposureCompensationRangeArg = exposureCompensationRange(pigeon_instanceArg) + val exposureCompensationStepArg = exposureCompensationStep(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.camera_android_camerax.ExposureState.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send( + listOf(pigeon_identifierArg, exposureCompensationRangeArg, exposureCompensationStepArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * An interface which contains the zoom related information from a camera. + * + * See https://developer.android.com/reference/androidx/camera/core/ZoomState. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiZoomState(open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar) { + /** The minimum zoom ratio. */ + abstract fun minZoomRatio(pigeon_instance: androidx.camera.core.ZoomState): Double + + /** The maximum zoom ratio. */ + abstract fun maxZoomRatio(pigeon_instance: androidx.camera.core.ZoomState): Double + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of ZoomState and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.ZoomState, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val minZoomRatioArg = minZoomRatio(pigeon_instanceArg) + val maxZoomRatioArg = maxZoomRatio(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.camera_android_camerax.ZoomState.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, minZoomRatioArg, maxZoomRatioArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * A use case providing CPU accessible images for an app to perform image analysis on. + * + * See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageAnalysis. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiImageAnalysis( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + abstract fun pigeon_defaultConstructor( + resolutionSelector: androidx.camera.core.resolutionselector.ResolutionSelector?, + targetRotation: Long? + ): androidx.camera.core.ImageAnalysis + + abstract fun resolutionSelector( + pigeon_instance: androidx.camera.core.ImageAnalysis + ): androidx.camera.core.resolutionselector.ResolutionSelector? + + /** Sets an analyzer to receive and analyze images. */ + abstract fun setAnalyzer( + pigeon_instance: androidx.camera.core.ImageAnalysis, + analyzer: androidx.camera.core.ImageAnalysis.Analyzer + ) + + /** Removes a previously set analyzer. */ + abstract fun clearAnalyzer(pigeon_instance: androidx.camera.core.ImageAnalysis) + + /** Sets the target rotation. */ + abstract fun setTargetRotation( + pigeon_instance: androidx.camera.core.ImageAnalysis, + rotation: Long + ) + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiImageAnalysis?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.pigeon_defaultConstructor", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val resolutionSelectorArg = + args[1] as androidx.camera.core.resolutionselector.ResolutionSelector? + val targetRotationArg = args[2] as Long? + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.pigeon_defaultConstructor(resolutionSelectorArg, targetRotationArg), + pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.setAnalyzer", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.ImageAnalysis + val analyzerArg = args[1] as androidx.camera.core.ImageAnalysis.Analyzer + val wrapped: List = + try { + api.setAnalyzer(pigeon_instanceArg, analyzerArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.clearAnalyzer", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.ImageAnalysis + val wrapped: List = + try { + api.clearAnalyzer(pigeon_instanceArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.setTargetRotation", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.ImageAnalysis + val rotationArg = args[1] as Long + val wrapped: List = + try { + api.setTargetRotation(pigeon_instanceArg, rotationArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of ImageAnalysis and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.ImageAnalysis, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val resolutionSelectorArg = resolutionSelector(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, resolutionSelectorArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } + + @Suppress("FunctionName") + /** An implementation of [PigeonApiUseCase] used to access callback methods */ + fun pigeon_getPigeonApiUseCase(): PigeonApiUseCase { + return pigeonRegistrar.getPigeonApiUseCase() + } +} +/** + * Interface for analyzing images. + * + * See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageAnalysis.Analyzer. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiAnalyzer(open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar) { + abstract fun pigeon_defaultConstructor(): androidx.camera.core.ImageAnalysis.Analyzer + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiAnalyzer?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.Analyzer.pigeon_defaultConstructor", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.pigeon_defaultConstructor(), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of Analyzer and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.ImageAnalysis.Analyzer, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + callback( + Result.failure( + CameraXError( + "new-instance-error", + "Attempting to create a new Dart instance of Analyzer, but the class has a nonnull callback method.", + ""))) + } + } + + /** Analyzes an image to produce a result. */ + fun analyze( + pigeon_instanceArg: androidx.camera.core.ImageAnalysis.Analyzer, + imageArg: androidx.camera.core.ImageProxy, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + return + } + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.camera_android_camerax.Analyzer.analyze" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_instanceArg, imageArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback(Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } +} +/** + * Error that the camera has encountered. + * + * See https://developer.android.com/reference/androidx/camera/core/CameraState.StateError. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiCameraStateStateError( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** The code of this error. */ + abstract fun code( + pigeon_instance: androidx.camera.core.CameraState.StateError + ): CameraStateErrorCode + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of CameraStateStateError and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.CameraState.StateError, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val codeArg = code(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.CameraStateStateError.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, codeArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * LiveData is a data holder class that can be observed within a given lifecycle. + * + * This is a wrapper around the native class to better support the generic type. Java has type + * erasure; + * + * See https://developer.android.com/reference/androidx/lifecycle/LiveData. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiLiveData(open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar) { + /** The generic type used by this instance. */ + abstract fun type( + pigeon_instance: io.flutter.plugins.camerax.LiveDataProxyApi.LiveDataWrapper + ): LiveDataSupportedType + + /** Adds the given observer to the observers list within the lifespan of the given owner. */ + abstract fun observe( + pigeon_instance: io.flutter.plugins.camerax.LiveDataProxyApi.LiveDataWrapper, + observer: androidx.lifecycle.Observer<*> + ) + + /** Removes all observers that are tied to the given `LifecycleOwner`. */ + abstract fun removeObservers( + pigeon_instance: io.flutter.plugins.camerax.LiveDataProxyApi.LiveDataWrapper + ) + + /** Returns the current value. */ + abstract fun getValue( + pigeon_instance: io.flutter.plugins.camerax.LiveDataProxyApi.LiveDataWrapper + ): Any? + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiLiveData?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.LiveData.observe", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = + args[0] as io.flutter.plugins.camerax.LiveDataProxyApi.LiveDataWrapper + val observerArg = args[1] as androidx.lifecycle.Observer<*> + val wrapped: List = + try { + api.observe(pigeon_instanceArg, observerArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.LiveData.removeObservers", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = + args[0] as io.flutter.plugins.camerax.LiveDataProxyApi.LiveDataWrapper + val wrapped: List = + try { + api.removeObservers(pigeon_instanceArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.LiveData.getValue", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = + args[0] as io.flutter.plugins.camerax.LiveDataProxyApi.LiveDataWrapper + val wrapped: List = + try { + listOf(api.getValue(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of LiveData and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: io.flutter.plugins.camerax.LiveDataProxyApi.LiveDataWrapper, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val typeArg = type(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.camera_android_camerax.LiveData.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, typeArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * An image proxy which has a similar interface as `android.media.Image`. + * + * See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageProxy. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiImageProxy( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** The image format. */ + abstract fun format(pigeon_instance: androidx.camera.core.ImageProxy): Long + + /** The image width. */ + abstract fun width(pigeon_instance: androidx.camera.core.ImageProxy): Long + + /** The image height. */ + abstract fun height(pigeon_instance: androidx.camera.core.ImageProxy): Long + + /** Returns the array of planes. */ + abstract fun getPlanes( + pigeon_instance: androidx.camera.core.ImageProxy + ): List + + /** Closes the underlying `android.media.Image`. */ + abstract fun close(pigeon_instance: androidx.camera.core.ImageProxy) + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiImageProxy?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ImageProxy.getPlanes", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.ImageProxy + val wrapped: List = + try { + listOf(api.getPlanes(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ImageProxy.close", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.ImageProxy + val wrapped: List = + try { + api.close(pigeon_instanceArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of ImageProxy and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.ImageProxy, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val formatArg = format(pigeon_instanceArg) + val widthArg = width(pigeon_instanceArg) + val heightArg = height(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.camera_android_camerax.ImageProxy.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, formatArg, widthArg, heightArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * A plane proxy which has an analogous interface as `android.media.Image.Plane`. + * + * See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageProxy.PlaneProxy. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiPlaneProxy( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** The pixels buffer. */ + abstract fun buffer(pigeon_instance: androidx.camera.core.ImageProxy.PlaneProxy): ByteArray + + /** The pixel stride. */ + abstract fun pixelStride(pigeon_instance: androidx.camera.core.ImageProxy.PlaneProxy): Long + + /** The row stride. */ + abstract fun rowStride(pigeon_instance: androidx.camera.core.ImageProxy.PlaneProxy): Long + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of PlaneProxy and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.ImageProxy.PlaneProxy, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val bufferArg = buffer(pigeon_instanceArg) + val pixelStrideArg = pixelStride(pigeon_instanceArg) + val rowStrideArg = rowStride(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.camera_android_camerax.PlaneProxy.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, bufferArg, pixelStrideArg, rowStrideArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * Defines a desired quality setting that can be used to configure components with quality setting + * requirements such as creating a Recorder. + * + * See https://developer.android.com/reference/kotlin/androidx/camera/video/QualitySelector. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiQualitySelector( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** Gets an instance of QualitySelector with a desired quality. */ + abstract fun from( + quality: VideoQuality, + fallbackStrategy: androidx.camera.video.FallbackStrategy? + ): androidx.camera.video.QualitySelector + + /** Gets an instance of QualitySelector with ordered desired qualities. */ + abstract fun fromOrderedList( + qualities: List, + fallbackStrategy: androidx.camera.video.FallbackStrategy? + ): androidx.camera.video.QualitySelector + + /** Gets the corresponding resolution from the input quality. */ + abstract fun getResolution( + cameraInfo: androidx.camera.core.CameraInfo, + quality: VideoQuality + ): android.util.Size? + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiQualitySelector?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.QualitySelector.from", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val qualityArg = args[1] as VideoQuality + val fallbackStrategyArg = args[2] as androidx.camera.video.FallbackStrategy? + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.from(qualityArg, fallbackStrategyArg), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.QualitySelector.fromOrderedList", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val qualitiesArg = args[1] as List + val fallbackStrategyArg = args[2] as androidx.camera.video.FallbackStrategy? + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.fromOrderedList(qualitiesArg, fallbackStrategyArg), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.QualitySelector.getResolution", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val cameraInfoArg = args[0] as androidx.camera.core.CameraInfo + val qualityArg = args[1] as VideoQuality + val wrapped: List = + try { + listOf(api.getResolution(cameraInfoArg, qualityArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of QualitySelector and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.video.QualitySelector, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.QualitySelector.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * A class represents the strategy that will be adopted when the device does not support all the + * desired Quality in QualitySelector in order to select the quality as possible. + * + * See https://developer.android.com/reference/androidx/camera/video/FallbackStrategy. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiFallbackStrategy( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** + * Returns a fallback strategy that will choose the quality that is closest to and higher than the + * input quality. + */ + abstract fun higherQualityOrLowerThan( + quality: VideoQuality + ): androidx.camera.video.FallbackStrategy + + /** + * Returns a fallback strategy that will choose the quality that is closest to and higher than the + * input quality. + */ + abstract fun higherQualityThan(quality: VideoQuality): androidx.camera.video.FallbackStrategy + + /** + * Returns a fallback strategy that will choose the quality that is closest to and lower than the + * input quality. + */ + abstract fun lowerQualityOrHigherThan( + quality: VideoQuality + ): androidx.camera.video.FallbackStrategy + + /** + * Returns a fallback strategy that will choose the quality that is closest to and lower than the + * input quality. + */ + abstract fun lowerQualityThan(quality: VideoQuality): androidx.camera.video.FallbackStrategy + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiFallbackStrategy?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.higherQualityOrLowerThan", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val qualityArg = args[1] as VideoQuality + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.higherQualityOrLowerThan(qualityArg), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.higherQualityThan", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val qualityArg = args[1] as VideoQuality + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.higherQualityThan(qualityArg), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.lowerQualityOrHigherThan", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val qualityArg = args[1] as VideoQuality + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.lowerQualityOrHigherThan(qualityArg), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.lowerQualityThan", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val qualityArg = args[1] as VideoQuality + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.lowerQualityThan(qualityArg), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of FallbackStrategy and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.video.FallbackStrategy, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * The CameraControl provides various asynchronous operations like zoom, focus and metering which + * affects output of all UseCases currently bound to that camera. + * + * See https://developer.android.com/reference/androidx/camera/core/CameraControl. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiCameraControl( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** Enable the torch or disable the torch. */ + abstract fun enableTorch( + pigeon_instance: androidx.camera.core.CameraControl, + torch: Boolean, + callback: (Result) -> Unit + ) + + /** Sets current zoom by ratio. */ + abstract fun setZoomRatio( + pigeon_instance: androidx.camera.core.CameraControl, + ratio: Double, + callback: (Result) -> Unit + ) + + /** Starts a focus and metering action configured by the `FocusMeteringAction`. */ + abstract fun startFocusAndMetering( + pigeon_instance: androidx.camera.core.CameraControl, + action: androidx.camera.core.FocusMeteringAction, + callback: (Result) -> Unit + ) + + /** Cancels current FocusMeteringAction and clears AF/AE/AWB regions. */ + abstract fun cancelFocusAndMetering( + pigeon_instance: androidx.camera.core.CameraControl, + callback: (Result) -> Unit + ) + + /** Set the exposure compensation value for the camera. */ + abstract fun setExposureCompensationIndex( + pigeon_instance: androidx.camera.core.CameraControl, + index: Long, + callback: (Result) -> Unit + ) + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiCameraControl?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.CameraControl.enableTorch", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.CameraControl + val torchArg = args[1] as Boolean + api.enableTorch(pigeon_instanceArg, torchArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.CameraControl.setZoomRatio", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.CameraControl + val ratioArg = args[1] as Double + api.setZoomRatio(pigeon_instanceArg, ratioArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.CameraControl.startFocusAndMetering", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.CameraControl + val actionArg = args[1] as androidx.camera.core.FocusMeteringAction + api.startFocusAndMetering(pigeon_instanceArg, actionArg) { + result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.CameraControl.cancelFocusAndMetering", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.CameraControl + api.cancelFocusAndMetering(pigeon_instanceArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.CameraControl.setExposureCompensationIndex", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.CameraControl + val indexArg = args[1] as Long + api.setExposureCompensationIndex(pigeon_instanceArg, indexArg) { result: Result + -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of CameraControl and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.CameraControl, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = "dev.flutter.pigeon.camera_android_camerax.CameraControl.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * The builder used to create the `FocusMeteringAction`. + * + * See + * https://developer.android.com/reference/kotlin/androidx/camera/core/FocusMeteringAction.Builder. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiFocusMeteringActionBuilder( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** Creates a Builder from a `MeteringPoint` with default mode FLAG_AF | FLAG_AE | FLAG_AWB. */ + abstract fun pigeon_defaultConstructor( + point: androidx.camera.core.MeteringPoint + ): androidx.camera.core.FocusMeteringAction.Builder + + /** Creates a Builder from a `MeteringPoint` and `MeteringMode`. */ + abstract fun withMode( + point: androidx.camera.core.MeteringPoint, + mode: MeteringMode + ): androidx.camera.core.FocusMeteringAction.Builder + + /** Adds another MeteringPoint with default metering mode. */ + abstract fun addPoint( + pigeon_instance: androidx.camera.core.FocusMeteringAction.Builder, + point: androidx.camera.core.MeteringPoint + ) + + /** Adds another MeteringPoint with specified meteringMode. */ + abstract fun addPointWithMode( + pigeon_instance: androidx.camera.core.FocusMeteringAction.Builder, + point: androidx.camera.core.MeteringPoint, + mode: MeteringMode + ) + + /** Disables the auto-cancel. */ + abstract fun disableAutoCancel(pigeon_instance: androidx.camera.core.FocusMeteringAction.Builder) + + /** Builds the `FocusMeteringAction` instance. */ + abstract fun build( + pigeon_instance: androidx.camera.core.FocusMeteringAction.Builder + ): androidx.camera.core.FocusMeteringAction + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers( + binaryMessenger: BinaryMessenger, + api: PigeonApiFocusMeteringActionBuilder? + ) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.pigeon_defaultConstructor", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val pointArg = args[1] as androidx.camera.core.MeteringPoint + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.pigeon_defaultConstructor(pointArg), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.withMode", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val pointArg = args[1] as androidx.camera.core.MeteringPoint + val modeArg = args[2] as MeteringMode + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.withMode(pointArg, modeArg), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.addPoint", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.FocusMeteringAction.Builder + val pointArg = args[1] as androidx.camera.core.MeteringPoint + val wrapped: List = + try { + api.addPoint(pigeon_instanceArg, pointArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.addPointWithMode", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.FocusMeteringAction.Builder + val pointArg = args[1] as androidx.camera.core.MeteringPoint + val modeArg = args[2] as MeteringMode + val wrapped: List = + try { + api.addPointWithMode(pigeon_instanceArg, pointArg, modeArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.disableAutoCancel", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.FocusMeteringAction.Builder + val wrapped: List = + try { + api.disableAutoCancel(pigeon_instanceArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.build", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.FocusMeteringAction.Builder + val wrapped: List = + try { + listOf(api.build(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** + * Creates a Dart instance of FocusMeteringActionBuilder and attaches it to [pigeon_instanceArg]. + */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.FocusMeteringAction.Builder, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * A configuration used to trigger a focus and/or metering action. + * + * See https://developer.android.com/reference/kotlin/androidx/camera/core/FocusMeteringAction. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiFocusMeteringAction( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** All MeteringPoints used for AE regions. */ + abstract fun meteringPointsAe( + pigeon_instance: androidx.camera.core.FocusMeteringAction + ): List + + /** All MeteringPoints used for AF regions. */ + abstract fun meteringPointsAf( + pigeon_instance: androidx.camera.core.FocusMeteringAction + ): List + + /** All MeteringPoints used for AWB regions. */ + abstract fun meteringPointsAwb( + pigeon_instance: androidx.camera.core.FocusMeteringAction + ): List + + /** If auto-cancel is enabled or not. */ + abstract fun isAutoCancelEnabled( + pigeon_instance: androidx.camera.core.FocusMeteringAction + ): Boolean + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of FocusMeteringAction and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.FocusMeteringAction, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val meteringPointsAeArg = meteringPointsAe(pigeon_instanceArg) + val meteringPointsAfArg = meteringPointsAf(pigeon_instanceArg) + val meteringPointsAwbArg = meteringPointsAwb(pigeon_instanceArg) + val isAutoCancelEnabledArg = isAutoCancelEnabled(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.FocusMeteringAction.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send( + listOf( + pigeon_identifierArg, + meteringPointsAeArg, + meteringPointsAfArg, + meteringPointsAwbArg, + isAutoCancelEnabledArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure( + CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * Result of the `CameraControl.startFocusAndMetering`. + * + * See https://developer.android.com/reference/androidx/camera/core/FocusMeteringResult. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiFocusMeteringResult( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** If auto focus is successful. */ + abstract fun isFocusSuccessful(pigeon_instance: androidx.camera.core.FocusMeteringResult): Boolean + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of FocusMeteringResult and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.FocusMeteringResult, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val isFocusSuccessfulArg = isFocusSuccessful(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.FocusMeteringResult.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg, isFocusSuccessfulArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * An immutable package of settings and outputs needed to capture a single image from the camera + * device. + * + * See https://developer.android.com/reference/android/hardware/camera2/CaptureRequest. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiCaptureRequest( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** + * Whether auto-exposure (AE) is currently locked to its latest calculated values. + * + * Value is boolean. + * + * This key is available on all devices. + */ + abstract fun controlAELock(): android.hardware.camera2.CaptureRequest.Key<*> + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiCaptureRequest?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.CaptureRequest.controlAELock", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.controlAELock(), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of CaptureRequest and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: android.hardware.camera2.CaptureRequest, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.CaptureRequest.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * A Key is used to do capture request field lookups with CaptureRequest.get or to set fields with + * `CaptureRequest.Builder.set`. + * + * See https://developer.android.com/reference/android/hardware/camera2/CaptureRequest.Key.html. + */ +@Suppress("UNCHECKED_CAST") +open class PigeonApiCaptureRequestKey( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of CaptureRequestKey and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: android.hardware.camera2.CaptureRequest.Key<*>, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.CaptureRequestKey.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * A bundle of Camera2 capture request options. + * + * See + * https://developer.android.com/reference/kotlin/androidx/camera/camera2/interop/CaptureRequestOptions. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiCaptureRequestOptions( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + abstract fun pigeon_defaultConstructor( + options: Map, Any?> + ): androidx.camera.camera2.interop.CaptureRequestOptions + + /** Returns a value for the given CaptureRequestKey or null if it hasn't been set. */ + abstract fun getCaptureRequestOption( + pigeon_instance: androidx.camera.camera2.interop.CaptureRequestOptions, + key: android.hardware.camera2.CaptureRequest.Key<*> + ): Any? + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers( + binaryMessenger: BinaryMessenger, + api: PigeonApiCaptureRequestOptions? + ) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.CaptureRequestOptions.pigeon_defaultConstructor", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val optionsArg = args[1] as Map, Any?> + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.pigeon_defaultConstructor(optionsArg), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.CaptureRequestOptions.getCaptureRequestOption", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = + args[0] as androidx.camera.camera2.interop.CaptureRequestOptions + val keyArg = args[1] as android.hardware.camera2.CaptureRequest.Key<*> + val wrapped: List = + try { + listOf(api.getCaptureRequestOption(pigeon_instanceArg, keyArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of CaptureRequestOptions and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.camera2.interop.CaptureRequestOptions, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.CaptureRequestOptions.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * An class that provides ability to interoperate with the 1android.hardware.camera21 APIs. + * + * See + * https://developer.android.com/reference/kotlin/androidx/camera/camera2/interop/Camera2CameraControl. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiCamera2CameraControl( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** Gets the `Camera2CameraControl` from a `CameraControl`. */ + abstract fun from( + cameraControl: androidx.camera.core.CameraControl + ): androidx.camera.camera2.interop.Camera2CameraControl + + /** Adds a `CaptureRequestOptions` updates the session with the options it contains. */ + abstract fun addCaptureRequestOptions( + pigeon_instance: androidx.camera.camera2.interop.Camera2CameraControl, + bundle: androidx.camera.camera2.interop.CaptureRequestOptions, + callback: (Result) -> Unit + ) + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers( + binaryMessenger: BinaryMessenger, + api: PigeonApiCamera2CameraControl? + ) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.Camera2CameraControl.from", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val cameraControlArg = args[1] as androidx.camera.core.CameraControl + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.from(cameraControlArg), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.Camera2CameraControl.addCaptureRequestOptions", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.camera2.interop.Camera2CameraControl + val bundleArg = args[1] as androidx.camera.camera2.interop.CaptureRequestOptions + api.addCaptureRequestOptions(pigeon_instanceArg, bundleArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(wrapError(error)) + } else { + reply.reply(wrapResult(null)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of Camera2CameraControl and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.camera2.interop.Camera2CameraControl, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.Camera2CameraControl.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * Applications can filter out unsuitable sizes and sort the resolution list in the preferred order + * by implementing the resolution filter interface. + * + * See + * https://developer.android.com/reference/kotlin/androidx/camera/core/resolutionselector/ResolutionFilter. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiResolutionFilter( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + abstract fun createWithOnePreferredSize( + preferredSize: android.util.Size + ): androidx.camera.core.resolutionselector.ResolutionFilter + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiResolutionFilter?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.ResolutionFilter.createWithOnePreferredSize", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val preferredSizeArg = args[1] as android.util.Size + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.createWithOnePreferredSize(preferredSizeArg), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of ResolutionFilter and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.resolutionselector.ResolutionFilter, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.ResolutionFilter.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * A Key is used to do camera characteristics field lookups with `CameraCharacteristics.get`. + * + * See + * https://developer.android.com/reference/android/hardware/camera2/CameraCharacteristics.Key.html. + */ +@Suppress("UNCHECKED_CAST") +open class PigeonApiCameraCharacteristicsKey( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + @Suppress("LocalVariableName", "FunctionName") + /** + * Creates a Dart instance of CameraCharacteristicsKey and attaches it to [pigeon_instanceArg]. + */ + fun pigeon_newInstance( + pigeon_instanceArg: android.hardware.camera2.CameraCharacteristics.Key<*>, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.CameraCharacteristicsKey.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * The properties describing a `CameraDevice`. + * + * See https://developer.android.com/reference/android/hardware/camera2/CameraCharacteristics. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiCameraCharacteristics( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** + * Generally classifies the overall set of the camera device functionality. + * + * Value is `InfoSupportedHardwareLevel`. + * + * This key is available on all devices. + */ + abstract fun infoSupportedHardwareLevel(): android.hardware.camera2.CameraCharacteristics.Key<*> + + /** + * Clockwise angle through which the output image needs to be rotated to be upright on the device + * screen in its native orientation.. + * + * Value is int. + * + * This key is available on all devices. + */ + abstract fun sensorOrientation(): android.hardware.camera2.CameraCharacteristics.Key<*> + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers( + binaryMessenger: BinaryMessenger, + api: PigeonApiCameraCharacteristics? + ) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.CameraCharacteristics.infoSupportedHardwareLevel", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.infoSupportedHardwareLevel(), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.CameraCharacteristics.sensorOrientation", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.sensorOrientation(), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of CameraCharacteristics and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: android.hardware.camera2.CameraCharacteristics, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.CameraCharacteristics.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * An interface for retrieving Camera2-related camera information. + * + * See + * https://developer.android.com/reference/kotlin/androidx/camera/camera2/interop/Camera2CameraInfo. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiCamera2CameraInfo( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** Gets the `Camera2CameraInfo` from a `CameraInfo`. */ + abstract fun from( + cameraInfo: androidx.camera.core.CameraInfo + ): androidx.camera.camera2.interop.Camera2CameraInfo + + /** Gets the string camera ID. */ + abstract fun getCameraId( + pigeon_instance: androidx.camera.camera2.interop.Camera2CameraInfo + ): String + + /** Gets a camera characteristic value. */ + abstract fun getCameraCharacteristic( + pigeon_instance: androidx.camera.camera2.interop.Camera2CameraInfo, + key: android.hardware.camera2.CameraCharacteristics.Key<*> + ): Any? + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiCamera2CameraInfo?) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.Camera2CameraInfo.from", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val cameraInfoArg = args[1] as androidx.camera.core.CameraInfo + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.from(cameraInfoArg), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.Camera2CameraInfo.getCameraId", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.camera2.interop.Camera2CameraInfo + val wrapped: List = + try { + listOf(api.getCameraId(pigeon_instanceArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.Camera2CameraInfo.getCameraCharacteristic", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.camera2.interop.Camera2CameraInfo + val keyArg = args[1] as android.hardware.camera2.CameraCharacteristics.Key<*> + val wrapped: List = + try { + listOf(api.getCameraCharacteristic(pigeon_instanceArg, keyArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of Camera2CameraInfo and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.camera2.interop.Camera2CameraInfo, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.Camera2CameraInfo.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * A factory to create a MeteringPoint. + * + * See https://developer.android.com/reference/androidx/camera/core/MeteringPointFactory. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiMeteringPointFactory( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** Creates a MeteringPoint by x, y. */ + abstract fun createPoint( + pigeon_instance: androidx.camera.core.MeteringPointFactory, + x: Double, + y: Double + ): androidx.camera.core.MeteringPoint + + /** Creates a MeteringPoint by x, y, size. */ + abstract fun createPointWithSize( + pigeon_instance: androidx.camera.core.MeteringPointFactory, + x: Double, + y: Double, + size: Double + ): androidx.camera.core.MeteringPoint + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers( + binaryMessenger: BinaryMessenger, + api: PigeonApiMeteringPointFactory? + ) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.MeteringPointFactory.createPoint", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.MeteringPointFactory + val xArg = args[1] as Double + val yArg = args[2] as Double + val wrapped: List = + try { + listOf(api.createPoint(pigeon_instanceArg, xArg, yArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.MeteringPointFactory.createPointWithSize", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_instanceArg = args[0] as androidx.camera.core.MeteringPointFactory + val xArg = args[1] as Double + val yArg = args[2] as Double + val sizeArg = args[3] as Double + val wrapped: List = + try { + listOf(api.createPointWithSize(pigeon_instanceArg, xArg, yArg, sizeArg)) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** Creates a Dart instance of MeteringPointFactory and attaches it to [pigeon_instanceArg]. */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.MeteringPointFactory, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.MeteringPointFactory.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } +} +/** + * A MeteringPointFactory that can convert a View (x, y) into a MeteringPoint which can then be used + * to construct a FocusMeteringAction to start a focus and metering action. + * + * See + * https://developer.android.com/reference/androidx/camera/core/DisplayOrientedMeteringPointFactory. + */ +@Suppress("UNCHECKED_CAST") +abstract class PigeonApiDisplayOrientedMeteringPointFactory( + open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar +) { + /** + * Creates a DisplayOrientedMeteringPointFactory for converting View (x, y) into a MeteringPoint + * based on the current display's rotation and CameraInfo. + */ + abstract fun pigeon_defaultConstructor( + cameraInfo: androidx.camera.core.CameraInfo, + width: Double, + height: Double + ): androidx.camera.core.DisplayOrientedMeteringPointFactory + + companion object { + @Suppress("LocalVariableName") + fun setUpMessageHandlers( + binaryMessenger: BinaryMessenger, + api: PigeonApiDisplayOrientedMeteringPointFactory? + ) { + val codec = api?.pigeonRegistrar?.codec ?: CameraXLibraryPigeonCodec() + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.DisplayOrientedMeteringPointFactory.pigeon_defaultConstructor", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val pigeon_identifierArg = args[0] as Long + val cameraInfoArg = args[1] as androidx.camera.core.CameraInfo + val widthArg = args[2] as Double + val heightArg = args[3] as Double + val wrapped: List = + try { + api.pigeonRegistrar.instanceManager.addDartCreatedInstance( + api.pigeon_defaultConstructor(cameraInfoArg, widthArg, heightArg), + pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + } + } + + @Suppress("LocalVariableName", "FunctionName") + /** + * Creates a Dart instance of DisplayOrientedMeteringPointFactory and attaches it to + * [pigeon_instanceArg]. + */ + fun pigeon_newInstance( + pigeon_instanceArg: androidx.camera.core.DisplayOrientedMeteringPointFactory, + callback: (Result) -> Unit + ) { + if (pigeonRegistrar.ignoreCallsToDart) { + callback( + Result.failure( + CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) + } else if (pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback(Result.success(Unit)) + } else { + val pigeon_identifierArg = + pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) + val binaryMessenger = pigeonRegistrar.binaryMessenger + val codec = pigeonRegistrar.codec + val channelName = + "dev.flutter.pigeon.camera_android_camerax.DisplayOrientedMeteringPointFactory.pigeon_newInstance" + val channel = BasicMessageChannel(binaryMessenger, channelName, codec) + channel.send(listOf(pigeon_identifierArg)) { + if (it is List<*>) { + if (it.size > 1) { + callback( + Result.failure(CameraXError(it[0] as String, it[1] as String, it[2] as String?))) + } else { + callback(Result.success(Unit)) + } + } else { + callback(Result.failure(createConnectionError(channelName))) + } + } + } + } + + @Suppress("FunctionName") + /** An implementation of [PigeonApiMeteringPointFactory] used to access callback methods */ + fun pigeon_getPigeonApiMeteringPointFactory(): PigeonApiMeteringPointFactory { + return pigeonRegistrar.getPigeonApiMeteringPointFactory() + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraXProxy.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraXProxy.java deleted file mode 100644 index e749940200a6..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CameraXProxy.java +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import android.app.Activity; -import android.util.Size; -import androidx.annotation.NonNull; -import androidx.camera.core.CameraSelector; -import androidx.camera.core.ImageAnalysis; -import androidx.camera.core.ImageCapture; -import androidx.camera.core.Preview; -import androidx.camera.video.Recorder; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ResolutionInfo; -import java.io.File; - -/** Utility class used to create CameraX-related objects primarily for testing purposes. */ -public class CameraXProxy { - /** - * Converts a {@link ResolutionInfo} instance to a {@link Size} for setting the target resolution - * of {@link UseCase}s. - */ - public static @NonNull Size sizeFromResolution(@NonNull ResolutionInfo resolutionInfo) { - return new Size(resolutionInfo.getWidth().intValue(), resolutionInfo.getHeight().intValue()); - } - - public @NonNull CameraSelector.Builder createCameraSelectorBuilder() { - return new CameraSelector.Builder(); - } - - /** Creates an instance of {@link CameraPermissionsManager}. */ - public @NonNull CameraPermissionsManager createCameraPermissionsManager() { - return new CameraPermissionsManager(); - } - - /** Creates an instance of the {@link DeviceOrientationManager}. */ - public @NonNull DeviceOrientationManager createDeviceOrientationManager( - @NonNull Activity activity, - @NonNull Boolean isFrontFacing, - int sensorOrientation, - @NonNull DeviceOrientationManager.DeviceOrientationChangeCallback callback) { - return new DeviceOrientationManager(activity, isFrontFacing, sensorOrientation, callback); - } - - /** Creates a builder for an instance of the {@link Preview} use case. */ - public @NonNull Preview.Builder createPreviewBuilder() { - return new Preview.Builder(); - } - - /** - * Creates an instance of the {@link SystemServicesFlutterApiImpl}. - * - *

Included in this class to utilize the callback methods it provides, e.g. {@code - * onCameraError(String)}. - */ - public @NonNull SystemServicesFlutterApiImpl createSystemServicesFlutterApiImpl( - @NonNull BinaryMessenger binaryMessenger) { - return new SystemServicesFlutterApiImpl(binaryMessenger); - } - - /** Creates an instance of {@link Recorder.Builder}. */ - @NonNull - public Recorder.Builder createRecorderBuilder() { - return new Recorder.Builder(); - } - - /** Creates a builder for an instance of the {@link ImageCapture} use case. */ - @NonNull - public ImageCapture.Builder createImageCaptureBuilder() { - return new ImageCapture.Builder(); - } - - /** - * Creates an {@link ImageCapture.OutputFileOptions} to configure where to save a captured image. - */ - @NonNull - public ImageCapture.OutputFileOptions createImageCaptureOutputFileOptions(@NonNull File file) { - return new ImageCapture.OutputFileOptions.Builder(file).build(); - } - - /** Creates an instance of {@link ImageAnalysis.Builder}. */ - @NonNull - public ImageAnalysis.Builder createImageAnalysisBuilder() { - return new ImageAnalysis.Builder(); - } - - /** Creates an array of {@code byte}s with the size provided. */ - @NonNull - public byte[] getBytesFromBuffer(int size) { - return new byte[size]; - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CaptureRequestOptionsHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CaptureRequestOptionsHostApiImpl.java deleted file mode 100644 index f76dd5422e72..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CaptureRequestOptionsHostApiImpl.java +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import android.hardware.camera2.CaptureRequest; -import androidx.annotation.NonNull; -import androidx.annotation.OptIn; -import androidx.annotation.VisibleForTesting; -import androidx.camera.camera2.interop.CaptureRequestOptions; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CaptureRequestKeySupportedType; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CaptureRequestOptionsHostApi; -import java.util.HashMap; -import java.util.Map; - -/** - * Host API implementation for {@link CaptureRequestOptions}. - * - *

This class may handle instantiating and adding native object instances that are attached to a - * Dart instance or handle method calls on the associated native class or an instance of the class. - */ -public class CaptureRequestOptionsHostApiImpl implements CaptureRequestOptionsHostApi { - private final InstanceManager instanceManager; - private final CaptureRequestOptionsProxy proxy; - - /** Proxy for constructor of {@link CaptureRequestOptions}. */ - @VisibleForTesting - public static class CaptureRequestOptionsProxy { - /** Creates an instance of {@link CaptureRequestOptions}. */ - // Suppression is safe because the type shared between the key and value pairs that - // represent capture request options is checked on the Dart side. - @SuppressWarnings("unchecked") - @OptIn(markerClass = androidx.camera.camera2.interop.ExperimentalCamera2Interop.class) - public @NonNull CaptureRequestOptions create( - @NonNull Map options) { - CaptureRequestOptions.Builder builder = getCaptureRequestOptionsBuilder(); - - for (Map.Entry option : options.entrySet()) { - CaptureRequestKeySupportedType optionKeyType = option.getKey(); - CaptureRequest.Key optionKey = getCaptureRequestKey(optionKeyType); - Object optionValue = option.getValue(); - - if (optionValue == null) { - builder.clearCaptureRequestOption(optionKey); - continue; - } - - switch (optionKeyType) { - case CONTROL_AE_LOCK: - builder.setCaptureRequestOption( - (CaptureRequest.Key) optionKey, (Boolean) optionValue); - break; - default: - throw new IllegalArgumentException( - "The capture request key " - + optionKeyType.toString() - + "is not currently supported by the plugin."); - } - } - - return builder.build(); - } - - private CaptureRequest.Key getCaptureRequestKey( - CaptureRequestKeySupportedType type) { - CaptureRequest.Key key; - switch (type) { - case CONTROL_AE_LOCK: - key = CaptureRequest.CONTROL_AE_LOCK; - break; - default: - throw new IllegalArgumentException( - "The capture request key is not currently supported by the plugin."); - } - return key; - } - - @VisibleForTesting - @OptIn(markerClass = androidx.camera.camera2.interop.ExperimentalCamera2Interop.class) - public @NonNull CaptureRequestOptions.Builder getCaptureRequestOptionsBuilder() { - return new CaptureRequestOptions.Builder(); - } - } - - /** - * Constructs a {@link CaptureRequestOptionsHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - */ - public CaptureRequestOptionsHostApiImpl(@NonNull InstanceManager instanceManager) { - this(instanceManager, new CaptureRequestOptionsProxy()); - } - - /** - * Constructs a {@link CaptureRequestOptionsHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - * @param proxy proxy for constructor of {@link CaptureRequestOptions} - */ - @VisibleForTesting - CaptureRequestOptionsHostApiImpl( - @NonNull InstanceManager instanceManager, @NonNull CaptureRequestOptionsProxy proxy) { - this.instanceManager = instanceManager; - this.proxy = proxy; - } - - @Override - public void create(@NonNull Long identifier, @NonNull Map options) { - Map decodedOptions = - new HashMap(); - for (Map.Entry option : options.entrySet()) { - Integer index = ((Number) option.getKey()).intValue(); - decodedOptions.put(CaptureRequestKeySupportedType.values()[index], option.getValue()); - } - instanceManager.addDartCreatedInstance(proxy.create(decodedOptions), identifier); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CaptureRequestOptionsProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CaptureRequestOptionsProxyApi.java new file mode 100644 index 000000000000..18932f7e35eb --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CaptureRequestOptionsProxyApi.java @@ -0,0 +1,59 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import android.hardware.camera2.CaptureRequest; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.camera.camera2.interop.CaptureRequestOptions; +import androidx.camera.camera2.interop.ExperimentalCamera2Interop; +import java.util.Map; + +/** + * ProxyApi implementation for {@link CaptureRequestOptions}. This class may handle instantiating + * native object instances that are attached to a Dart instance or handle method calls on the + * associated native class or an instance of that class. + */ +class CaptureRequestOptionsProxyApi extends PigeonApiCaptureRequestOptions { + CaptureRequestOptionsProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @ExperimentalCamera2Interop + CaptureRequestOptions.Builder createBuilder() { + return new CaptureRequestOptions.Builder(); + } + + @SuppressWarnings("unchecked") + @ExperimentalCamera2Interop + @NonNull + @Override + public CaptureRequestOptions pigeon_defaultConstructor( + @NonNull Map, ?> options) { + final CaptureRequestOptions.Builder builder = createBuilder(); + + for (final Map.Entry, ?> option : options.entrySet()) { + Object optionValue = option.getValue(); + + if (optionValue == null) { + builder.clearCaptureRequestOption(option.getKey()); + continue; + } + + builder.setCaptureRequestOption( + (CaptureRequest.Key) option.getKey(), option.getValue()); + } + + return builder.build(); + } + + @ExperimentalCamera2Interop + @Nullable + @Override + public Object getCaptureRequestOption( + @NonNull CaptureRequestOptions pigeonInstance, @NonNull CaptureRequest.Key key) { + return pigeonInstance.getCaptureRequestOption(key); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CaptureRequestProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CaptureRequestProxyApi.java new file mode 100644 index 000000000000..9556baccc4bb --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/CaptureRequestProxyApi.java @@ -0,0 +1,25 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import android.hardware.camera2.CaptureRequest; +import androidx.annotation.NonNull; + +/** + * ProxyApi implementation for {@link CaptureRequest}. This class may handle instantiating native + * object instances that are attached to a Dart instance or handle method calls on the associated + * native class or an instance of that class. + */ +class CaptureRequestProxyApi extends PigeonApiCaptureRequest { + CaptureRequestProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public android.hardware.camera2.CaptureRequest.Key controlAELock() { + return CaptureRequest.CONTROL_AE_LOCK; + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManager.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManager.java index a8ad257a2bc4..fa391d2af497 100644 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManager.java +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManager.java @@ -4,7 +4,6 @@ package io.flutter.plugins.camerax; -import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; @@ -12,47 +11,37 @@ import android.content.res.Configuration; import android.view.Display; import android.view.Surface; -import android.view.WindowManager; import androidx.annotation.NonNull; import androidx.annotation.VisibleForTesting; import io.flutter.embedding.engine.systemchannels.PlatformChannel; import io.flutter.embedding.engine.systemchannels.PlatformChannel.DeviceOrientation; +import java.util.Objects; /** * Support class to help to determine the media orientation based on the orientation of the device. */ public class DeviceOrientationManager { - - interface DeviceOrientationChangeCallback { - void onChange(DeviceOrientation newOrientation); - } - private static final IntentFilter orientationIntentFilter = new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED); - private final Activity activity; - private final boolean isFrontFacing; - private final int sensorOrientation; - private final DeviceOrientationChangeCallback deviceOrientationChangeCallback; + private final DeviceOrientationManagerProxyApi api; private PlatformChannel.DeviceOrientation lastOrientation; private BroadcastReceiver broadcastReceiver; - DeviceOrientationManager( - @NonNull Activity activity, - boolean isFrontFacing, - int sensorOrientation, - DeviceOrientationChangeCallback callback) { - this.activity = activity; - this.isFrontFacing = isFrontFacing; - this.sensorOrientation = sensorOrientation; - this.deviceOrientationChangeCallback = callback; + DeviceOrientationManager(DeviceOrientationManagerProxyApi api) { + this.api = api; + } + + @NonNull + Context getContext() { + return api.getPigeonRegistrar().getContext(); } /** * Starts listening to the device's sensors or UI for orientation updates. * *

When orientation information is updated, the callback method of the {@link - * DeviceOrientationChangeCallback} is called with the new orientation. + * DeviceOrientationManagerProxyApi} is called with the new orientation. * *

If the device's ACCELEROMETER_ROTATION setting is enabled the {@link * DeviceOrientationManager} will report orientation updates based on the sensor information. If @@ -70,8 +59,8 @@ public void onReceive(Context context, Intent intent) { handleUIOrientationChange(); } }; - activity.registerReceiver(broadcastReceiver, orientationIntentFilter); - broadcastReceiver.onReceive(activity, null); + getContext().registerReceiver(broadcastReceiver, orientationIntentFilter); + broadcastReceiver.onReceive(getContext(), null); } /** Stops listening for orientation updates. */ @@ -79,7 +68,7 @@ public void stop() { if (broadcastReceiver == null) { return; } - activity.unregisterReceiver(broadcastReceiver); + getContext().unregisterReceiver(broadcastReceiver); broadcastReceiver = null; } @@ -92,7 +81,7 @@ public void stop() { @VisibleForTesting void handleUIOrientationChange() { PlatformChannel.DeviceOrientation orientation = getUIOrientation(); - handleOrientationChange(orientation, lastOrientation, deviceOrientationChangeCallback); + handleOrientationChange(this, orientation, lastOrientation, api); lastOrientation = orientation; } @@ -105,11 +94,30 @@ void handleUIOrientationChange() { */ @VisibleForTesting static void handleOrientationChange( + DeviceOrientationManager manager, DeviceOrientation newOrientation, DeviceOrientation previousOrientation, - DeviceOrientationChangeCallback callback) { + DeviceOrientationManagerProxyApi api) { if (!newOrientation.equals(previousOrientation)) { - callback.onChange(newOrientation); + api.getPigeonRegistrar() + .runOnMainThread( + new ProxyApiRegistrar.FlutterMethodRunnable() { + @Override + public void run() { + api.onDeviceOrientationChanged( + manager, + newOrientation.toString(), + ResultCompat.asCompatCallback( + result -> { + if (result.isFailure()) { + onFailure( + "DeviceOrientationManager.onDeviceOrientationChanged", + Objects.requireNonNull(result.exceptionOrNull())); + } + return null; + })); + } + }); } } @@ -126,7 +134,7 @@ static void handleOrientationChange( @NonNull PlatformChannel.DeviceOrientation getUIOrientation() { final int rotation = getDefaultRotation(); - final int orientation = activity.getResources().getConfiguration().orientation; + final int orientation = getContext().getResources().getConfiguration().orientation; switch (orientation) { case Configuration.ORIENTATION_PORTRAIT: @@ -171,9 +179,8 @@ int getDefaultRotation() { * * @return An instance of the Android {@link android.view.Display}. */ - @SuppressWarnings("deprecation") @VisibleForTesting Display getDisplay() { - return ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); + return api.getPigeonRegistrar().getDisplay(); } } diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManagerFlutterApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManagerFlutterApiImpl.java deleted file mode 100644 index e3e514cfd780..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManagerFlutterApiImpl.java +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.DeviceOrientationManagerFlutterApi; - -public class DeviceOrientationManagerFlutterApiImpl extends DeviceOrientationManagerFlutterApi { - public DeviceOrientationManagerFlutterApiImpl(@NonNull BinaryMessenger binaryMessenger) { - super(binaryMessenger); - } - - public void sendDeviceOrientationChangedEvent( - @NonNull String orientation, @NonNull Reply reply) { - super.onDeviceOrientationChanged(orientation, reply); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManagerHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManagerHostApiImpl.java deleted file mode 100644 index 363bc39b2780..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManagerHostApiImpl.java +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import android.app.Activity; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.VisibleForTesting; -import io.flutter.embedding.engine.systemchannels.PlatformChannel.DeviceOrientation; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.CameraPermissionsManager.PermissionsRegistry; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.DeviceOrientationManagerHostApi; - -public class DeviceOrientationManagerHostApiImpl implements DeviceOrientationManagerHostApi { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - - @VisibleForTesting public @NonNull CameraXProxy cameraXProxy = new CameraXProxy(); - @VisibleForTesting public @Nullable DeviceOrientationManager deviceOrientationManager; - - @VisibleForTesting - public @NonNull DeviceOrientationManagerFlutterApiImpl deviceOrientationManagerFlutterApiImpl; - - private Activity activity; - private PermissionsRegistry permissionsRegistry; - - public DeviceOrientationManagerHostApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - this.deviceOrientationManagerFlutterApiImpl = - new DeviceOrientationManagerFlutterApiImpl(binaryMessenger); - } - - public void setActivity(@NonNull Activity activity) { - this.activity = activity; - } - - /** - * Starts listening for device orientation changes using an instance of a {@link - * DeviceOrientationManager}. - * - *

Whenever a change in device orientation is detected by the {@code DeviceOrientationManager}, - * the {@link SystemServicesFlutterApi} will be used to notify the Dart side. - */ - @Override - public void startListeningForDeviceOrientationChange( - @NonNull Boolean isFrontFacing, @NonNull Long sensorOrientation) { - if (activity == null) { - throw new IllegalStateException( - "Activity must be set to start listening for device orientation changes."); - } - - deviceOrientationManager = - cameraXProxy.createDeviceOrientationManager( - activity, - isFrontFacing, - sensorOrientation.intValue(), - (DeviceOrientation newOrientation) -> { - deviceOrientationManagerFlutterApiImpl.sendDeviceOrientationChangedEvent( - serializeDeviceOrientation(newOrientation), reply -> {}); - }); - deviceOrientationManager.start(); - } - - /** Serializes {@code DeviceOrientation} into a String that the Dart side is able to recognize. */ - String serializeDeviceOrientation(DeviceOrientation orientation) { - return orientation.toString(); - } - - /** - * Tells the {@code deviceOrientationManager} to stop listening for orientation updates. - * - *

Has no effect if the {@code deviceOrientationManager} was never created to listen for device - * orientation updates. - */ - @Override - public void stopListeningForDeviceOrientationChange() { - if (deviceOrientationManager != null) { - deviceOrientationManager.stop(); - } - } - - /** - * Gets default capture rotation for CameraX {@code UseCase}s. - * - *

The default capture rotation for CameraX is the rotation of default {@code Display} at the - * time that a {@code UseCase} is bound, but the default {@code Display} does not change in this - * plugin, so this value is {@code Display}-agnostic. - * - *

See - * https://developer.android.com/reference/androidx/camera/core/ImageCapture#setTargetRotation(int) - * for instance for more information on how this default value is used. - */ - @Override - @NonNull - public Long getDefaultDisplayRotation() { - int defaultRotation; - try { - defaultRotation = deviceOrientationManager.getDefaultRotation(); - } catch (NullPointerException e) { - throw new IllegalStateException( - "startListeningForDeviceOrientationChange must first be called to subscribe to device orientation changes in order to retrieve default rotation."); - } - - return Long.valueOf(defaultRotation); - } - - /** Gets current UI orientation based on the current device orientation and rotation. */ - @Override - @NonNull - public String getUiOrientation() { - return serializeDeviceOrientation(deviceOrientationManager.getUIOrientation()); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManagerProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManagerProxyApi.java new file mode 100644 index 000000000000..ef8698843802 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DeviceOrientationManagerProxyApi.java @@ -0,0 +1,53 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; + +/** + * ProxyApi implementation for {@link DeviceOrientationManager}. This class may handle instantiating + * native object instances that are attached to a Dart instance or handle method calls on the + * associated native class or an instance of that class. + */ +public class DeviceOrientationManagerProxyApi extends PigeonApiDeviceOrientationManager { + DeviceOrientationManagerProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public ProxyApiRegistrar getPigeonRegistrar() { + return (ProxyApiRegistrar) super.getPigeonRegistrar(); + } + + @NonNull + @Override + public DeviceOrientationManager pigeon_defaultConstructor() { + return new DeviceOrientationManager(this); + } + + @Override + public void startListeningForDeviceOrientationChange( + @NonNull DeviceOrientationManager pigeonInstance) { + pigeonInstance.start(); + } + + @Override + public void stopListeningForDeviceOrientationChange( + @NonNull DeviceOrientationManager pigeonInstance) { + pigeonInstance.stop(); + } + + @Override + public long getDefaultDisplayRotation(@NonNull DeviceOrientationManager pigeonInstance) { + return pigeonInstance.getDefaultRotation(); + } + + @NonNull + @Override + public String getUiOrientation(@NonNull DeviceOrientationManager pigeonInstance) { + return pigeonInstance.getUIOrientation().toString(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DisplayOrientedMeteringPointFactoryProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DisplayOrientedMeteringPointFactoryProxyApi.java new file mode 100644 index 000000000000..93bfb70d5e37 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/DisplayOrientedMeteringPointFactoryProxyApi.java @@ -0,0 +1,42 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import android.view.Display; +import androidx.annotation.NonNull; +import androidx.camera.core.CameraInfo; +import androidx.camera.core.DisplayOrientedMeteringPointFactory; + +/** + * ProxyApi implementation for {@link DisplayOrientedMeteringPointFactory}. This class may handle + * instantiating native object instances that are attached to a Dart instance or handle method calls + * on the associated native class or an instance of that class. + */ +class DisplayOrientedMeteringPointFactoryProxyApi + extends PigeonApiDisplayOrientedMeteringPointFactory { + DisplayOrientedMeteringPointFactoryProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public ProxyApiRegistrar getPigeonRegistrar() { + return (ProxyApiRegistrar) super.getPigeonRegistrar(); + } + + @NonNull + @Override + public DisplayOrientedMeteringPointFactory pigeon_defaultConstructor( + @NonNull CameraInfo cameraInfo, double width, double height) { + final Display display = getPigeonRegistrar().getDisplay(); + + if (display != null) { + return new DisplayOrientedMeteringPointFactory( + display, cameraInfo, (float) width, (float) height); + } + + throw new IllegalStateException("A Display could not be retrieved."); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ExposureStateFlutterApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ExposureStateFlutterApiImpl.java deleted file mode 100644 index 1f31f603a8a4..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ExposureStateFlutterApiImpl.java +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import android.util.Range; -import androidx.annotation.NonNull; -import androidx.camera.core.ExposureState; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ExposureCompensationRange; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ExposureStateFlutterApi; - -public class ExposureStateFlutterApiImpl extends ExposureStateFlutterApi { - private final InstanceManager instanceManager; - - public ExposureStateFlutterApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - super(binaryMessenger); - this.instanceManager = instanceManager; - } - - /** - * Creates a {@link ExposureState} on the Dart side with its exposure compensation range that can - * be used to set the exposure compensation index and its exposure compensation step, the smallest - * step by which the exposure compensation can be changed. - */ - void create(@NonNull ExposureState exposureState, @NonNull Reply reply) { - if (instanceManager.containsInstance(exposureState)) { - return; - } - - final Range exposureCompensationRangeFromState = - exposureState.getExposureCompensationRange(); - ExposureCompensationRange exposureCompensationRange = - new ExposureCompensationRange.Builder() - .setMinCompensation(exposureCompensationRangeFromState.getLower().longValue()) - .setMaxCompensation(exposureCompensationRangeFromState.getUpper().longValue()) - .build(); - final Double exposureCompensationStep = - exposureState.getExposureCompensationStep().doubleValue(); - - create( - instanceManager.addHostCreatedInstance(exposureState), - exposureCompensationRange, - exposureCompensationStep, - reply); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ExposureStateProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ExposureStateProxyApi.java new file mode 100644 index 000000000000..45163b8b58f2 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ExposureStateProxyApi.java @@ -0,0 +1,31 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import android.util.Range; +import androidx.annotation.NonNull; +import androidx.camera.core.ExposureState; + +/** + * ProxyApi implementation for {@link ExposureState}. This class may handle instantiating native + * object instances that are attached to a Dart instance or handle method calls on the associated + * native class or an instance of that class. + */ +class ExposureStateProxyApi extends PigeonApiExposureState { + ExposureStateProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public Range exposureCompensationRange(ExposureState pigeonInstance) { + return pigeonInstance.getExposureCompensationRange(); + } + + @Override + public double exposureCompensationStep(ExposureState pigeonInstance) { + return pigeonInstance.getExposureCompensationStep().doubleValue(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FallbackStrategyHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FallbackStrategyHostApiImpl.java deleted file mode 100644 index ae67ed711ca9..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FallbackStrategyHostApiImpl.java +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.annotation.VisibleForTesting; -import androidx.camera.video.FallbackStrategy; -import androidx.camera.video.Quality; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.FallbackStrategyHostApi; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.VideoQuality; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.VideoResolutionFallbackRule; - -/** - * Host API implementation for {@link FallbackStrategy}. - * - *

This class may handle instantiating and adding native object instances that are attached to a - * Dart instance or handle method calls on the associated native class or an instance of the class. - */ -public class FallbackStrategyHostApiImpl implements FallbackStrategyHostApi { - private final InstanceManager instanceManager; - - private final FallbackStrategyProxy proxy; - - /** Proxy for constructor of {@link FallbackStrategy}. */ - @VisibleForTesting - public static class FallbackStrategyProxy { - /** Creates an instance of {@link FallbackStrategy}. */ - public @NonNull FallbackStrategy create( - @NonNull VideoQuality videoQuality, @NonNull VideoResolutionFallbackRule fallbackRule) { - Quality quality = QualitySelectorHostApiImpl.getQualityFromVideoQuality(videoQuality); - - switch (fallbackRule) { - case HIGHER_QUALITY_OR_LOWER_THAN: - return FallbackStrategy.higherQualityOrLowerThan(quality); - case HIGHER_QUALITY_THAN: - return FallbackStrategy.higherQualityThan(quality); - case LOWER_QUALITY_OR_HIGHER_THAN: - return FallbackStrategy.lowerQualityOrHigherThan(quality); - case LOWER_QUALITY_THAN: - return FallbackStrategy.lowerQualityThan(quality); - } - throw new IllegalArgumentException( - "Specified fallback rule " + fallbackRule + " unrecognized."); - } - } - - /** - * Constructs a {@link FallbackStrategyHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - */ - public FallbackStrategyHostApiImpl(@NonNull InstanceManager instanceManager) { - this(instanceManager, new FallbackStrategyProxy()); - } - - /** - * Constructs a {@link FallbackStrategyHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - * @param proxy proxy for constructor of {@link FallbackStrategy} - */ - FallbackStrategyHostApiImpl( - @NonNull InstanceManager instanceManager, @NonNull FallbackStrategyProxy proxy) { - this.instanceManager = instanceManager; - this.proxy = proxy; - } - - /** - * Creates a {@link FallbackStrategy} instance with the video quality and fallback rule specified. - */ - @Override - public void create( - @NonNull Long identifier, - @NonNull VideoQuality videoQuality, - @NonNull VideoResolutionFallbackRule fallbackRule) { - instanceManager.addDartCreatedInstance(proxy.create(videoQuality, fallbackRule), identifier); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FallbackStrategyProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FallbackStrategyProxyApi.java new file mode 100644 index 000000000000..b7a7922e19c8 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FallbackStrategyProxyApi.java @@ -0,0 +1,64 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.camera.video.FallbackStrategy; +import androidx.camera.video.Quality; + +/** + * ProxyApi implementation for {@link FallbackStrategy}. This class may handle instantiating native + * object instances that are attached to a Dart instance or handle method calls on the associated + * native class or an instance of that class. + */ +class FallbackStrategyProxyApi extends PigeonApiFallbackStrategy { + FallbackStrategyProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public FallbackStrategy higherQualityOrLowerThan(@NonNull VideoQuality quality) { + return FallbackStrategy.higherQualityOrLowerThan(getNativeQuality(quality)); + } + + @NonNull + @Override + public FallbackStrategy higherQualityThan(@NonNull VideoQuality quality) { + return FallbackStrategy.higherQualityThan(getNativeQuality(quality)); + } + + @NonNull + @Override + public FallbackStrategy lowerQualityOrHigherThan(@NonNull VideoQuality quality) { + return FallbackStrategy.lowerQualityOrHigherThan(getNativeQuality(quality)); + } + + @NonNull + @Override + public FallbackStrategy lowerQualityThan(@NonNull VideoQuality quality) { + return FallbackStrategy.lowerQualityThan(getNativeQuality(quality)); + } + + Quality getNativeQuality(VideoQuality quality) { + switch (quality) { + case SD: + return Quality.SD; + case HD: + return Quality.HD; + case FHD: + return Quality.FHD; + case UHD: + return Quality.UHD; + case LOWEST: + return Quality.LOWEST; + case HIGHEST: + return Quality.HIGHEST; + } + + throw new IllegalArgumentException( + "VideoQuality " + quality + " is unhandled by FallbackStrategyProxyApi."); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringActionBuilderProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringActionBuilderProxyApi.java new file mode 100644 index 000000000000..a19a33c01b0b --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringActionBuilderProxyApi.java @@ -0,0 +1,72 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.camera.core.FocusMeteringAction; +import androidx.camera.core.MeteringPoint; + +/** + * ProxyApi implementation for {@link FocusMeteringAction.Builder}. This class may handle + * instantiating native object instances that are attached to a Dart instance or handle method calls + * on the associated native class or an instance of that class. + */ +class FocusMeteringActionBuilderProxyApi extends PigeonApiFocusMeteringActionBuilder { + FocusMeteringActionBuilderProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public FocusMeteringAction.Builder pigeon_defaultConstructor(@NonNull MeteringPoint point) { + return new FocusMeteringAction.Builder(point); + } + + @NonNull + @Override + public FocusMeteringAction.Builder withMode( + @NonNull MeteringPoint point, @NonNull MeteringMode mode) { + return new FocusMeteringAction.Builder(point, getNativeMeteringMode(mode)); + } + + @Override + public void addPoint(FocusMeteringAction.Builder pigeonInstance, @NonNull MeteringPoint point) { + pigeonInstance.addPoint(point); + } + + @Override + public void addPointWithMode( + FocusMeteringAction.Builder pigeonInstance, + @NonNull MeteringPoint point, + @NonNull MeteringMode mode) { + pigeonInstance.addPoint(point, getNativeMeteringMode(mode)); + } + + @Override + public void disableAutoCancel(FocusMeteringAction.Builder pigeonInstance) { + pigeonInstance.disableAutoCancel(); + } + + @NonNull + @Override + public androidx.camera.core.FocusMeteringAction build( + FocusMeteringAction.Builder pigeonInstance) { + return pigeonInstance.build(); + } + + int getNativeMeteringMode(@NonNull MeteringMode mode) { + switch (mode) { + case AE: + return FocusMeteringAction.FLAG_AE; + case AF: + return FocusMeteringAction.FLAG_AF; + case AWB: + return FocusMeteringAction.FLAG_AWB; + } + + throw new IllegalArgumentException( + "MeteringMode " + mode + " is unhandled by FocusMeteringActionBuilderProxyApi."); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringActionHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringActionHostApiImpl.java deleted file mode 100644 index dcda333c2e90..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringActionHostApiImpl.java +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.VisibleForTesting; -import androidx.camera.core.FocusMeteringAction; -import androidx.camera.core.MeteringPoint; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.FocusMeteringActionHostApi; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.MeteringPointInfo; -import java.util.ArrayList; -import java.util.List; - -/** - * Host API implementation for {@link FocusMeteringAction}. - * - *

This class may handle instantiating and adding native object instances that are attached to a - * Dart instance or handle method calls on the associated native class or an instance of the class. - */ -public class FocusMeteringActionHostApiImpl implements FocusMeteringActionHostApi { - private final InstanceManager instanceManager; - - private final FocusMeteringActionProxy proxy; - - /** Proxy for constructor of {@link FocusMeteringAction}. */ - @VisibleForTesting - public static class FocusMeteringActionProxy { - /** Creates an instance of {@link FocusMeteringAction}. */ - public @NonNull FocusMeteringAction create( - @NonNull List meteringPoints, - @NonNull List meteringPointModes, - @Nullable Boolean disableAutoCancel) { - if (meteringPoints.size() >= 1 && meteringPoints.size() != meteringPointModes.size()) { - throw new IllegalArgumentException( - "One metering point must be specified and the number of specified metering points must match the number of specified metering point modes."); - } - - FocusMeteringAction.Builder focusMeteringActionBuilder; - - // Create builder to potentially add more MeteringPoints to. - MeteringPoint firstMeteringPoint = meteringPoints.get(0); - Integer firstMeteringPointMode = meteringPointModes.get(0); - if (firstMeteringPointMode == null) { - focusMeteringActionBuilder = getFocusMeteringActionBuilder(firstMeteringPoint); - } else { - focusMeteringActionBuilder = - getFocusMeteringActionBuilder(firstMeteringPoint, firstMeteringPointMode); - } - - // Add any additional metering points in order as specified by input lists. - for (int i = 1; i < meteringPoints.size(); i++) { - MeteringPoint meteringPoint = meteringPoints.get(i); - Integer meteringMode = meteringPointModes.get(i); - - if (meteringMode == null) { - focusMeteringActionBuilder.addPoint(meteringPoint); - } else { - focusMeteringActionBuilder.addPoint(meteringPoint, meteringMode); - } - } - - if (disableAutoCancel != null && disableAutoCancel == true) { - focusMeteringActionBuilder.disableAutoCancel(); - } - - return focusMeteringActionBuilder.build(); - } - - @VisibleForTesting - @NonNull - public FocusMeteringAction.Builder getFocusMeteringActionBuilder( - @NonNull MeteringPoint meteringPoint) { - return new FocusMeteringAction.Builder(meteringPoint); - } - - @VisibleForTesting - @NonNull - public FocusMeteringAction.Builder getFocusMeteringActionBuilder( - @NonNull MeteringPoint meteringPoint, int meteringMode) { - return new FocusMeteringAction.Builder(meteringPoint, meteringMode); - } - } - - /** - * Constructs a {@link FocusMeteringActionHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - */ - public FocusMeteringActionHostApiImpl(@NonNull InstanceManager instanceManager) { - this(instanceManager, new FocusMeteringActionProxy()); - } - - /** - * Constructs a {@link FocusMeteringActionHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - * @param proxy proxy for constructor of {@link FocusMeteringAction} - */ - FocusMeteringActionHostApiImpl( - @NonNull InstanceManager instanceManager, @NonNull FocusMeteringActionProxy proxy) { - this.instanceManager = instanceManager; - this.proxy = proxy; - } - - @Override - public void create( - @NonNull Long identifier, - @NonNull List meteringPointInfos, - @Nullable Boolean disableAutoCancel) { - final List meteringPoints = new ArrayList(); - final List meteringPointModes = new ArrayList(); - for (MeteringPointInfo meteringPointInfo : meteringPointInfos) { - meteringPoints.add(instanceManager.getInstance(meteringPointInfo.getMeteringPointId())); - Long meteringPointMode = meteringPointInfo.getMeteringMode(); - meteringPointModes.add(meteringPointMode == null ? null : meteringPointMode.intValue()); - } - - instanceManager.addDartCreatedInstance( - proxy.create(meteringPoints, meteringPointModes, disableAutoCancel), identifier); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringActionProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringActionProxyApi.java new file mode 100644 index 000000000000..cd38caecef74 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringActionProxyApi.java @@ -0,0 +1,46 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.camera.core.FocusMeteringAction; +import androidx.camera.core.MeteringPoint; +import java.util.List; + +/** + * ProxyApi implementation for {@link FocusMeteringAction}. This class may handle instantiating + * native object instances that are attached to a Dart instance or handle method calls on the + * associated native class or an instance of that class. + */ +class FocusMeteringActionProxyApi extends PigeonApiFocusMeteringAction { + FocusMeteringActionProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public List meteringPointsAe(FocusMeteringAction pigeonInstance) { + return pigeonInstance.getMeteringPointsAe(); + } + + @NonNull + @Override + public List meteringPointsAf( + FocusMeteringAction pigeonInstance) { + return pigeonInstance.getMeteringPointsAf(); + } + + @NonNull + @Override + public List meteringPointsAwb( + FocusMeteringAction pigeonInstance) { + return pigeonInstance.getMeteringPointsAwb(); + } + + @Override + public boolean isAutoCancelEnabled(FocusMeteringAction pigeonInstance) { + return pigeonInstance.isAutoCancelEnabled(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringResultFlutterApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringResultFlutterApiImpl.java deleted file mode 100644 index 3c0ed4c4482a..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringResultFlutterApiImpl.java +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.annotation.VisibleForTesting; -import androidx.camera.core.FocusMeteringResult; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.FocusMeteringResultFlutterApi; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.FocusMeteringResultFlutterApi.Reply; - -/** - * Flutter API implementation for {@link FocusMeteringResult}. - * - *

This class may handle adding native instances that are attached to a Dart instance or passing - * arguments of callbacks methods to a Dart instance. - */ -public class FocusMeteringResultFlutterApiImpl { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - private FocusMeteringResultFlutterApi focusMeteringResultFlutterApi; - - /** - * Constructs a {@link FocusMeteringResultFlutterApiImpl}. - * - * @param binaryMessenger used to communicate with Dart over asynchronous messages - * @param instanceManager maintains instances stored to communicate with attached Dart objects - */ - public FocusMeteringResultFlutterApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - focusMeteringResultFlutterApi = new FocusMeteringResultFlutterApi(binaryMessenger); - } - - /** - * Stores the {@link FocusMeteringResult} instance and notifies Dart to create and store a new - * {@link FocusMeteringResult} instance that is attached to this one. If {@code instance} has - * already been added, this method does nothing. - */ - public void create(@NonNull FocusMeteringResult instance, @NonNull Reply callback) { - if (!instanceManager.containsInstance(instance)) { - focusMeteringResultFlutterApi.create( - instanceManager.addHostCreatedInstance(instance), callback); - } - } - - /** Sets the Flutter API used to send messages to Dart. */ - @VisibleForTesting - void setApi(@NonNull FocusMeteringResultFlutterApi api) { - this.focusMeteringResultFlutterApi = api; - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringResultHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringResultHostApiImpl.java deleted file mode 100644 index de4640347604..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringResultHostApiImpl.java +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.annotation.VisibleForTesting; -import androidx.camera.core.FocusMeteringResult; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.FocusMeteringResultHostApi; - -/** - * Host API implementation for {@link FocusMeteringResult}. - * - *

This class may handle instantiating and adding native object instances that are attached to a - * Dart instance or handle method calls on the associated native class or an instance of the class. - */ -public class FocusMeteringResultHostApiImpl implements FocusMeteringResultHostApi { - private final InstanceManager instanceManager; - - private final FocusMeteringResultProxy proxy; - - /** Proxy for methods of {@link FocusMeteringResult}. */ - @VisibleForTesting - public static class FocusMeteringResultProxy { - - /** - * Returns whether or not auto focus was successful. - * - *

If the current camera does not support auto focus, it will return true. If auto focus is - * not requested, it will return false. - */ - @NonNull - public Boolean isFocusSuccessful(@NonNull FocusMeteringResult focusMeteringResult) { - return focusMeteringResult.isFocusSuccessful(); - } - } - - /** - * Constructs a {@link FocusMeteringResultHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - */ - public FocusMeteringResultHostApiImpl(@NonNull InstanceManager instanceManager) { - this(instanceManager, new FocusMeteringResultProxy()); - } - - /** - * Constructs a {@link FocusMeteringResultHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - * @param proxy proxy for methods of {@link FocusMeteringResult} - */ - FocusMeteringResultHostApiImpl( - @NonNull InstanceManager instanceManager, @NonNull FocusMeteringResultProxy proxy) { - this.instanceManager = instanceManager; - this.proxy = proxy; - } - - @Override - @NonNull - public Boolean isFocusSuccessful(@NonNull Long identifier) { - return proxy.isFocusSuccessful(instanceManager.getInstance(identifier)); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringResultProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringResultProxyApi.java new file mode 100644 index 000000000000..2da7efc2f3f6 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/FocusMeteringResultProxyApi.java @@ -0,0 +1,24 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.camera.core.FocusMeteringResult; + +/** + * ProxyApi implementation for {@link FocusMeteringResult}. This class may handle instantiating + * native object instances that are attached to a Dart instance or handle method calls on the + * associated native class or an instance of that class. + */ +class FocusMeteringResultProxyApi extends PigeonApiFocusMeteringResult { + FocusMeteringResultProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @Override + public boolean isFocusSuccessful(FocusMeteringResult pigeonInstance) { + return pigeonInstance.isFocusSuccessful(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageAnalysisHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageAnalysisHostApiImpl.java deleted file mode 100644 index 8774adc9def7..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageAnalysisHostApiImpl.java +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import android.content.Context; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.VisibleForTesting; -import androidx.camera.core.ImageAnalysis; -import androidx.camera.core.resolutionselector.ResolutionSelector; -import androidx.core.content.ContextCompat; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ImageAnalysisHostApi; -import java.util.Objects; - -public class ImageAnalysisHostApiImpl implements ImageAnalysisHostApi { - - private InstanceManager instanceManager; - private BinaryMessenger binaryMessenger; - @Nullable private Context context; - - @VisibleForTesting @NonNull public CameraXProxy cameraXProxy = new CameraXProxy(); - - public ImageAnalysisHostApiImpl( - @NonNull BinaryMessenger binaryMessenger, - @NonNull InstanceManager instanceManager, - @NonNull Context context) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - this.context = context; - } - - /** - * Sets the context that will be used to run an {@link ImageAnalysis.Analyzer} on the main thread. - */ - public void setContext(@NonNull Context context) { - this.context = context; - } - - /** Creates an {@link ImageAnalysis} instance with the target resolution if specified. */ - @Override - public void create( - @NonNull Long identifier, @Nullable Long rotation, @Nullable Long resolutionSelectorId) { - ImageAnalysis.Builder imageAnalysisBuilder = cameraXProxy.createImageAnalysisBuilder(); - - if (rotation != null) { - imageAnalysisBuilder.setTargetRotation(rotation.intValue()); - } - if (resolutionSelectorId != null) { - ResolutionSelector resolutionSelector = - Objects.requireNonNull(instanceManager.getInstance(resolutionSelectorId)); - imageAnalysisBuilder.setResolutionSelector(resolutionSelector); - } - - ImageAnalysis imageAnalysis = imageAnalysisBuilder.build(); - instanceManager.addDartCreatedInstance(imageAnalysis, identifier); - } - - /** - * Sets {@link ImageAnalysis.Analyzer} instance with specified {@code analyzerIdentifier} on the - * {@link ImageAnalysis} instance with the specified {@code identifier} to receive and analyze - * images. - */ - @Override - public void setAnalyzer(@NonNull Long identifier, @NonNull Long analyzerIdentifier) { - if (context == null) { - throw new IllegalStateException("Context must be set to set an Analyzer."); - } - - // Shorten time interval used to define how often the instanceManager removes garbage - // collected weak references to native Android objects that it manages in order to - // account for the increased memory usage that comes from analyzing images with an - // ImageAnalysis.Analyzer. - instanceManager.setClearFinalizedWeakReferencesInterval( - InstanceManager.CLEAR_FINALIZED_WEAK_REFERENCES_INTERVAL_FOR_IMAGE_ANALYSIS); - instanceManager.releaseAllFinalizedInstances(); - - getImageAnalysisInstance(identifier) - .setAnalyzer( - ContextCompat.getMainExecutor(context), - Objects.requireNonNull(instanceManager.getInstance(analyzerIdentifier))); - } - - /** Clears any analyzer previously set on the specified {@link ImageAnalysis} instance. */ - @Override - public void clearAnalyzer(@NonNull Long identifier) { - ImageAnalysis imageAnalysis = - (ImageAnalysis) Objects.requireNonNull(instanceManager.getInstance(identifier)); - imageAnalysis.clearAnalyzer(); - - // Restore the default time interval used to define how often the instanceManager - // removes garbage collected weak references to native Android objects that it - // manages since analyzing images with an ImageAnalysis.Analyzer, which involves - // increased memory usage, is finished. - instanceManager.setClearFinalizedWeakReferencesInterval( - InstanceManager.DEFAULT_CLEAR_FINALIZED_WEAK_REFERENCES_INTERVAL); - } - - /** Dynamically sets the target rotation of the {@link ImageAnalysis}. */ - @Override - public void setTargetRotation(@NonNull Long identifier, @NonNull Long rotation) { - ImageAnalysis imageAnalysis = getImageAnalysisInstance(identifier); - imageAnalysis.setTargetRotation(rotation.intValue()); - } - - /** - * Retrieives the {@link ImageAnalysis} instance associated with the specified {@code identifier}. - */ - private ImageAnalysis getImageAnalysisInstance(@NonNull Long identifier) { - return Objects.requireNonNull(instanceManager.getInstance(identifier)); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageAnalysisProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageAnalysisProxyApi.java new file mode 100644 index 000000000000..8d5efdd05e44 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageAnalysisProxyApi.java @@ -0,0 +1,75 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.camera.core.ImageAnalysis; +import androidx.camera.core.resolutionselector.ResolutionSelector; +import androidx.core.content.ContextCompat; + +/** + * ProxyApi implementation for {@link ImageAnalysis}. This class may handle instantiating native + * object instances that are attached to a Dart instance or handle method calls on the associated + * native class or an instance of that class. + */ +class ImageAnalysisProxyApi extends PigeonApiImageAnalysis { + static final long CLEAR_FINALIZED_WEAK_REFERENCES_INTERVAL_FOR_IMAGE_ANALYSIS = 1000; + + @NonNull + @Override + public ImageAnalysis pigeon_defaultConstructor( + @Nullable ResolutionSelector resolutionSelector, @Nullable Long targetRotation) { + final ImageAnalysis.Builder builder = new ImageAnalysis.Builder(); + if (resolutionSelector != null) { + builder.setResolutionSelector(resolutionSelector); + } + if (targetRotation != null) { + builder.setTargetRotation(targetRotation.intValue()); + } + return builder.build(); + } + + ImageAnalysisProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public ProxyApiRegistrar getPigeonRegistrar() { + return (ProxyApiRegistrar) super.getPigeonRegistrar(); + } + + @Override + public void setAnalyzer( + ImageAnalysis pigeonInstance, @NonNull androidx.camera.core.ImageAnalysis.Analyzer analyzer) { + getPigeonRegistrar() + .getInstanceManager() + .setClearFinalizedWeakReferencesInterval( + CLEAR_FINALIZED_WEAK_REFERENCES_INTERVAL_FOR_IMAGE_ANALYSIS); + pigeonInstance.setAnalyzer( + ContextCompat.getMainExecutor(getPigeonRegistrar().getContext()), analyzer); + } + + @Override + public void clearAnalyzer(ImageAnalysis pigeonInstance) { + pigeonInstance.clearAnalyzer(); + getPigeonRegistrar() + .getInstanceManager() + .setClearFinalizedWeakReferencesInterval( + getPigeonRegistrar().getDefaultClearFinalizedWeakReferencesInterval()); + } + + @Override + public void setTargetRotation(ImageAnalysis pigeonInstance, long rotation) { + pigeonInstance.setTargetRotation((int) rotation); + } + + @Nullable + @Override + public ResolutionSelector resolutionSelector(@NonNull ImageAnalysis pigeonInstance) { + return pigeonInstance.getResolutionSelector(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageCaptureHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageCaptureHostApiImpl.java deleted file mode 100644 index 8e2e6f7291a5..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageCaptureHostApiImpl.java +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import android.content.Context; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.VisibleForTesting; -import androidx.camera.core.ImageCapture; -import androidx.camera.core.ImageCaptureException; -import androidx.camera.core.resolutionselector.ResolutionSelector; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ImageCaptureHostApi; -import java.io.File; -import java.io.IOException; -import java.util.Objects; -import java.util.concurrent.Executors; - -public class ImageCaptureHostApiImpl implements ImageCaptureHostApi { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - - @Nullable private Context context; - private SystemServicesFlutterApiImpl systemServicesFlutterApiImpl; - - public static final String TEMPORARY_FILE_NAME = "CAP"; - public static final String JPG_FILE_TYPE = ".jpg"; - - @VisibleForTesting public @NonNull CameraXProxy cameraXProxy = new CameraXProxy(); - - public ImageCaptureHostApiImpl( - @NonNull BinaryMessenger binaryMessenger, - @NonNull InstanceManager instanceManager, - @NonNull Context context) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - this.context = context; - } - - /** - * Sets the context that the {@link ImageCapture} will use to find a location to save a captured - * image. - */ - public void setContext(@NonNull Context context) { - this.context = context; - } - - /** - * Creates an {@link ImageCapture} with the requested flash mode and target resolution if - * specified. - */ - @Override - public void create( - @NonNull Long identifier, - @Nullable Long rotation, - @Nullable Long flashMode, - @Nullable Long resolutionSelectorId) { - ImageCapture.Builder imageCaptureBuilder = cameraXProxy.createImageCaptureBuilder(); - - if (rotation != null) { - imageCaptureBuilder.setTargetRotation(rotation.intValue()); - } - if (flashMode != null) { - // This sets the requested flash mode, but may fail silently. - imageCaptureBuilder.setFlashMode(flashMode.intValue()); - } - if (resolutionSelectorId != null) { - ResolutionSelector resolutionSelector = - Objects.requireNonNull(instanceManager.getInstance(resolutionSelectorId)); - imageCaptureBuilder.setResolutionSelector(resolutionSelector); - } - - ImageCapture imageCapture = imageCaptureBuilder.build(); - instanceManager.addDartCreatedInstance(imageCapture, identifier); - } - - /** Sets the flash mode of the {@link ImageCapture} instance with the specified identifier. */ - @Override - public void setFlashMode(@NonNull Long identifier, @NonNull Long flashMode) { - ImageCapture imageCapture = getImageCaptureInstance(identifier); - imageCapture.setFlashMode(flashMode.intValue()); - } - - /** Captures a still image and uses the result to return its absolute path in memory. */ - @Override - public void takePicture( - @NonNull Long identifier, @NonNull GeneratedCameraXLibrary.Result result) { - if (context == null) { - throw new IllegalStateException("Context must be set to take picture."); - } - - ImageCapture imageCapture = getImageCaptureInstance(identifier); - final File outputDir = context.getCacheDir(); - File temporaryCaptureFile; - try { - temporaryCaptureFile = File.createTempFile(TEMPORARY_FILE_NAME, JPG_FILE_TYPE, outputDir); - } catch (IOException | SecurityException e) { - result.error(e); - return; - } - - ImageCapture.OutputFileOptions outputFileOptions = - cameraXProxy.createImageCaptureOutputFileOptions(temporaryCaptureFile); - ImageCapture.OnImageSavedCallback onImageSavedCallback = - createOnImageSavedCallback(temporaryCaptureFile, result); - - imageCapture.takePicture( - outputFileOptions, Executors.newSingleThreadExecutor(), onImageSavedCallback); - } - - /** Creates a callback used when saving a captured image. */ - @VisibleForTesting - public @NonNull ImageCapture.OnImageSavedCallback createOnImageSavedCallback( - @NonNull File file, @NonNull GeneratedCameraXLibrary.Result result) { - return new ImageCapture.OnImageSavedCallback() { - @Override - public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) { - result.success(file.getAbsolutePath()); - } - - @Override - public void onError(@NonNull ImageCaptureException exception) { - result.error(exception); - } - }; - } - - /** Dynamically sets the target rotation of the {@link ImageCapture}. */ - @Override - public void setTargetRotation(@NonNull Long identifier, @NonNull Long rotation) { - ImageCapture imageCapture = getImageCaptureInstance(identifier); - imageCapture.setTargetRotation(rotation.intValue()); - } - - /** - * Retrieves the {@link ImageCapture} instance associated with the specified {@code identifier}. - */ - private ImageCapture getImageCaptureInstance(@NonNull Long identifier) { - return Objects.requireNonNull(instanceManager.getInstance(identifier)); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageCaptureProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageCaptureProxyApi.java new file mode 100644 index 000000000000..a0970da5b335 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageCaptureProxyApi.java @@ -0,0 +1,137 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.camera.core.ImageCapture; +import androidx.camera.core.ImageCaptureException; +import androidx.camera.core.resolutionselector.ResolutionSelector; +import java.io.File; +import java.io.IOException; +import java.util.concurrent.Executors; +import kotlin.Result; +import kotlin.Unit; +import kotlin.jvm.functions.Function1; + +/** + * ProxyApi implementation for {@link ImageCapture}. This class may handle instantiating native + * object instances that are attached to a Dart instance or handle method calls on the associated + * native class or an instance of that class. + */ +class ImageCaptureProxyApi extends PigeonApiImageCapture { + static final String TEMPORARY_FILE_NAME = "CAP"; + static final String JPG_FILE_TYPE = ".jpg"; + + ImageCaptureProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public ProxyApiRegistrar getPigeonRegistrar() { + return (ProxyApiRegistrar) super.getPigeonRegistrar(); + } + + @NonNull + @Override + public ImageCapture pigeon_defaultConstructor( + @Nullable androidx.camera.core.resolutionselector.ResolutionSelector resolutionSelector, + @Nullable Long targetRotation, + @Nullable CameraXFlashMode flashMode) { + final ImageCapture.Builder builder = new ImageCapture.Builder(); + if (targetRotation != null) { + builder.setTargetRotation(targetRotation.intValue()); + } + if (flashMode != null) { + // This sets the requested flash mode, but may fail silently. + switch (flashMode) { + case AUTO: + builder.setFlashMode(ImageCapture.FLASH_MODE_AUTO); + break; + case OFF: + builder.setFlashMode(ImageCapture.FLASH_MODE_OFF); + break; + case ON: + builder.setFlashMode(ImageCapture.FLASH_MODE_ON); + break; + } + } + if (resolutionSelector != null) { + builder.setResolutionSelector(resolutionSelector); + } + return builder.build(); + } + + @Override + public void setFlashMode( + @NonNull ImageCapture pigeonInstance, @NonNull CameraXFlashMode flashMode) { + int nativeFlashMode = -1; + switch (flashMode) { + case AUTO: + nativeFlashMode = ImageCapture.FLASH_MODE_AUTO; + break; + case OFF: + nativeFlashMode = ImageCapture.FLASH_MODE_OFF; + break; + case ON: + nativeFlashMode = ImageCapture.FLASH_MODE_ON; + } + pigeonInstance.setFlashMode(nativeFlashMode); + } + + @Override + public void takePicture( + @NonNull ImageCapture pigeonInstance, + @NonNull Function1, Unit> callback) { + final File outputDir = getPigeonRegistrar().getContext().getCacheDir(); + File temporaryCaptureFile; + try { + temporaryCaptureFile = File.createTempFile(TEMPORARY_FILE_NAME, JPG_FILE_TYPE, outputDir); + } catch (IOException | SecurityException e) { + ResultCompat.failure(e, callback); + return; + } + + final ImageCapture.OutputFileOptions outputFileOptions = + createImageCaptureOutputFileOptions(temporaryCaptureFile); + final ImageCapture.OnImageSavedCallback onImageSavedCallback = + createOnImageSavedCallback(temporaryCaptureFile, callback); + + pigeonInstance.takePicture( + outputFileOptions, Executors.newSingleThreadExecutor(), onImageSavedCallback); + } + + @Override + public void setTargetRotation(ImageCapture pigeonInstance, long rotation) { + pigeonInstance.setTargetRotation((int) rotation); + } + + @Nullable + @Override + public ResolutionSelector resolutionSelector(@NonNull ImageCapture pigeonInstance) { + return pigeonInstance.getResolutionSelector(); + } + + ImageCapture.OutputFileOptions createImageCaptureOutputFileOptions(@NonNull File file) { + return new ImageCapture.OutputFileOptions.Builder(file).build(); + } + + @NonNull + ImageCapture.OnImageSavedCallback createOnImageSavedCallback( + @NonNull File file, @NonNull Function1, Unit> callback) { + return new ImageCapture.OnImageSavedCallback() { + @Override + public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) { + ResultCompat.success(file.getAbsolutePath(), callback); + } + + @Override + public void onError(@NonNull ImageCaptureException exception) { + ResultCompat.failure(exception, callback); + } + }; + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageProxyFlutterApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageProxyFlutterApiImpl.java deleted file mode 100644 index 0ad569973fd8..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageProxyFlutterApiImpl.java +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.annotation.VisibleForTesting; -import androidx.camera.core.ImageProxy; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ImageProxyFlutterApi; - -/** - * Flutter API implementation for {@link ImageProxy}. - * - *

This class may handle adding native instances that are attached to a Dart instance or passing - * arguments of callbacks methods to a Dart instance. - */ -public class ImageProxyFlutterApiImpl { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - private ImageProxyFlutterApi api; - - /** - * Constructs a {@link ImageProxyFlutterApiImpl}. - * - * @param binaryMessenger used to communicate with Dart over asynchronous messages - * @param instanceManager maintains instances stored to communicate with attached Dart objects - */ - public ImageProxyFlutterApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - api = new ImageProxyFlutterApi(binaryMessenger); - } - - /** - * Stores the {@link ImageProxy} instance and notifies Dart to create and store a new {@link - * ImageProxy} instance that is attached to this one. If {@code instance} has already been added, - * this method does nothing. - */ - public void create( - @NonNull ImageProxy instance, - @NonNull Long imageFormat, - @NonNull Long imageHeight, - @NonNull Long imageWidth, - @NonNull ImageProxyFlutterApi.Reply callback) { - if (!instanceManager.containsInstance(instance)) { - api.create( - instanceManager.addHostCreatedInstance(instance), - imageFormat, - imageHeight, - imageWidth, - callback); - } - } - - /** - * Sets the Flutter API used to send messages to Dart. - * - *

This is only visible for testing. - */ - @VisibleForTesting - void setApi(@NonNull ImageProxyFlutterApi api) { - this.api = api; - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageProxyHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageProxyHostApiImpl.java deleted file mode 100644 index ad34c6ed8d06..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageProxyHostApiImpl.java +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.annotation.VisibleForTesting; -import androidx.camera.core.ImageProxy; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ImageProxyHostApi; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -/** - * Host API implementation for {@link ImageProxy}. - * - *

This class may handle instantiating and adding native object instances that are attached to a - * Dart instance or handle method calls on the associated native class or an instance of the class. - */ -public class ImageProxyHostApiImpl implements ImageProxyHostApi { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - - @VisibleForTesting @NonNull public CameraXProxy cameraXProxy = new CameraXProxy(); - - @VisibleForTesting @NonNull public PlaneProxyFlutterApiImpl planeProxyFlutterApiImpl; - - /** - * Constructs a {@link ImageProxyHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - */ - public ImageProxyHostApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - planeProxyFlutterApiImpl = new PlaneProxyFlutterApiImpl(binaryMessenger, instanceManager); - } - - /** - * Returns the array of identifiers for planes of the {@link ImageProxy} instance with the - * specified identifier. - */ - @Override - @NonNull - public List getPlanes(@NonNull Long identifier) { - ImageProxy.PlaneProxy[] planes = getImageProxyInstance(identifier).getPlanes(); - List planeIdentifiers = new ArrayList(); - - for (ImageProxy.PlaneProxy plane : planes) { - ByteBuffer byteBuffer = plane.getBuffer(); - byte[] bytes = cameraXProxy.getBytesFromBuffer(byteBuffer.remaining()); - byteBuffer.get(bytes, 0, bytes.length); - Long pixelStride = Long.valueOf(plane.getPixelStride()); - Long rowStride = Long.valueOf(plane.getRowStride()); - - planeProxyFlutterApiImpl.create(plane, bytes, pixelStride, rowStride, reply -> {}); - planeIdentifiers.add(instanceManager.getIdentifierForStrongReference(plane)); - } - - return planeIdentifiers; - } - - /** - * Closes the {@link androidx.camera.core.Image} instance associated with the {@link ImageProxy} - * instance with the specified identifier. - */ - @Override - public void close(@NonNull Long identifier) { - getImageProxyInstance(identifier).close(); - } - - /** - * Retrieives the {@link ImageProxy} instance associated with the specified {@code identifier}. - */ - private ImageProxy getImageProxyInstance(@NonNull Long identifier) { - return Objects.requireNonNull(instanceManager.getInstance(identifier)); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageProxyProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageProxyProxyApi.java new file mode 100644 index 000000000000..2620f4c0981d --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ImageProxyProxyApi.java @@ -0,0 +1,48 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.camera.core.ImageProxy; +import androidx.camera.core.ImageProxy.PlaneProxy; +import java.util.Arrays; +import java.util.List; + +/** + * ProxyApi implementation for {@link ImageProxy}. This class may handle instantiating native object + * instances that are attached to a Dart instance or handle method calls on the associated native + * class or an instance of that class. + */ +class ImageProxyProxyApi extends PigeonApiImageProxy { + ImageProxyProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @Override + public long format(ImageProxy pigeonInstance) { + return pigeonInstance.getFormat(); + } + + @Override + public long width(ImageProxy pigeonInstance) { + return pigeonInstance.getWidth(); + } + + @Override + public long height(ImageProxy pigeonInstance) { + return pigeonInstance.getHeight(); + } + + @NonNull + @Override + public List getPlanes(ImageProxy pigeonInstance) { + return Arrays.asList(pigeonInstance.getPlanes()); + } + + @Override + public void close(ImageProxy pigeonInstance) { + pigeonInstance.close(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/InstanceManager.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/InstanceManager.java deleted file mode 100644 index a8a25daa1fab..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/InstanceManager.java +++ /dev/null @@ -1,287 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import android.os.Handler; -import android.os.Looper; -import android.util.Log; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import java.lang.ref.ReferenceQueue; -import java.lang.ref.WeakReference; -import java.util.HashMap; -import java.util.WeakHashMap; - -/** - * Maintains instances used to communicate with the corresponding objects in Dart. - * - *

Objects stored in this container are represented by an object in Dart that is also stored in - * an InstanceManager with the same identifier. - * - *

When an instance is added with an identifier, either can be used to retrieve the other. - * - *

Added instances are added as a weak reference and a strong reference. When the strong - * reference is removed with `{@link #remove(long)}` and the weak reference is deallocated, the - * `finalizationListener` is made with the instance's identifier. However, if the strong reference - * is removed and then the identifier is retrieved with the intention to pass the identifier to Dart - * (e.g. calling {@link #getIdentifierForStrongReference(Object)}), the strong reference to the - * instance is recreated. The strong reference will then need to be removed manually again. - */ -@SuppressWarnings("unchecked") -public class InstanceManager { - // Identifiers are locked to a specific range to avoid collisions with objects - // created simultaneously from Dart. - // Host uses identifiers >= 2^16 and Dart is expected to use values n where, - // 0 <= n < 2^16. - private static final long MIN_HOST_CREATED_IDENTIFIER = 65536; - private static final String TAG = "InstanceManager"; - - /** - * The default time interval used to define how often this instance removes garbage collected weak - * references to native Android objects that this instance manages. - */ - public static final long DEFAULT_CLEAR_FINALIZED_WEAK_REFERENCES_INTERVAL = 3000; - - /** - * The time interval used to define how often this instance removes garbage collected weak - * references to native Android objects that this instance manages, specifically when an {@code - * ImageAnalysis.Analyzer} is set on an {@code ImageAnalysis} instance to support image streaming. - * - *

Streaming images with an {@code ImageAnalysis.Analyzer} involves increased memory usage, so - * this interval, which is lower than the default {@link - * DEFAULT_CLEAR_FINALIZED_WEAK_REFERENCES_INTERVAL} interval, accommodates this fact. - */ - public static final long CLEAR_FINALIZED_WEAK_REFERENCES_INTERVAL_FOR_IMAGE_ANALYSIS = 1000; - - /** Interface for listening when a weak reference of an instance is removed from the manager. */ - public interface FinalizationListener { - void onFinalize(long identifier); - } - - private final WeakHashMap identifiers = new WeakHashMap<>(); - private final HashMap> weakInstances = new HashMap<>(); - private final HashMap strongInstances = new HashMap<>(); - - private final ReferenceQueue referenceQueue = new ReferenceQueue<>(); - private final HashMap, Long> weakReferencesToIdentifiers = new HashMap<>(); - - private final Handler handler = new Handler(Looper.getMainLooper()); - - private final FinalizationListener finalizationListener; - - private long nextIdentifier = MIN_HOST_CREATED_IDENTIFIER; - private boolean hasFinalizationListenerStopped = false; - - private long clearFinalizedWeakReferencesInterval = - DEFAULT_CLEAR_FINALIZED_WEAK_REFERENCES_INTERVAL; - - /** - * Instantiate a new manager. - * - *

When the manager is no longer needed, {@link #stopFinalizationListener()} must be called. - * - * @param finalizationListener the listener for garbage collected weak references. - * @return a new `InstanceManager`. - */ - @NonNull - public static InstanceManager create(@NonNull FinalizationListener finalizationListener) { - return new InstanceManager(finalizationListener); - } - - private InstanceManager(FinalizationListener finalizationListener) { - this.finalizationListener = finalizationListener; - handler.postDelayed(this::releaseAllFinalizedInstances, clearFinalizedWeakReferencesInterval); - } - - /** - * Removes `identifier` and its associated strongly referenced instance, if present, from the - * manager. - * - * @param identifier the identifier paired to an instance. - * @param the expected return type. - * @return the removed instance if the manager contains the given identifier, otherwise `null` if - * the manager doesn't contain the value. - */ - @Nullable - public T remove(long identifier) { - logWarningIfFinalizationListenerHasStopped(); - return (T) strongInstances.remove(identifier); - } - - /** - * Retrieves the identifier paired with an instance. - * - *

If the manager contains a strong reference to `instance`, it will return the identifier - * associated with `instance`. If the manager contains only a weak reference to `instance`, a new - * strong reference to `instance` will be added and will need to be removed again with {@link - * #remove(long)}. - * - *

If this method returns a nonnull identifier, this method also expects the Dart - * `InstanceManager` to have, or recreate, a weak reference to the Dart instance the identifier is - * associated with. - * - * @param instance an instance that may be stored in the manager. - * @return the identifier associated with `instance` if the manager contains the value, otherwise - * `null` if the manager doesn't contain the value. - */ - @Nullable - public Long getIdentifierForStrongReference(@Nullable Object instance) { - logWarningIfFinalizationListenerHasStopped(); - - final Long identifier = identifiers.get(instance); - if (identifier != null) { - strongInstances.put(identifier, instance); - } - return identifier; - } - - /** - * Adds a new instance that was instantiated from Dart. - * - *

The same instance can be added multiple times, but each identifier must be unique. This - * allows two objects that are equivalent (e.g. the `equals` method returns true and their - * hashcodes are equal) to both be added. - * - * @param instance the instance to be stored. - * @param identifier the identifier to be paired with instance. This value must be >= 0 and - * unique. - */ - public void addDartCreatedInstance(@NonNull Object instance, long identifier) { - logWarningIfFinalizationListenerHasStopped(); - addInstance(instance, identifier); - } - - /** - * Adds a new instance that was instantiated from the host platform. - * - * @param instance the instance to be stored. This must be unique to all other added instances. - * @return the unique identifier (>= 0) stored with instance. - */ - public long addHostCreatedInstance(@NonNull Object instance) { - logWarningIfFinalizationListenerHasStopped(); - - if (containsInstance(instance)) { - throw new IllegalArgumentException( - "Instance of " + instance.getClass() + " has already been added."); - } - final long identifier = nextIdentifier++; - addInstance(instance, identifier); - return identifier; - } - - /** - * Retrieves the instance associated with identifier. - * - * @param identifier the identifier associated with an instance. - * @param the expected return type. - * @return the instance associated with `identifier` if the manager contains the value, otherwise - * `null` if the manager doesn't contain the value. - */ - @Nullable - public T getInstance(long identifier) { - logWarningIfFinalizationListenerHasStopped(); - - final WeakReference instance = (WeakReference) weakInstances.get(identifier); - if (instance != null) { - return instance.get(); - } - return null; - } - - /** - * Returns whether this manager contains the given `instance`. - * - * @param instance the instance whose presence in this manager is to be tested. - * @return whether this manager contains the given `instance`. - */ - public boolean containsInstance(@Nullable Object instance) { - logWarningIfFinalizationListenerHasStopped(); - return identifiers.containsKey(instance); - } - - /** - * Stop the periodic run of the {@link FinalizationListener} for instances that have been garbage - * collected. - * - *

The InstanceManager can continue to be used, but the {@link FinalizationListener} will no - * longer be called and methods will log a warning. - */ - public void stopFinalizationListener() { - handler.removeCallbacks(this::releaseAllFinalizedInstances); - hasFinalizationListenerStopped = true; - } - - /** - * Removes all of the instances from this manager. - * - *

The manager will be empty after this call returns. - */ - public void clear() { - identifiers.clear(); - weakInstances.clear(); - strongInstances.clear(); - weakReferencesToIdentifiers.clear(); - } - - /** - * Whether the {@link FinalizationListener} is still being called for instances that are garbage - * collected. - * - *

See {@link #stopFinalizationListener()}. - */ - public boolean hasFinalizationListenerStopped() { - return hasFinalizationListenerStopped; - } - - /** - * Modifies the time interval used to define how often this instance removes garbage collected - * weak references to native Android objects that this instance was managing. - */ - public void setClearFinalizedWeakReferencesInterval(long interval) { - clearFinalizedWeakReferencesInterval = interval; - } - - /** - * Releases garbage collected weak references to native Android objects that this instance was - * managing. - */ - public void releaseAllFinalizedInstances() { - if (hasFinalizationListenerStopped()) { - return; - } - - WeakReference reference; - while ((reference = (WeakReference) referenceQueue.poll()) != null) { - final Long identifier = weakReferencesToIdentifiers.remove(reference); - if (identifier != null) { - weakInstances.remove(identifier); - strongInstances.remove(identifier); - finalizationListener.onFinalize(identifier); - } - } - handler.postDelayed(this::releaseAllFinalizedInstances, clearFinalizedWeakReferencesInterval); - } - - private void addInstance(Object instance, long identifier) { - if (identifier < 0) { - throw new IllegalArgumentException(String.format("Identifier must be >= 0: %d", identifier)); - } - if (weakInstances.containsKey(identifier)) { - throw new IllegalArgumentException( - String.format("Identifier has already been added: %d", identifier)); - } - final WeakReference weakReference = new WeakReference<>(instance, referenceQueue); - identifiers.put(instance, identifier); - weakInstances.put(identifier, weakReference); - weakReferencesToIdentifiers.put(weakReference, identifier); - strongInstances.put(identifier, instance); - } - - private void logWarningIfFinalizationListenerHasStopped() { - if (hasFinalizationListenerStopped()) { - Log.w(TAG, "The manager was used after calls to the FinalizationListener have been stopped."); - } - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/JavaObjectHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/JavaObjectHostApiImpl.java deleted file mode 100644 index 538d4542cf4b..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/JavaObjectHostApiImpl.java +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.JavaObjectHostApi; - -/** - * A pigeon Host API implementation that handles creating {@link Object}s and invoking its static - * and instance methods. - * - *

{@link Object} instances created by {@link JavaObjectHostApiImpl} are used to intercommunicate - * with a paired Dart object. - */ -public class JavaObjectHostApiImpl implements JavaObjectHostApi { - private final InstanceManager instanceManager; - - /** - * Constructs a {@link JavaObjectHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with Dart objects - */ - public JavaObjectHostApiImpl(@NonNull InstanceManager instanceManager) { - this.instanceManager = instanceManager; - } - - @Override - public void dispose(@NonNull Long identifier) { - instanceManager.remove(identifier); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/LiveDataFlutterApiWrapper.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/LiveDataFlutterApiWrapper.java deleted file mode 100644 index 35af27ce6cc3..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/LiveDataFlutterApiWrapper.java +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.annotation.VisibleForTesting; -import androidx.lifecycle.LiveData; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.LiveDataFlutterApi; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.LiveDataSupportedType; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.LiveDataSupportedTypeData; - -/** - * Flutter API implementation for {@link LiveData}. - * - *

This class may handle adding native instances that are attached to a Dart instance or passing - * arguments of callbacks methods to a Dart instance. - */ -public class LiveDataFlutterApiWrapper { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - private LiveDataFlutterApi liveDataFlutterApi; - - /** - * Constructs a {@link LiveDataFlutterApiWrapper}. - * - * @param binaryMessenger used to communicate with Dart over asynchronous messages - * @param instanceManager maintains instances stored to communicate with attached Dart objects - */ - public LiveDataFlutterApiWrapper( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - liveDataFlutterApi = new LiveDataFlutterApi(binaryMessenger); - } - - /** - * Stores the {@link LiveData} instance and notifies Dart to create and store a new {@link - * LiveData} instance that is attached to this one. If {@code instance} has already been added, - * this method does nothing. - */ - public void create( - @NonNull LiveData instance, - @NonNull LiveDataSupportedType type, - @NonNull LiveDataFlutterApi.Reply callback) { - if (!instanceManager.containsInstance(instance)) { - liveDataFlutterApi.create( - instanceManager.addHostCreatedInstance(instance), - new LiveDataSupportedTypeData.Builder().setValue(type).build(), - callback); - } - } - - /** Sets the Flutter API used to send messages to Dart. */ - @VisibleForTesting - void setApi(@NonNull LiveDataFlutterApi api) { - this.liveDataFlutterApi = api; - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/LiveDataHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/LiveDataHostApiImpl.java deleted file mode 100644 index 3f7ec5125ec4..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/LiveDataHostApiImpl.java +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.camera.core.CameraState; -import androidx.camera.core.ZoomState; -import androidx.lifecycle.LifecycleOwner; -import androidx.lifecycle.LiveData; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.LiveDataHostApi; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.LiveDataSupportedType; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.LiveDataSupportedTypeData; -import java.util.Objects; - -/** - * Host API implementation for {@link LiveData}. - * - *

This class may handle instantiating and adding native object instances that are attached to a - * Dart instance or handle method calls on the associated native class or an instance of the class. - */ -public class LiveDataHostApiImpl implements LiveDataHostApi { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - @Nullable private LifecycleOwner lifecycleOwner; - - /** - * Constructs a {@link LiveDataHostApiImpl}. - * - * @param binaryMessenger used to communicate with Dart over asynchronous messages - * @param instanceManager maintains instances stored to communicate with attached Dart objects - */ - public LiveDataHostApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - } - - /** Sets {@link LifecycleOwner} used to observe the camera state if so requested. */ - public void setLifecycleOwner(@Nullable LifecycleOwner lifecycleOwner) { - this.lifecycleOwner = lifecycleOwner; - } - - /** - * Adds an {@link Observer} with the specified identifier to the observers list of this instance - * within the lifespan of the {@link lifecycleOwner}. - */ - @Override - @SuppressWarnings("unchecked") - public void observe(@NonNull Long identifier, @NonNull Long observerIdentifier) { - if (lifecycleOwner == null) { - throw new IllegalStateException("LifecycleOwner must be set to observe a LiveData instance."); - } - - getLiveDataInstance(identifier) - .observe( - lifecycleOwner, - Objects.requireNonNull(instanceManager.getInstance(observerIdentifier))); - } - - /** Removes all observers of this instance that are tied to the {@link lifecycleOwner}. */ - @Override - public void removeObservers(@NonNull Long identifier) { - if (lifecycleOwner == null) { - throw new IllegalStateException("LifecycleOwner must be set to remove LiveData observers."); - } - - getLiveDataInstance(identifier).removeObservers(lifecycleOwner); - } - - @Override - @Nullable - public Long getValue(@NonNull Long identifier, @NonNull LiveDataSupportedTypeData type) { - Object value = getLiveDataInstance(identifier).getValue(); - if (value == null) { - return null; - } - - LiveDataSupportedType valueType = type.getValue(); - switch (valueType) { - case CAMERA_STATE: - return createCameraState((CameraState) value); - case ZOOM_STATE: - return createZoomState((ZoomState) value); - default: - throw new IllegalArgumentException( - "The type of LiveData whose value was requested is not supported."); - } - } - - /** Creates a {@link CameraState} on the Dart side and returns its identifier. */ - private Long createCameraState(CameraState cameraState) { - new CameraStateFlutterApiWrapper(binaryMessenger, instanceManager) - .create( - cameraState, - CameraStateFlutterApiWrapper.getCameraStateType(cameraState.getType()), - cameraState.getError(), - reply -> {}); - return instanceManager.getIdentifierForStrongReference(cameraState); - } - - /** Creates a {@link ZoomState} on the Dart side and returns its identifiers. */ - private Long createZoomState(ZoomState zoomState) { - new ZoomStateFlutterApiImpl(binaryMessenger, instanceManager).create(zoomState, reply -> {}); - return instanceManager.getIdentifierForStrongReference(zoomState); - } - - /** Retrieves the {@link LiveData} instance that has the specified identifier. */ - private LiveData getLiveDataInstance(@NonNull Long identifier) { - return Objects.requireNonNull(instanceManager.getInstance(identifier)); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/LiveDataProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/LiveDataProxyApi.java new file mode 100644 index 000000000000..f018c458d8df --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/LiveDataProxyApi.java @@ -0,0 +1,81 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.lifecycle.LifecycleOwner; +import androidx.lifecycle.LiveData; +import androidx.lifecycle.Observer; + +/** + * ProxyApi implementation for {@link LiveData}. This class may handle instantiating native object + * instances that are attached to a Dart instance or handle method calls on the associated native + * class or an instance of that class. + */ +public class LiveDataProxyApi extends PigeonApiLiveData { + public static class LiveDataWrapper { + private final LiveData liveData; + private final LiveDataSupportedType genericType; + + LiveDataWrapper(@NonNull LiveData liveData, @NonNull LiveDataSupportedType genericType) { + this.liveData = liveData; + this.genericType = genericType; + } + + @NonNull + public LiveData getLiveData() { + return liveData; + } + + @NonNull + public LiveDataSupportedType getGenericType() { + return genericType; + } + } + + LiveDataProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public ProxyApiRegistrar getPigeonRegistrar() { + return (ProxyApiRegistrar) super.getPigeonRegistrar(); + } + + @NonNull + @Override + public LiveDataSupportedType type(@NonNull LiveDataWrapper pigeonInstance) { + return pigeonInstance.getGenericType(); + } + + @SuppressWarnings("unchecked") + @Override + public void observe(@NonNull LiveDataWrapper pigeonInstance, @NonNull Observer observer) { + final LifecycleOwner lifecycleOwner = getPigeonRegistrar().getLifecycleOwner(); + if (lifecycleOwner == null) { + throw new IllegalStateException("LifecycleOwner must be set to observe a LiveData instance."); + } + + final LiveData castedLiveData = (LiveData) pigeonInstance.getLiveData(); + castedLiveData.observe(lifecycleOwner, (Observer) observer); + } + + @Override + public void removeObservers(@NonNull LiveDataWrapper pigeonInstance) { + if (getPigeonRegistrar().getLifecycleOwner() == null) { + throw new IllegalStateException("LifecycleOwner must be set to remove LiveData observers."); + } + + pigeonInstance.getLiveData().removeObservers(getPigeonRegistrar().getLifecycleOwner()); + } + + @Nullable + @Override + public Object getValue(@NonNull LiveDataWrapper pigeonInstance) { + return pigeonInstance.getLiveData().getValue(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/MeteringPointFactoryProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/MeteringPointFactoryProxyApi.java new file mode 100644 index 000000000000..979ee6d2a2dc --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/MeteringPointFactoryProxyApi.java @@ -0,0 +1,33 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.camera.core.MeteringPoint; +import androidx.camera.core.MeteringPointFactory; + +/** + * ProxyApi implementation for {@link MeteringPointFactory}. This class may handle instantiating + * native object instances that are attached to a Dart instance or handle method calls on the + * associated native class or an instance of that class. + */ +class MeteringPointFactoryProxyApi extends PigeonApiMeteringPointFactory { + MeteringPointFactoryProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public MeteringPoint createPoint(MeteringPointFactory pigeonInstance, double x, double y) { + return pigeonInstance.createPoint((float) x, (float) y); + } + + @NonNull + @Override + public MeteringPoint createPointWithSize( + MeteringPointFactory pigeonInstance, double x, double y, double size) { + return pigeonInstance.createPoint((float) x, (float) y, (float) size); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/MeteringPointHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/MeteringPointHostApiImpl.java deleted file mode 100644 index a8775ebb2278..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/MeteringPointHostApiImpl.java +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import android.app.Activity; -import android.content.Context; -import android.os.Build; -import android.view.Display; -import android.view.WindowManager; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.VisibleForTesting; -import androidx.camera.core.CameraInfo; -import androidx.camera.core.DisplayOrientedMeteringPointFactory; -import androidx.camera.core.MeteringPoint; -import androidx.camera.core.MeteringPointFactory; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.MeteringPointHostApi; -import java.util.Objects; - -/** - * Host API implementation for {@link MeteringPoint}. - * - *

This class handles instantiating and adding native object instances that are attached to a - * Dart instance or handle method calls on the associated native class or an instance of the class. - */ -public class MeteringPointHostApiImpl implements MeteringPointHostApi { - private final InstanceManager instanceManager; - private final MeteringPointProxy proxy; - - /** Proxy for constructor and static methods of {@link MeteringPoint}. */ - @VisibleForTesting - public static class MeteringPointProxy { - Activity activity; - - /** - * Creates a surface oriented {@link MeteringPoint} with the specified x, y, and size. - * - *

A {@link DisplayOrientedMeteringPointFactory} is used to construct the {@link - * MeteringPoint} because this factory handles the transformation of specified coordinates based - * on camera information and the device orientation automatically. - */ - @NonNull - public MeteringPoint create( - @NonNull Double x, - @NonNull Double y, - @Nullable Double size, - @NonNull CameraInfo cameraInfo) { - Display display = null; - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { - display = activity.getDisplay(); - } else { - display = getDefaultDisplayForAndroidVersionBelowR(activity); - } - - DisplayOrientedMeteringPointFactory factory = - getDisplayOrientedMeteringPointFactory(display, cameraInfo, 1f, 1f); - - if (size == null) { - return factory.createPoint(x.floatValue(), y.floatValue()); - } else { - return factory.createPoint(x.floatValue(), y.floatValue(), size.floatValue()); - } - } - - @NonNull - @SuppressWarnings("deprecation") - private Display getDefaultDisplayForAndroidVersionBelowR(@NonNull Activity activity) { - return ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)) - .getDefaultDisplay(); - } - - @VisibleForTesting - @NonNull - public DisplayOrientedMeteringPointFactory getDisplayOrientedMeteringPointFactory( - @NonNull Display display, @NonNull CameraInfo cameraInfo, float width, float height) { - return new DisplayOrientedMeteringPointFactory(display, cameraInfo, width, height); - } - - /** - * Returns the default point size of the {@link MeteringPoint} width and height, which is a - * normalized percentage of the sensor width/height. - */ - public float getDefaultPointSize() { - return MeteringPointFactory.getDefaultPointSize(); - } - } - /** - * Constructs a {@link MeteringPointHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - */ - public MeteringPointHostApiImpl(@NonNull InstanceManager instanceManager) { - this(instanceManager, new MeteringPointProxy()); - } - - /** - * Constructs a {@link MeteringPointHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - * @param proxy proxy for constructor and static methods of {@link MeteringPoint} - */ - @VisibleForTesting - MeteringPointHostApiImpl( - @NonNull InstanceManager instanceManager, @NonNull MeteringPointProxy proxy) { - this.instanceManager = instanceManager; - this.proxy = proxy; - } - - public void setActivity(@NonNull Activity activity) { - this.proxy.activity = activity; - } - - @Override - public void create( - @NonNull Long identifier, - @NonNull Double x, - @NonNull Double y, - @Nullable Double size, - @NonNull Long cameraInfoId) { - MeteringPoint meteringPoint = - proxy.create( - x, - y, - size, - (CameraInfo) Objects.requireNonNull(instanceManager.getInstance(cameraInfoId))); - instanceManager.addDartCreatedInstance(meteringPoint, identifier); - } - - @Override - @NonNull - public Double getDefaultPointSize() { - return (double) proxy.getDefaultPointSize(); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/MeteringPointProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/MeteringPointProxyApi.java new file mode 100644 index 000000000000..9fb651dc4fbc --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/MeteringPointProxyApi.java @@ -0,0 +1,24 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.camera.core.MeteringPoint; + +/** + * ProxyApi implementation for {@link MeteringPoint}. This class may handle instantiating native + * object instances that are attached to a Dart instance or handle method calls on the associated + * native class or an instance of that class. + */ +class MeteringPointProxyApi extends PigeonApiMeteringPoint { + MeteringPointProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @Override + public double getSize(MeteringPoint pigeonInstance) { + return pigeonInstance.getSize(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ObserverFlutterApiWrapper.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ObserverFlutterApiWrapper.java deleted file mode 100644 index f514ddbf86df..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ObserverFlutterApiWrapper.java +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import android.util.Log; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.VisibleForTesting; -import androidx.camera.core.CameraState; -import androidx.camera.core.ZoomState; -import androidx.lifecycle.Observer; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ObserverFlutterApi; -import java.util.Objects; - -/** - * Flutter API implementation for {@link Observer}. - * - *

This class may handle adding native instances that are attached to a Dart instance or passing - * arguments of callbacks methods to a Dart instance. - */ -public class ObserverFlutterApiWrapper { - - private static final String TAG = "ObserverFlutterApi"; - - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - private ObserverFlutterApi observerFlutterApi; - - @VisibleForTesting @Nullable public CameraStateFlutterApiWrapper cameraStateFlutterApiWrapper; - @VisibleForTesting @Nullable public ZoomStateFlutterApiImpl zoomStateFlutterApiImpl; - - /** - * Constructs a {@link ObserverFlutterApiWrapper}. - * - * @param binaryMessenger used to communicate with Dart over asynchronous messages - * @param instanceManager maintains instances stored to communicate with attached Dart objects - */ - public ObserverFlutterApiWrapper( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - observerFlutterApi = new ObserverFlutterApi(binaryMessenger); - } - - /** - * Sends a message to Dart to call {@link Observer.onChanged} on the Dart object representing - * {@code instance}. - */ - public void onChanged( - @NonNull Observer instance, - @NonNull T value, - @NonNull ObserverFlutterApi.Reply callback) { - - // Cast value to type of data that is being observed and create it on the Dart side - // if supported by this plugin. - // - // The supported types can be found in GeneratedCameraXLibrary.java as the - // LiveDataSupportedType enum. To add a new type, please follow the instructions - // found in pigeons/camerax_library.dart in the documentation for LiveDataSupportedType. - if (value instanceof CameraState) { - createCameraState((CameraState) value); - } else if (value instanceof ZoomState) { - createZoomState((ZoomState) value); - } else { - throw new UnsupportedOperationException( - "The type of value that was observed is not handled by this plugin."); - } - - Long observerIdentifier = instanceManager.getIdentifierForStrongReference(instance); - if (observerIdentifier == null) { - Log.e( - TAG, - "The Observer that received a callback has been garbage collected. Please create a new instance to receive any further data changes."); - return; - } - - observerFlutterApi.onChanged( - Objects.requireNonNull(observerIdentifier), - instanceManager.getIdentifierForStrongReference(value), - callback); - } - - /** Creates a {@link CameraState} on the Dart side. */ - private void createCameraState(CameraState cameraState) { - if (cameraStateFlutterApiWrapper == null) { - cameraStateFlutterApiWrapper = - new CameraStateFlutterApiWrapper(binaryMessenger, instanceManager); - } - cameraStateFlutterApiWrapper.create( - cameraState, - CameraStateFlutterApiWrapper.getCameraStateType(cameraState.getType()), - cameraState.getError(), - reply -> {}); - } - - /** Creates a {@link ZoomState} on the Dart side. */ - private void createZoomState(ZoomState zoomState) { - if (zoomStateFlutterApiImpl == null) { - zoomStateFlutterApiImpl = new ZoomStateFlutterApiImpl(binaryMessenger, instanceManager); - } - zoomStateFlutterApiImpl.create(zoomState, reply -> {}); - } - - /** Sets the Flutter API used to send messages to Dart. */ - @VisibleForTesting - void setApi(@NonNull ObserverFlutterApi api) { - this.observerFlutterApi = api; - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ObserverHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ObserverHostApiImpl.java deleted file mode 100644 index 46ffe6c4b8ee..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ObserverHostApiImpl.java +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.annotation.VisibleForTesting; -import androidx.lifecycle.Observer; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ObserverHostApi; -import java.util.Objects; - -/** - * Host API implementation for {@link Observer}. - * - *

This class may handle instantiating and adding native object instances that are attached to a - * Dart instance or handle method calls on the associated native class or an instance of the class. - */ -public class ObserverHostApiImpl implements ObserverHostApi { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - private final ObserverProxy observerProxy; - - /** Proxy for constructor of {@link Observer}. */ - @VisibleForTesting - public static class ObserverProxy { - - /** Creates an instance of {@link Observer}. */ - @NonNull - public ObserverImpl create( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - return new ObserverImpl(binaryMessenger, instanceManager); - } - } - - /** Implementation of {@link Observer} that passes arguments of callback methods to Dart. */ - public static class ObserverImpl implements Observer { - private ObserverFlutterApiWrapper observerFlutterApiWrapper; - - /** - * Constructs an instance of {@link Observer} that passes arguments of callbacks methods to - * Dart. - */ - public ObserverImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - super(); - observerFlutterApiWrapper = new ObserverFlutterApiWrapper(binaryMessenger, instanceManager); - } - - /** Method called when the data in observance is changed to {@code value}. */ - @Override - public void onChanged(T value) { - observerFlutterApiWrapper.onChanged(this, value, reply -> {}); - } - - /** Flutter API used to send messages back to Dart. */ - @VisibleForTesting - void setApi(@NonNull ObserverFlutterApiWrapper api) { - this.observerFlutterApiWrapper = api; - } - } - - /** - * Constructs a {@link ObserverHostApiImpl}. - * - * @param binaryMessenger used to communicate with Dart over asynchronous messages - * @param instanceManager maintains instances stored to communicate with attached Dart objects - */ - public ObserverHostApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - this(binaryMessenger, instanceManager, new ObserverProxy()); - } - - /** - * Constructs a {@link ObserverHostApiImpl}. - * - * @param binaryMessenger used to communicate with Dart over asynchronous messages - * @param instanceManager maintains instances stored to communicate with attached Dart objects - * @param proxy proxy for constructor of {@link Observer} - */ - @VisibleForTesting - ObserverHostApiImpl( - @NonNull BinaryMessenger binaryMessenger, - @NonNull InstanceManager instanceManager, - @NonNull ObserverProxy observerProxy) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - this.observerProxy = observerProxy; - } - - /** Creates an {@link Observer} instance with the specified observer. */ - @Override - public void create(@NonNull Long identifier) { - instanceManager.addDartCreatedInstance( - observerProxy.create(binaryMessenger, instanceManager), identifier); - } - - private Observer getObserverInstance(@NonNull Long identifier) { - return Objects.requireNonNull(instanceManager.getInstance(identifier)); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ObserverProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ObserverProxyApi.java new file mode 100644 index 000000000000..4a150eee758e --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ObserverProxyApi.java @@ -0,0 +1,64 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.lifecycle.Observer; +import java.util.Objects; + +/** + * ProxyApi implementation for {@link Observer}. This class may handle instantiating native object + * instances that are attached to a Dart instance or handle method calls on the associated native + * class or an instance of that class. + */ +class ObserverProxyApi extends PigeonApiObserver { + /** Implementation of {@link Observer} that passes arguments of callback methods to Dart. */ + static class ObserverImpl implements Observer { + final ObserverProxyApi api; + + ObserverImpl(@NonNull ObserverProxyApi api) { + this.api = api; + } + + @Override + public void onChanged(T t) { + api.getPigeonRegistrar() + .runOnMainThread( + new ProxyApiRegistrar.FlutterMethodRunnable() { + @Override + public void run() { + api.onChanged( + ObserverImpl.this, + t, + ResultCompat.asCompatCallback( + result -> { + if (result.isFailure()) { + onFailure( + "Observer.onChanged", + Objects.requireNonNull(result.exceptionOrNull())); + } + return null; + })); + } + }); + } + } + + ObserverProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public ProxyApiRegistrar getPigeonRegistrar() { + return (ProxyApiRegistrar) super.getPigeonRegistrar(); + } + + @NonNull + @Override + public Observer pigeon_defaultConstructor() { + return new ObserverImpl<>(this); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PendingRecordingFlutterApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PendingRecordingFlutterApiImpl.java deleted file mode 100644 index b3c46769ad98..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PendingRecordingFlutterApiImpl.java +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.camera.video.PendingRecording; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.PendingRecordingFlutterApi; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.VideoRecordEvent; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.VideoRecordEventData; - -public class PendingRecordingFlutterApiImpl extends PendingRecordingFlutterApi { - private final InstanceManager instanceManager; - - public PendingRecordingFlutterApiImpl( - @Nullable BinaryMessenger binaryMessenger, @Nullable InstanceManager instanceManager) { - super(binaryMessenger); - this.instanceManager = instanceManager; - } - - void create(@NonNull PendingRecording pendingRecording, @Nullable Reply reply) { - create(instanceManager.addHostCreatedInstance(pendingRecording), reply); - } - - void sendVideoRecordingFinalizedEvent(@NonNull Reply reply) { - super.onVideoRecordingEvent( - new VideoRecordEventData.Builder().setValue(VideoRecordEvent.FINALIZE).build(), reply); - } - - void sendVideoRecordingStartedEvent(@NonNull Reply reply) { - super.onVideoRecordingEvent( - new VideoRecordEventData.Builder().setValue(VideoRecordEvent.START).build(), reply); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PendingRecordingHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PendingRecordingHostApiImpl.java deleted file mode 100644 index 93aa39c56bee..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PendingRecordingHostApiImpl.java +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import android.content.Context; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.VisibleForTesting; -import androidx.camera.video.PendingRecording; -import androidx.camera.video.Recording; -import androidx.camera.video.VideoRecordEvent; -import androidx.core.content.ContextCompat; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.PendingRecordingHostApi; -import java.util.Objects; -import java.util.concurrent.Executor; - -public class PendingRecordingHostApiImpl implements PendingRecordingHostApi { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - @Nullable private Context context; - - @VisibleForTesting @NonNull public CameraXProxy cameraXProxy = new CameraXProxy(); - - @VisibleForTesting PendingRecordingFlutterApiImpl pendingRecordingFlutterApi; - - @VisibleForTesting SystemServicesFlutterApiImpl systemServicesFlutterApi; - - @VisibleForTesting RecordingFlutterApiImpl recordingFlutterApi; - - public PendingRecordingHostApiImpl( - @NonNull BinaryMessenger binaryMessenger, - @NonNull InstanceManager instanceManager, - @Nullable Context context) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - this.context = context; - systemServicesFlutterApi = cameraXProxy.createSystemServicesFlutterApiImpl(binaryMessenger); - recordingFlutterApi = new RecordingFlutterApiImpl(binaryMessenger, instanceManager); - pendingRecordingFlutterApi = - new PendingRecordingFlutterApiImpl(binaryMessenger, instanceManager); - } - - /** Sets the context, which is used to get the {@link Executor} needed to start the recording. */ - public void setContext(@Nullable Context context) { - this.context = context; - } - - /** - * Starts the given {@link PendingRecording}, creating a new {@link Recording}. The recording is - * then added to the instance manager and we return the corresponding identifier. - * - * @param identifier An identifier corresponding to a PendingRecording. - */ - @NonNull - @Override - public Long start(@NonNull Long identifier) { - PendingRecording pendingRecording = getPendingRecordingFromInstanceId(identifier); - Recording recording = - pendingRecording.start(this.getExecutor(), event -> handleVideoRecordEvent(event)); - recordingFlutterApi.create(recording, reply -> {}); - return Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(recording)); - } - - @Nullable - @VisibleForTesting - public Executor getExecutor() { - if (context == null) { - throw new IllegalStateException("Context must be set to get an executor to start recording."); - } - - return ContextCompat.getMainExecutor(context); - } - - /** - * Handles {@link VideoRecordEvent}s that come in during video recording. Sends any errors - * encountered using {@link SystemServicesFlutterApiImpl}. - * - *

Currently only sends {@link VideoRecordEvent.Start} and {@link VideoRecordEvent.Finalize} - * events to the Dart side. - */ - @VisibleForTesting - public void handleVideoRecordEvent(@NonNull VideoRecordEvent event) { - if (event instanceof VideoRecordEvent.Start) { - pendingRecordingFlutterApi.sendVideoRecordingStartedEvent(reply -> {}); - } else if (event instanceof VideoRecordEvent.Finalize) { - pendingRecordingFlutterApi.sendVideoRecordingFinalizedEvent(reply -> {}); - VideoRecordEvent.Finalize castedEvent = (VideoRecordEvent.Finalize) event; - if (castedEvent.hasError()) { - String cameraErrorMessage; - if (castedEvent.getCause() != null) { - cameraErrorMessage = castedEvent.getCause().toString(); - } else { - cameraErrorMessage = - "Error code " + castedEvent.getError() + ": An error occurred while recording video."; - } - systemServicesFlutterApi.sendCameraError(cameraErrorMessage, reply -> {}); - } - } - } - - private PendingRecording getPendingRecordingFromInstanceId(Long instanceId) { - return (PendingRecording) Objects.requireNonNull(instanceManager.getInstance(instanceId)); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PendingRecordingProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PendingRecordingProxyApi.java new file mode 100644 index 000000000000..c7f294a0f593 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PendingRecordingProxyApi.java @@ -0,0 +1,35 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.camera.video.PendingRecording; +import androidx.camera.video.Recording; +import androidx.core.content.ContextCompat; + +/** + * ProxyApi implementation for {@link PendingRecording}. This class may handle instantiating native + * object instances that are attached to a Dart instance or handle method calls on the associated + * native class or an instance of that class. + */ +class PendingRecordingProxyApi extends PigeonApiPendingRecording { + PendingRecordingProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public ProxyApiRegistrar getPigeonRegistrar() { + return (ProxyApiRegistrar) super.getPigeonRegistrar(); + } + + @NonNull + @Override + public Recording start( + PendingRecording pigeonInstance, @NonNull VideoRecordEventListener listener) { + return pigeonInstance.start( + ContextCompat.getMainExecutor(getPigeonRegistrar().getContext()), listener::onEvent); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PlaneProxyFlutterApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PlaneProxyFlutterApiImpl.java deleted file mode 100644 index 713e40321bdc..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PlaneProxyFlutterApiImpl.java +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.annotation.VisibleForTesting; -import androidx.camera.core.ImageProxy; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.PlaneProxyFlutterApi; - -/** - * Flutter API implementation for {@link ImageProxy.PlaneProxy}. - * - *

This class may handle adding native instances that are attached to a Dart instance or passing - * arguments of callbacks methods to a Dart instance. - */ -public class PlaneProxyFlutterApiImpl { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - private PlaneProxyFlutterApi api; - - /** - * Constructs a {@link PlaneProxyFlutterApiImpl}. - * - * @param binaryMessenger used to communicate with Dart over asynchronous messages - * @param instanceManager maintains instances stored to communicate with attached Dart objects - */ - public PlaneProxyFlutterApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - api = new PlaneProxyFlutterApi(binaryMessenger); - } - - /** - * Stores the {@link ImageProxy.PlaneProxy} instance and notifies Dart to create and store a new - * {@link ImageProxy.PlaneProxy} instance that is attached to this one. If {@code instance} has - * already been added, this method does nothing. - */ - public void create( - @NonNull ImageProxy.PlaneProxy instance, - @NonNull byte[] bytes, - @NonNull Long pixelStride, - @NonNull Long rowStride, - @NonNull PlaneProxyFlutterApi.Reply callback) { - if (!instanceManager.containsInstance(instance)) { - api.create( - instanceManager.addHostCreatedInstance(instance), - bytes, - pixelStride, - rowStride, - callback); - } - } - - /** - * Sets the Flutter API used to send messages to Dart. - * - *

This is only visible for testing. - */ - @VisibleForTesting - void setApi(@NonNull PlaneProxyFlutterApi api) { - this.api = api; - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PlaneProxyProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PlaneProxyProxyApi.java new file mode 100644 index 000000000000..df140f0006f1 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PlaneProxyProxyApi.java @@ -0,0 +1,41 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.camera.core.ImageProxy.PlaneProxy; +import java.nio.ByteBuffer; + +/** + * ProxyApi implementation for {@link PlaneProxy}. This class may handle instantiating native object + * instances that are attached to a Dart instance or handle method calls on the associated native + * class or an instance of that class. + */ +class PlaneProxyProxyApi extends PigeonApiPlaneProxy { + PlaneProxyProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public byte[] buffer(PlaneProxy pigeonInstance) { + final ByteBuffer buffer = pigeonInstance.getBuffer(); + + byte[] bytes = new byte[buffer.remaining()]; + buffer.get(bytes, 0, bytes.length); + + return bytes; + } + + @Override + public long pixelStride(PlaneProxy pigeonInstance) { + return pigeonInstance.getPixelStride(); + } + + @Override + public long rowStride(PlaneProxy pigeonInstance) { + return pigeonInstance.getRowStride(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PreviewHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PreviewHostApiImpl.java deleted file mode 100644 index ffec50a22d41..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PreviewHostApiImpl.java +++ /dev/null @@ -1,199 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import android.util.Size; -import android.view.Surface; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.VisibleForTesting; -import androidx.camera.core.Preview; -import androidx.camera.core.SurfaceRequest; -import androidx.camera.core.resolutionselector.ResolutionSelector; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.PreviewHostApi; -import io.flutter.view.TextureRegistry; -import java.util.Objects; -import java.util.concurrent.Executors; - -public class PreviewHostApiImpl implements PreviewHostApi { - final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - private final TextureRegistry textureRegistry; - - @VisibleForTesting public @NonNull CameraXProxy cameraXProxy = new CameraXProxy(); - @VisibleForTesting public @Nullable TextureRegistry.SurfaceProducer flutterSurfaceProducer; - - public PreviewHostApiImpl( - @NonNull BinaryMessenger binaryMessenger, - @NonNull InstanceManager instanceManager, - @NonNull TextureRegistry textureRegistry) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - this.textureRegistry = textureRegistry; - } - - /** Creates a {@link Preview} with the target rotation and resolution if specified. */ - @Override - public void create( - @NonNull Long identifier, @Nullable Long rotation, @Nullable Long resolutionSelectorId) { - Preview.Builder previewBuilder = cameraXProxy.createPreviewBuilder(); - - if (rotation != null) { - previewBuilder.setTargetRotation(rotation.intValue()); - } - if (resolutionSelectorId != null) { - ResolutionSelector resolutionSelector = - Objects.requireNonNull(instanceManager.getInstance(resolutionSelectorId)); - previewBuilder.setResolutionSelector(resolutionSelector); - } - - Preview preview = previewBuilder.build(); - instanceManager.addDartCreatedInstance(preview, identifier); - } - - /** - * Sets the {@link Preview.SurfaceProvider} that will be used to provide a {@code Surface} backed - * by a Flutter {@link TextureRegistry.SurfaceTextureEntry} used to build the {@link Preview}. - */ - @Override - public @NonNull Long setSurfaceProvider(@NonNull Long identifier) { - Preview preview = getPreviewInstance(identifier); - flutterSurfaceProducer = textureRegistry.createSurfaceProducer(); - Preview.SurfaceProvider surfaceProvider = createSurfaceProvider(flutterSurfaceProducer); - preview.setSurfaceProvider(surfaceProvider); - - return flutterSurfaceProducer.id(); - } - - /** - * Creates a {@link Preview.SurfaceProvider} that specifies how to provide a {@link Surface} to a - * {@code Preview} that is backed by a Flutter {@link TextureRegistry.SurfaceTextureEntry}. - */ - @VisibleForTesting - public @NonNull Preview.SurfaceProvider createSurfaceProvider( - @NonNull TextureRegistry.SurfaceProducer surfaceProducer) { - return new Preview.SurfaceProvider() { - @Override - public void onSurfaceRequested(@NonNull SurfaceRequest request) { - // Set callback for surfaceProducer to invalidate Surfaces that it produces when they - // get destroyed. - surfaceProducer.setCallback( - new TextureRegistry.SurfaceProducer.Callback() { - @Override - public void onSurfaceAvailable() { - // Do nothing. The Preview.SurfaceProvider will handle this whenever a new - // Surface is needed. - } - - @Override - // TODO(bparrishMines): Replace with onSurfaceCleanup once available on stable. See - // https://github.com/flutter/flutter/issues/161256. - @SuppressWarnings({"deprecation", "removal"}) - public void onSurfaceDestroyed() { - // Invalidate the SurfaceRequest so that CameraX knows to to make a new request - // for a surface. - request.invalidate(); - } - }); - - // Provide surface. - surfaceProducer.setSize( - request.getResolution().getWidth(), request.getResolution().getHeight()); - Surface flutterSurface = surfaceProducer.getSurface(); - request.provideSurface( - flutterSurface, - Executors.newSingleThreadExecutor(), - (result) -> { - // See - // https://developer.android.com/reference/androidx/camera/core/SurfaceRequest.Result - // for documentation. - // Always attempt a release. - flutterSurface.release(); - int resultCode = result.getResultCode(); - switch (resultCode) { - case SurfaceRequest.Result.RESULT_REQUEST_CANCELLED: - case SurfaceRequest.Result.RESULT_WILL_NOT_PROVIDE_SURFACE: - case SurfaceRequest.Result.RESULT_SURFACE_ALREADY_PROVIDED: - case SurfaceRequest.Result.RESULT_SURFACE_USED_SUCCESSFULLY: - // Only need to release, do nothing. - break; - case SurfaceRequest.Result.RESULT_INVALID_SURFACE: // Intentional fall through. - default: - // Release and send error. - SystemServicesFlutterApiImpl systemServicesFlutterApi = - cameraXProxy.createSystemServicesFlutterApiImpl(binaryMessenger); - systemServicesFlutterApi.sendCameraError( - getProvideSurfaceErrorDescription(resultCode), reply -> {}); - break; - } - }); - } - }; - } - - /** - * Returns an error description for each {@link SurfaceRequest.Result} that represents an error - * with providing a surface. - */ - String getProvideSurfaceErrorDescription(int resultCode) { - switch (resultCode) { - case SurfaceRequest.Result.RESULT_INVALID_SURFACE: - return resultCode + ": Provided surface could not be used by the camera."; - default: - return resultCode + ": Attempt to provide a surface resulted with unrecognizable code."; - } - } - - /** - * Releases the Flutter {@link TextureRegistry.SurfaceTextureEntry} if used to provide a surface - * for a {@link Preview}. - */ - @Override - public void releaseFlutterSurfaceTexture() { - if (flutterSurfaceProducer != null) { - flutterSurfaceProducer.release(); - return; - } - throw new IllegalStateException( - "releaseFlutterSurfaceTexture() cannot be called if the flutterSurfaceProducer for the camera preview has not yet been initialized."); - } - - /** Returns the resolution information for the specified {@link Preview}. */ - @Override - public @NonNull GeneratedCameraXLibrary.ResolutionInfo getResolutionInfo( - @NonNull Long identifier) { - Preview preview = getPreviewInstance(identifier); - Size resolution = preview.getResolutionInfo().getResolution(); - - GeneratedCameraXLibrary.ResolutionInfo.Builder resolutionInfo = - new GeneratedCameraXLibrary.ResolutionInfo.Builder() - .setWidth(Long.valueOf(resolution.getWidth())) - .setHeight(Long.valueOf(resolution.getHeight())); - return resolutionInfo.build(); - } - - /** Dynamically sets the target rotation of the {@link Preview}. */ - @Override - public void setTargetRotation(@NonNull Long identifier, @NonNull Long rotation) { - Preview preview = getPreviewInstance(identifier); - preview.setTargetRotation(rotation.intValue()); - } - - @NonNull - @Override - public Boolean surfaceProducerHandlesCropAndRotation() { - if (flutterSurfaceProducer != null) { - return flutterSurfaceProducer.handlesCropAndRotation(); - } - throw new IllegalStateException( - "surfaceProducerHandlesCropAndRotation() cannot be called if the flutterSurfaceProducer for the camera preview has not yet been initialized."); - } - - /** Retrieves the {@link Preview} instance associated with the specified {@code identifier}. */ - private Preview getPreviewInstance(@NonNull Long identifier) { - return Objects.requireNonNull(instanceManager.getInstance(identifier)); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PreviewProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PreviewProxyApi.java new file mode 100644 index 000000000000..65d8f8a37a5e --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/PreviewProxyApi.java @@ -0,0 +1,167 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import android.view.Surface; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.camera.core.Preview; +import androidx.camera.core.SurfaceRequest; +import androidx.camera.core.resolutionselector.ResolutionSelector; +import io.flutter.view.TextureRegistry; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Executors; + +/** + * ProxyApi implementation for {@link Preview}. This class may handle instantiating native object + * instances that are attached to a Dart instance or handle method calls on the associated native + * class or an instance of that class. + */ +class PreviewProxyApi extends PigeonApiPreview { + // Stores the SurfaceProducer when it is used as a SurfaceProvider for a Preview. + private final Map surfaceProducers = new HashMap<>(); + + PreviewProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public ProxyApiRegistrar getPigeonRegistrar() { + return (ProxyApiRegistrar) super.getPigeonRegistrar(); + } + + @NonNull + @Override + public Preview pigeon_defaultConstructor( + @Nullable ResolutionSelector resolutionSelector, @Nullable Long targetRotation) { + final Preview.Builder builder = new Preview.Builder(); + if (targetRotation != null) { + builder.setTargetRotation(targetRotation.intValue()); + } + if (resolutionSelector != null) { + builder.setResolutionSelector(resolutionSelector); + } + return builder.build(); + } + + @Override + public long setSurfaceProvider( + @NonNull Preview pigeonInstance, @NonNull SystemServicesManager systemServicesManager) { + final TextureRegistry.SurfaceProducer surfaceProducer = + getPigeonRegistrar().getTextureRegistry().createSurfaceProducer(); + final Preview.SurfaceProvider surfaceProvider = + createSurfaceProvider(surfaceProducer, systemServicesManager); + + pigeonInstance.setSurfaceProvider(surfaceProvider); + surfaceProducers.put(pigeonInstance, surfaceProducer); + + return surfaceProducer.id(); + } + + @Override + public void releaseSurfaceProvider(@NonNull Preview pigeonInstance) { + final TextureRegistry.SurfaceProducer surfaceProducer = surfaceProducers.remove(pigeonInstance); + if (surfaceProducer != null) { + surfaceProducer.release(); + return; + } + throw new IllegalStateException( + "releaseFlutterSurfaceTexture() cannot be called if the flutterSurfaceProducer for the camera preview has not yet been initialized."); + } + + @Override + public boolean surfaceProducerHandlesCropAndRotation(@NonNull Preview pigeonInstance) { + final TextureRegistry.SurfaceProducer surfaceProducer = surfaceProducers.get(pigeonInstance); + if (surfaceProducer != null) { + return surfaceProducer.handlesCropAndRotation(); + } + throw new IllegalStateException( + "surfaceProducerHandlesCropAndRotation() cannot be called if the flutterSurfaceProducer for the camera preview has not yet been initialized."); + } + + @Nullable + @Override + public androidx.camera.core.ResolutionInfo getResolutionInfo(Preview pigeonInstance) { + return pigeonInstance.getResolutionInfo(); + } + + @Override + public void setTargetRotation(Preview pigeonInstance, long rotation) { + pigeonInstance.setTargetRotation((int) rotation); + } + + @NonNull + Preview.SurfaceProvider createSurfaceProvider( + @NonNull TextureRegistry.SurfaceProducer surfaceProducer, + @NonNull SystemServicesManager systemServicesManager) { + return request -> { + // Set callback for surfaceProducer to invalidate Surfaces that it produces when they + // get destroyed. + surfaceProducer.setCallback( + new TextureRegistry.SurfaceProducer.Callback() { + public void onSurfaceAvailable() { + // Do nothing. The Preview.SurfaceProvider will handle this whenever a new + // Surface is needed. + } + + @Override + // TODO(bparrishMines): Replace with onSurfaceCleanup once available on stable. See + // https://github.com/flutter/flutter/issues/161256. + @SuppressWarnings({"deprecation", "removal"}) + public void onSurfaceDestroyed() { + // Invalidate the SurfaceRequest so that CameraX knows to to make a new request + // for a surface. + request.invalidate(); + } + }); + + // Provide surface. + surfaceProducer.setSize( + request.getResolution().getWidth(), request.getResolution().getHeight()); + Surface flutterSurface = surfaceProducer.getSurface(); + request.provideSurface( + flutterSurface, + Executors.newSingleThreadExecutor(), + (result) -> { + // See + // https://developer.android.com/reference/androidx/camera/core/SurfaceRequest.Result + // for documentation. + // Always attempt a release. + flutterSurface.release(); + int resultCode = result.getResultCode(); + switch (resultCode) { + case SurfaceRequest.Result.RESULT_REQUEST_CANCELLED: + case SurfaceRequest.Result.RESULT_WILL_NOT_PROVIDE_SURFACE: + case SurfaceRequest.Result.RESULT_SURFACE_ALREADY_PROVIDED: + case SurfaceRequest.Result.RESULT_SURFACE_USED_SUCCESSFULLY: + // Only need to release, do nothing. + break; + case SurfaceRequest.Result.RESULT_INVALID_SURFACE: // Intentional fall through. + default: + systemServicesManager.onCameraError(getProvideSurfaceErrorDescription(resultCode)); + } + }); + }; + } + + /** + * Returns an error description for each {@link SurfaceRequest.Result} that represents an error + * with providing a surface. + */ + String getProvideSurfaceErrorDescription(int resultCode) { + if (resultCode == SurfaceRequest.Result.RESULT_INVALID_SURFACE) { + return resultCode + ": Provided surface could not be used by the camera."; + } + return resultCode + ": Attempt to provide a surface resulted with unrecognizable code."; + } + + @Nullable + @Override + public ResolutionSelector resolutionSelector(@NonNull Preview pigeonInstance) { + return pigeonInstance.getResolutionSelector(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProcessCameraProviderFlutterApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProcessCameraProviderFlutterApiImpl.java deleted file mode 100644 index 35e2bc0ec73c..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProcessCameraProviderFlutterApiImpl.java +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.camera.lifecycle.ProcessCameraProvider; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ProcessCameraProviderFlutterApi; - -public class ProcessCameraProviderFlutterApiImpl extends ProcessCameraProviderFlutterApi { - public ProcessCameraProviderFlutterApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - super(binaryMessenger); - this.instanceManager = instanceManager; - } - - private final InstanceManager instanceManager; - - void create(ProcessCameraProvider processCameraProvider, Reply reply) { - create(instanceManager.addHostCreatedInstance(processCameraProvider), reply); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProcessCameraProviderHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProcessCameraProviderHostApiImpl.java deleted file mode 100644 index 0e22e1aa5a5f..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProcessCameraProviderHostApiImpl.java +++ /dev/null @@ -1,176 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import android.content.Context; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.camera.core.Camera; -import androidx.camera.core.CameraInfo; -import androidx.camera.core.CameraSelector; -import androidx.camera.core.UseCase; -import androidx.camera.lifecycle.ProcessCameraProvider; -import androidx.core.content.ContextCompat; -import androidx.lifecycle.LifecycleOwner; -import com.google.common.util.concurrent.ListenableFuture; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ProcessCameraProviderHostApi; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -public class ProcessCameraProviderHostApiImpl implements ProcessCameraProviderHostApi { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - - @Nullable private Context context; - @Nullable private LifecycleOwner lifecycleOwner; - - public ProcessCameraProviderHostApiImpl( - @NonNull BinaryMessenger binaryMessenger, - @NonNull InstanceManager instanceManager, - @NonNull Context context) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - this.context = context; - } - - public void setLifecycleOwner(@Nullable LifecycleOwner lifecycleOwner) { - this.lifecycleOwner = lifecycleOwner; - } - - /** - * Sets the context that the {@code ProcessCameraProvider} will use to attach the lifecycle of the - * camera to. - * - *

If using the camera plugin in an add-to-app context, ensure that a new instance of the - * {@code ProcessCameraProvider} is fetched via {@code #getInstance} anytime the context changes. - */ - public void setContext(@NonNull Context context) { - this.context = context; - } - - /** - * Returns the instance of the {@code ProcessCameraProvider} to manage the lifecycle of the camera - * for the current {@code Context}. - */ - @Override - public void getInstance(@NonNull GeneratedCameraXLibrary.Result result) { - if (context == null) { - throw new IllegalStateException("Context must be set to get ProcessCameraProvider instance."); - } - - ListenableFuture processCameraProviderFuture = - ProcessCameraProvider.getInstance(context); - - processCameraProviderFuture.addListener( - () -> { - try { - // Camera provider is now guaranteed to be available. - ProcessCameraProvider processCameraProvider = processCameraProviderFuture.get(); - - final ProcessCameraProviderFlutterApiImpl flutterApi = - new ProcessCameraProviderFlutterApiImpl(binaryMessenger, instanceManager); - if (!instanceManager.containsInstance(processCameraProvider)) { - flutterApi.create(processCameraProvider, reply -> {}); - } - result.success(instanceManager.getIdentifierForStrongReference(processCameraProvider)); - } catch (Exception e) { - result.error(e); - } - }, - ContextCompat.getMainExecutor(context)); - } - - /** Returns cameras available to the {@code ProcessCameraProvider}. */ - @NonNull - @Override - public List getAvailableCameraInfos(@NonNull Long identifier) { - ProcessCameraProvider processCameraProvider = - (ProcessCameraProvider) Objects.requireNonNull(instanceManager.getInstance(identifier)); - - List availableCameras = processCameraProvider.getAvailableCameraInfos(); - List availableCamerasIds = new ArrayList<>(); - final CameraInfoFlutterApiImpl cameraInfoFlutterApi = - new CameraInfoFlutterApiImpl(binaryMessenger, instanceManager); - - for (CameraInfo cameraInfo : availableCameras) { - if (!instanceManager.containsInstance(cameraInfo)) { - cameraInfoFlutterApi.create(cameraInfo, result -> {}); - } - availableCamerasIds.add(instanceManager.getIdentifierForStrongReference(cameraInfo)); - } - return availableCamerasIds; - } - - /** - * Binds specified {@code UseCase}s to the lifecycle of the {@code LifecycleOwner} that - * corresponds to this instance and returns the instance of the {@code Camera} whose lifecycle - * that {@code LifecycleOwner} reflects. - */ - @Override - public @NonNull Long bindToLifecycle( - @NonNull Long identifier, - @NonNull Long cameraSelectorIdentifier, - @NonNull List useCaseIds) { - if (lifecycleOwner == null) { - throw new IllegalStateException( - "LifecycleOwner must be set to get ProcessCameraProvider instance."); - } - - ProcessCameraProvider processCameraProvider = - (ProcessCameraProvider) Objects.requireNonNull(instanceManager.getInstance(identifier)); - CameraSelector cameraSelector = - (CameraSelector) - Objects.requireNonNull(instanceManager.getInstance(cameraSelectorIdentifier)); - UseCase[] useCases = new UseCase[useCaseIds.size()]; - for (int i = 0; i < useCaseIds.size(); i++) { - useCases[i] = - (UseCase) - Objects.requireNonNull( - instanceManager.getInstance(((Number) useCaseIds.get(i)).longValue())); - } - - Camera camera = processCameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector, useCases); - - final CameraFlutterApiImpl cameraFlutterApi = - new CameraFlutterApiImpl(binaryMessenger, instanceManager); - if (!instanceManager.containsInstance(camera)) { - cameraFlutterApi.create(camera, result -> {}); - } - - return Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(camera)); - } - - @Override - public @NonNull Boolean isBound(@NonNull Long identifier, @NonNull Long useCaseIdentifier) { - ProcessCameraProvider processCameraProvider = - (ProcessCameraProvider) Objects.requireNonNull(instanceManager.getInstance(identifier)); - UseCase useCase = - (UseCase) Objects.requireNonNull(instanceManager.getInstance(useCaseIdentifier)); - return processCameraProvider.isBound(useCase); - } - - @Override - public void unbind(@NonNull Long identifier, @NonNull List useCaseIds) { - ProcessCameraProvider processCameraProvider = - (ProcessCameraProvider) Objects.requireNonNull(instanceManager.getInstance(identifier)); - UseCase[] useCases = new UseCase[useCaseIds.size()]; - for (int i = 0; i < useCaseIds.size(); i++) { - useCases[i] = - (UseCase) - Objects.requireNonNull( - instanceManager.getInstance(((Number) useCaseIds.get(i)).longValue())); - } - processCameraProvider.unbind(useCases); - } - - @Override - public void unbindAll(@NonNull Long identifier) { - ProcessCameraProvider processCameraProvider = - (ProcessCameraProvider) Objects.requireNonNull(instanceManager.getInstance(identifier)); - processCameraProvider.unbindAll(); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProcessCameraProviderProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProcessCameraProviderProxyApi.java new file mode 100644 index 000000000000..86e62ec661a7 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProcessCameraProviderProxyApi.java @@ -0,0 +1,92 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.camera.core.Camera; +import androidx.camera.core.CameraInfo; +import androidx.camera.core.CameraSelector; +import androidx.camera.core.UseCase; +import androidx.camera.lifecycle.ProcessCameraProvider; +import androidx.core.content.ContextCompat; +import androidx.lifecycle.LifecycleOwner; +import com.google.common.util.concurrent.ListenableFuture; +import java.util.List; +import kotlin.Result; +import kotlin.Unit; +import kotlin.jvm.functions.Function1; + +/** + * ProxyApi implementation for {@link ProcessCameraProvider}. This class may handle instantiating + * native object instances that are attached to a Dart instance or handle method calls on the + * associated native class or an instance of that class. + */ +class ProcessCameraProviderProxyApi extends PigeonApiProcessCameraProvider { + ProcessCameraProviderProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public ProxyApiRegistrar getPigeonRegistrar() { + return (ProxyApiRegistrar) super.getPigeonRegistrar(); + } + + @Override + public void getInstance( + @NonNull Function1, Unit> callback) { + final ListenableFuture processCameraProviderFuture = + ProcessCameraProvider.getInstance(getPigeonRegistrar().getContext()); + + processCameraProviderFuture.addListener( + () -> { + try { + // Camera provider is now guaranteed to be available. + ResultCompat.success(processCameraProviderFuture.get(), callback); + } catch (Exception e) { + ResultCompat.failure(e, callback); + } + }, + ContextCompat.getMainExecutor(getPigeonRegistrar().getContext())); + } + + @NonNull + @Override + public List getAvailableCameraInfos(ProcessCameraProvider pigeonInstance) { + return pigeonInstance.getAvailableCameraInfos(); + } + + @NonNull + @Override + public Camera bindToLifecycle( + @NonNull ProcessCameraProvider pigeonInstance, + @NonNull CameraSelector cameraSelector, + @NonNull List useCases) { + final LifecycleOwner lifecycleOwner = getPigeonRegistrar().getLifecycleOwner(); + if (lifecycleOwner != null) { + return pigeonInstance.bindToLifecycle( + lifecycleOwner, cameraSelector, useCases.toArray(new UseCase[0])); + } + + throw new IllegalStateException( + "LifecycleOwner must be set to get ProcessCameraProvider instance."); + } + + @Override + public boolean isBound(ProcessCameraProvider pigeonInstance, @NonNull UseCase useCase) { + return pigeonInstance.isBound(useCase); + } + + @Override + public void unbind( + ProcessCameraProvider pigeonInstance, @NonNull List useCases) { + pigeonInstance.unbind(useCases.toArray(new UseCase[0])); + } + + @Override + public void unbindAll(ProcessCameraProvider pigeonInstance) { + pigeonInstance.unbindAll(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProxyApiRegistrar.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProxyApiRegistrar.java new file mode 100644 index 000000000000..42042488c02c --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProxyApiRegistrar.java @@ -0,0 +1,424 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import android.app.Activity; +import android.content.Context; +import android.os.Build; +import android.os.Handler; +import android.os.Looper; +import android.util.Log; +import android.view.Display; +import android.view.WindowManager; +import androidx.annotation.ChecksSdkIntAtLeast; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.lifecycle.LifecycleOwner; +import io.flutter.plugin.common.BinaryMessenger; +import io.flutter.view.TextureRegistry; + +public class ProxyApiRegistrar extends CameraXLibraryPigeonProxyApiRegistrar { + @NonNull + private final CameraPermissionsManager cameraPermissionsManager = new CameraPermissionsManager(); + + @NonNull private final TextureRegistry textureRegistry; + + @NonNull private Context context; + + @Nullable private CameraPermissionsManager.PermissionsRegistry permissionsRegistry; + + /** + * Handles errors received from calling a method from host->Dart. + * + *

If a call to Dart fails, users should call `onFailure`. + */ + public abstract static class FlutterMethodRunnable implements Runnable { + void onFailure(@NonNull String methodName, @NonNull Throwable throwable) { + final String errorMessage; + if (throwable instanceof CameraXError) { + final CameraXError cameraXError = (CameraXError) throwable; + errorMessage = + cameraXError.getCode() + + ": Error returned from calling " + + methodName + + ": " + + cameraXError.getMessage() + + " Details: " + + cameraXError.getDetails(); + } else { + errorMessage = + throwable.getClass().getSimpleName() + + ": Error returned from calling " + + methodName + + ": " + + throwable.getMessage(); + } + Log.e("ProxyApiRegistrar", errorMessage); + } + } + + // PreviewProxyApi maintains a state to track SurfaceProducers provided by the Flutter engine. + @NonNull private final PreviewProxyApi previewProxyApi = new PreviewProxyApi(this); + + public ProxyApiRegistrar( + @NonNull BinaryMessenger binaryMessenger, + @NonNull Context context, + @NonNull TextureRegistry textureRegistry) { + super(binaryMessenger); + this.context = context; + this.textureRegistry = textureRegistry; + } + + // Interface for an injectable SDK version checker. + @ChecksSdkIntAtLeast(parameter = 0) + boolean sdkIsAtLeast(int version) { + return Build.VERSION.SDK_INT >= version; + } + + // Added to be overridden for tests. The test implementation calls `callback` immediately, instead + // of waiting for the main thread to run it. + void runOnMainThread(@NonNull FlutterMethodRunnable runnable) { + if (context instanceof Activity) { + ((Activity) context).runOnUiThread(runnable); + } else { + new Handler(Looper.getMainLooper()).post(runnable); + } + } + + @NonNull + public Context getContext() { + return context; + } + + @Nullable + public Activity getActivity() { + if (context instanceof Activity) { + return (Activity) context; + } + + return null; + } + + public void setContext(@NonNull Context context) { + this.context = context; + } + + @Nullable + public LifecycleOwner getLifecycleOwner() { + if (context instanceof LifecycleOwner) { + return (LifecycleOwner) context; + } else if (context instanceof Activity) { + return new ProxyLifecycleProvider((Activity) context); + } + + return null; + } + + @NonNull + public CameraPermissionsManager getCameraPermissionsManager() { + return cameraPermissionsManager; + } + + void setPermissionsRegistry( + @Nullable CameraPermissionsManager.PermissionsRegistry permissionsRegistry) { + this.permissionsRegistry = permissionsRegistry; + } + + @Nullable + CameraPermissionsManager.PermissionsRegistry getPermissionsRegistry() { + return permissionsRegistry; + } + + @NonNull + TextureRegistry getTextureRegistry() { + return textureRegistry; + } + + long getDefaultClearFinalizedWeakReferencesInterval() { + return 3000; + } + + @SuppressWarnings("deprecation") + @Nullable + Display getDisplay() { + if (sdkIsAtLeast(Build.VERSION_CODES.R)) { + return getContext().getDisplay(); + } else { + return ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)) + .getDefaultDisplay(); + } + } + + @NonNull + @Override + public PigeonApiCameraSize getPigeonApiCameraSize() { + return new CameraSizeProxyApi(this); + } + + @NonNull + @Override + public PigeonApiResolutionInfo getPigeonApiResolutionInfo() { + return new ResolutionInfoProxyApi(this); + } + + @NonNull + @Override + public PigeonApiCameraIntegerRange getPigeonApiCameraIntegerRange() { + return new CameraIntegerRangeProxyApi(this); + } + + @NonNull + @Override + public PigeonApiMeteringPoint getPigeonApiMeteringPoint() { + return new MeteringPointProxyApi(this); + } + + @NonNull + @Override + public PigeonApiObserver getPigeonApiObserver() { + return new ObserverProxyApi(this); + } + + @NonNull + @Override + public PigeonApiCameraInfo getPigeonApiCameraInfo() { + return new CameraInfoProxyApi(this); + } + + @NonNull + @Override + public PigeonApiCameraSelector getPigeonApiCameraSelector() { + return new CameraSelectorProxyApi(this); + } + + @NonNull + @Override + public PigeonApiProcessCameraProvider getPigeonApiProcessCameraProvider() { + return new ProcessCameraProviderProxyApi(this); + } + + @NonNull + @Override + public PigeonApiCamera getPigeonApiCamera() { + return new CameraProxyApi(this); + } + + @NonNull + @Override + public SystemServicesManagerProxyApi getPigeonApiSystemServicesManager() { + return new SystemServicesManagerProxyApi(this); + } + + @NonNull + @Override + public DeviceOrientationManagerProxyApi getPigeonApiDeviceOrientationManager() { + return new DeviceOrientationManagerProxyApi(this); + } + + @NonNull + @Override + public PigeonApiPreview getPigeonApiPreview() { + return previewProxyApi; + } + + @NonNull + @Override + public PigeonApiVideoCapture getPigeonApiVideoCapture() { + return new VideoCaptureProxyApi(this); + } + + @NonNull + @Override + public PigeonApiRecorder getPigeonApiRecorder() { + return new RecorderProxyApi(this); + } + + @NonNull + @Override + public PigeonApiVideoRecordEventListener getPigeonApiVideoRecordEventListener() { + return new VideoRecordEventListenerProxyApi(this); + } + + @NonNull + @Override + public PigeonApiPendingRecording getPigeonApiPendingRecording() { + return new PendingRecordingProxyApi(this); + } + + @NonNull + @Override + public PigeonApiRecording getPigeonApiRecording() { + return new RecordingProxyApi(this); + } + + @NonNull + @Override + public PigeonApiImageCapture getPigeonApiImageCapture() { + return new ImageCaptureProxyApi(this); + } + + @NonNull + @Override + public PigeonApiResolutionStrategy getPigeonApiResolutionStrategy() { + return new ResolutionStrategyProxyApi(this); + } + + @NonNull + @Override + public PigeonApiResolutionSelector getPigeonApiResolutionSelector() { + return new ResolutionSelectorProxyApi(this); + } + + @NonNull + @Override + public PigeonApiAspectRatioStrategy getPigeonApiAspectRatioStrategy() { + return new AspectRatioStrategyProxyApi(this); + } + + @NonNull + @Override + public PigeonApiCameraState getPigeonApiCameraState() { + return new CameraStateProxyApi(this); + } + + @NonNull + @Override + public PigeonApiExposureState getPigeonApiExposureState() { + return new ExposureStateProxyApi(this); + } + + @NonNull + @Override + public PigeonApiZoomState getPigeonApiZoomState() { + return new ZoomStateProxyApi(this); + } + + @NonNull + @Override + public PigeonApiImageAnalysis getPigeonApiImageAnalysis() { + return new ImageAnalysisProxyApi(this); + } + + @NonNull + @Override + public PigeonApiAnalyzer getPigeonApiAnalyzer() { + return new AnalyzerProxyApi(this); + } + + @NonNull + @Override + public PigeonApiCameraStateStateError getPigeonApiCameraStateStateError() { + return new CameraStateStateErrorProxyApi(this); + } + + @NonNull + @Override + public PigeonApiLiveData getPigeonApiLiveData() { + return new LiveDataProxyApi(this); + } + + @NonNull + @Override + public PigeonApiImageProxy getPigeonApiImageProxy() { + return new ImageProxyProxyApi(this); + } + + @NonNull + @Override + public PigeonApiPlaneProxy getPigeonApiPlaneProxy() { + return new PlaneProxyProxyApi(this); + } + + @NonNull + @Override + public PigeonApiQualitySelector getPigeonApiQualitySelector() { + return new QualitySelectorProxyApi(this); + } + + @NonNull + @Override + public PigeonApiFallbackStrategy getPigeonApiFallbackStrategy() { + return new FallbackStrategyProxyApi(this); + } + + @NonNull + @Override + public PigeonApiCameraControl getPigeonApiCameraControl() { + return new CameraControlProxyApi(this); + } + + @NonNull + @Override + public PigeonApiFocusMeteringActionBuilder getPigeonApiFocusMeteringActionBuilder() { + return new FocusMeteringActionBuilderProxyApi(this); + } + + @NonNull + @Override + public PigeonApiFocusMeteringAction getPigeonApiFocusMeteringAction() { + return new FocusMeteringActionProxyApi(this); + } + + @NonNull + @Override + public PigeonApiFocusMeteringResult getPigeonApiFocusMeteringResult() { + return new FocusMeteringResultProxyApi(this); + } + + @NonNull + @Override + public PigeonApiCaptureRequest getPigeonApiCaptureRequest() { + return new CaptureRequestProxyApi(this); + } + + @NonNull + @Override + public PigeonApiCaptureRequestOptions getPigeonApiCaptureRequestOptions() { + return new CaptureRequestOptionsProxyApi(this); + } + + @NonNull + @Override + public PigeonApiCamera2CameraControl getPigeonApiCamera2CameraControl() { + return new Camera2CameraControlProxyApi(this); + } + + @NonNull + @Override + public PigeonApiResolutionFilter getPigeonApiResolutionFilter() { + return new ResolutionFilterProxyApi(this); + } + + @NonNull + @Override + public PigeonApiCameraCharacteristics getPigeonApiCameraCharacteristics() { + return new CameraCharacteristicsProxyApi(this); + } + + @NonNull + @Override + public PigeonApiCamera2CameraInfo getPigeonApiCamera2CameraInfo() { + return new Camera2CameraInfoProxyApi(this); + } + + @NonNull + @Override + public PigeonApiMeteringPointFactory getPigeonApiMeteringPointFactory() { + return new MeteringPointFactoryProxyApi(this); + } + + @NonNull + @Override + public PigeonApiDisplayOrientedMeteringPointFactory + getPigeonApiDisplayOrientedMeteringPointFactory() { + return new DisplayOrientedMeteringPointFactoryProxyApi(this); + } + + @NonNull + @Override + public CameraPermissionsErrorProxyApi getPigeonApiCameraPermissionsError() { + return new CameraPermissionsErrorProxyApi(this); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProxyLifecycleProvider.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProxyLifecycleProvider.java index d80d7b32357f..87d26cf75655 100644 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProxyLifecycleProvider.java +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ProxyLifecycleProvider.java @@ -8,6 +8,7 @@ import android.app.Application.ActivityLifecycleCallbacks; import android.os.Bundle; import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import androidx.lifecycle.Lifecycle; import androidx.lifecycle.Lifecycle.Event; @@ -31,7 +32,7 @@ public class ProxyLifecycleProvider implements ActivityLifecycleCallbacks, Lifec } @Override - public void onActivityCreated(@NonNull Activity activity, @NonNull Bundle savedInstanceState) { + public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) { if (activity.hashCode() != registrarActivityHashCode) { return; } diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/QualitySelectorHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/QualitySelectorHostApiImpl.java deleted file mode 100644 index 87a00e629348..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/QualitySelectorHostApiImpl.java +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import android.util.Size; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.VisibleForTesting; -import androidx.camera.video.FallbackStrategy; -import androidx.camera.video.Quality; -import androidx.camera.video.QualitySelector; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.QualitySelectorHostApi; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ResolutionInfo; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.VideoQuality; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.VideoQualityData; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -/** - * Host API implementation for {@link QualitySelector}. - * - *

This class may handle instantiating and adding native object instances that are attached to a - * Dart instance or handle method calls on the associated native class or an instance of the class. - */ -public class QualitySelectorHostApiImpl implements QualitySelectorHostApi { - private final InstanceManager instanceManager; - - private final QualitySelectorProxy proxy; - - /** Proxy for constructor of {@link QualitySelector}. */ - @VisibleForTesting - public static class QualitySelectorProxy { - /** Creates an instance of {@link QualitySelector}. */ - public @NonNull QualitySelector create( - @NonNull List videoQualityDataList, - @Nullable FallbackStrategy fallbackStrategy) { - // Convert each index of VideoQuality to Quality. - List qualityList = new ArrayList(); - for (VideoQualityData videoQualityData : videoQualityDataList) { - qualityList.add(getQualityFromVideoQuality(videoQualityData.getQuality())); - } - - boolean fallbackStrategySpecified = fallbackStrategy != null; - if (qualityList.size() == 0) { - throw new IllegalArgumentException( - "List of at least one Quality must be supplied to create QualitySelector."); - } else if (qualityList.size() == 1) { - Quality quality = qualityList.get(0); - return fallbackStrategySpecified - ? QualitySelector.from(quality, fallbackStrategy) - : QualitySelector.from(quality); - } - - return fallbackStrategySpecified - ? QualitySelector.fromOrderedList(qualityList, fallbackStrategy) - : QualitySelector.fromOrderedList(qualityList); - } - } - - /** - * Constructs a {@link QualitySelectorHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - */ - public QualitySelectorHostApiImpl(@NonNull InstanceManager instanceManager) { - this(instanceManager, new QualitySelectorProxy()); - } - - /** - * Constructs a {@link QualitySelectorHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - * @param proxy proxy for constructor of {@link QualitySelector} - */ - QualitySelectorHostApiImpl( - @NonNull InstanceManager instanceManager, @NonNull QualitySelectorProxy proxy) { - this.instanceManager = instanceManager; - this.proxy = proxy; - } - - /** - * Creates a {@link QualitySelector} instance with the quality list and {@link FallbackStrategy} - * with the identifier specified. - */ - @Override - public void create( - @NonNull Long identifier, - @NonNull List videoQualityDataList, - @Nullable Long fallbackStrategyIdentifier) { - instanceManager.addDartCreatedInstance( - proxy.create( - videoQualityDataList, - fallbackStrategyIdentifier == null - ? null - : Objects.requireNonNull(instanceManager.getInstance(fallbackStrategyIdentifier))), - identifier); - } - - /** - * Retrieves the corresponding resolution from the input quality for the camera represented by the - * {@link CameraInfo} represented by the identifier specified. - */ - @Override - public @NonNull ResolutionInfo getResolution( - @NonNull Long cameraInfoIdentifier, @NonNull VideoQuality quality) { - final Size result = - QualitySelector.getResolution( - Objects.requireNonNull(instanceManager.getInstance(cameraInfoIdentifier)), - getQualityFromVideoQuality(quality)); - return new ResolutionInfo.Builder() - .setWidth(Long.valueOf(result.getWidth())) - .setHeight(Long.valueOf(result.getHeight())) - .build(); - } - - /** - * Converts the specified {@link VideoQuality to a {@link Quality} that is understood - * by CameraX. - */ - public static @NonNull Quality getQualityFromVideoQuality(@NonNull VideoQuality videoQuality) { - switch (videoQuality) { - case SD: - return Quality.SD; - case HD: - return Quality.HD; - case FHD: - return Quality.FHD; - case UHD: - return Quality.UHD; - case LOWEST: - return Quality.LOWEST; - case HIGHEST: - return Quality.HIGHEST; - } - throw new IllegalArgumentException( - "VideoQuality " + videoQuality + " is unhandled by QualitySelectorHostApiImpl."); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/QualitySelectorProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/QualitySelectorProxyApi.java new file mode 100644 index 000000000000..59d946dcf173 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/QualitySelectorProxyApi.java @@ -0,0 +1,80 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import android.util.Size; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.camera.video.FallbackStrategy; +import androidx.camera.video.Quality; +import androidx.camera.video.QualitySelector; +import java.util.ArrayList; +import java.util.List; + +/** + * ProxyApi implementation for {@link QualitySelector}. This class may handle instantiating native + * object instances that are attached to a Dart instance or handle method calls on the associated + * native class or an instance of that class. + */ +class QualitySelectorProxyApi extends PigeonApiQualitySelector { + QualitySelectorProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public QualitySelector from( + @NonNull VideoQuality quality, @Nullable FallbackStrategy fallbackStrategy) { + if (fallbackStrategy == null) { + return QualitySelector.from(getNativeQuality(quality)); + } + + return QualitySelector.from(getNativeQuality(quality), fallbackStrategy); + } + + @NonNull + @Override + public QualitySelector fromOrderedList( + @NonNull List qualities, + @Nullable FallbackStrategy fallbackStrategy) { + final List nativeQualities = new ArrayList<>(); + for (final VideoQuality quality : qualities) { + nativeQualities.add(getNativeQuality(quality)); + } + + if (fallbackStrategy == null) { + return QualitySelector.fromOrderedList(nativeQualities); + } + + return QualitySelector.fromOrderedList(nativeQualities, fallbackStrategy); + } + + @Nullable + @Override + public Size getResolution( + @NonNull androidx.camera.core.CameraInfo cameraInfo, @NonNull VideoQuality quality) { + return QualitySelector.getResolution(cameraInfo, getNativeQuality(quality)); + } + + Quality getNativeQuality(VideoQuality quality) { + switch (quality) { + case SD: + return Quality.SD; + case HD: + return Quality.HD; + case FHD: + return Quality.FHD; + case UHD: + return Quality.UHD; + case LOWEST: + return Quality.LOWEST; + case HIGHEST: + return Quality.HIGHEST; + } + + throw new IllegalArgumentException( + "VideoQuality " + quality + " is unhandled by QualitySelectorProxyApi."); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecorderFlutterApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecorderFlutterApiImpl.java deleted file mode 100644 index 5258996ca65f..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecorderFlutterApiImpl.java +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.camera.video.Recorder; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.RecorderFlutterApi; - -public class RecorderFlutterApiImpl extends RecorderFlutterApi { - private final InstanceManager instanceManager; - - public RecorderFlutterApiImpl( - @Nullable BinaryMessenger binaryMessenger, @Nullable InstanceManager instanceManager) { - super(binaryMessenger); - this.instanceManager = instanceManager; - } - - void create( - @NonNull Recorder recorder, - @Nullable Long aspectRatio, - @Nullable Long bitRate, - @Nullable Reply reply) { - create(instanceManager.addHostCreatedInstance(recorder), aspectRatio, bitRate, reply); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecorderHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecorderHostApiImpl.java deleted file mode 100644 index 74b301e6c0b4..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecorderHostApiImpl.java +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import android.Manifest; -import android.content.Context; -import android.content.pm.PackageManager; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.VisibleForTesting; -import androidx.camera.video.FileOutputOptions; -import androidx.camera.video.PendingRecording; -import androidx.camera.video.Recorder; -import androidx.core.content.ContextCompat; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.RecorderHostApi; -import java.io.File; -import java.util.Objects; -import java.util.concurrent.Executor; - -public class RecorderHostApiImpl implements RecorderHostApi { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - @Nullable private Context context; - - @NonNull @VisibleForTesting public CameraXProxy cameraXProxy = new CameraXProxy(); - - @NonNull @VisibleForTesting public PendingRecordingFlutterApiImpl pendingRecordingFlutterApi; - - public RecorderHostApiImpl( - @Nullable BinaryMessenger binaryMessenger, - @NonNull InstanceManager instanceManager, - @Nullable Context context) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - this.context = context; - this.pendingRecordingFlutterApi = - new PendingRecordingFlutterApiImpl(binaryMessenger, instanceManager); - } - - @Override - public void create( - @NonNull Long instanceId, - @Nullable Long aspectRatio, - @Nullable Long bitRate, - @Nullable Long qualitySelector) { - if (context == null) { - throw new IllegalStateException("Context must be set to create Recorder instance."); - } - - Recorder.Builder recorderBuilder = cameraXProxy.createRecorderBuilder(); - if (aspectRatio != null) { - recorderBuilder.setAspectRatio(aspectRatio.intValue()); - } - if (bitRate != null) { - recorderBuilder.setTargetVideoEncodingBitRate(bitRate.intValue()); - } - if (qualitySelector != null) { - recorderBuilder.setQualitySelector( - Objects.requireNonNull(instanceManager.getInstance(qualitySelector))); - } - Recorder recorder = recorderBuilder.setExecutor(ContextCompat.getMainExecutor(context)).build(); - instanceManager.addDartCreatedInstance(recorder, instanceId); - } - - /** Sets the context, which is used to get the {@link Executor} passed to the Recorder builder. */ - public void setContext(@Nullable Context context) { - this.context = context; - } - - /** Gets the aspect ratio of the given {@link Recorder}. */ - @NonNull - @Override - public Long getAspectRatio(@NonNull Long identifier) { - Recorder recorder = getRecorderFromInstanceId(identifier); - return Long.valueOf(recorder.getAspectRatio()); - } - - /** Gets the target video encoding bitrate of the given {@link Recorder}. */ - @NonNull - @Override - public Long getTargetVideoEncodingBitRate(@NonNull Long identifier) { - Recorder recorder = getRecorderFromInstanceId(identifier); - return Long.valueOf(recorder.getTargetVideoEncodingBitRate()); - } - - /** - * Uses the provided {@link Recorder} to prepare a recording that will be saved to a file at the - * provided path. - */ - @NonNull - @Override - public Long prepareRecording(@NonNull Long identifier, @NonNull String path) { - if (context == null) { - throw new IllegalStateException("Context must be set to prepare recording."); - } - - Recorder recorder = getRecorderFromInstanceId(identifier); - File temporaryCaptureFile = openTempFile(path); - FileOutputOptions fileOutputOptions = - new FileOutputOptions.Builder(temporaryCaptureFile).build(); - PendingRecording pendingRecording = recorder.prepareRecording(context, fileOutputOptions); - if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) - == PackageManager.PERMISSION_GRANTED) { - pendingRecording.withAudioEnabled(); - } - pendingRecordingFlutterApi.create(pendingRecording, reply -> {}); - return Objects.requireNonNull( - instanceManager.getIdentifierForStrongReference(pendingRecording)); - } - - @Nullable - @VisibleForTesting - public File openTempFile(@NonNull String path) { - File file = null; - try { - file = new File(path); - } catch (NullPointerException | SecurityException e) { - throw new RuntimeException(e); - } - return file; - } - - private Recorder getRecorderFromInstanceId(Long instanceId) { - return (Recorder) Objects.requireNonNull(instanceManager.getInstance(instanceId)); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecorderProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecorderProxyApi.java new file mode 100644 index 000000000000..4aa83f9e66ee --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecorderProxyApi.java @@ -0,0 +1,95 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import android.Manifest; +import android.content.pm.PackageManager; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.camera.video.FileOutputOptions; +import androidx.camera.video.PendingRecording; +import androidx.camera.video.QualitySelector; +import androidx.camera.video.Recorder; +import androidx.core.content.ContextCompat; +import java.io.File; + +/** + * ProxyApi implementation for {@link Recorder}. This class may handle instantiating native object + * instances that are attached to a Dart instance or handle method calls on the associated native + * class or an instance of that class. + */ +class RecorderProxyApi extends PigeonApiRecorder { + RecorderProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public ProxyApiRegistrar getPigeonRegistrar() { + return (ProxyApiRegistrar) super.getPigeonRegistrar(); + } + + @NonNull + @Override + public Recorder pigeon_defaultConstructor( + @Nullable Long aspectRatio, + @Nullable Long targetVideoEncodingBitRate, + @Nullable androidx.camera.video.QualitySelector qualitySelector) { + final Recorder.Builder builder = new Recorder.Builder(); + if (aspectRatio != null) { + builder.setAspectRatio(aspectRatio.intValue()); + } + if (targetVideoEncodingBitRate != null) { + builder.setTargetVideoEncodingBitRate(targetVideoEncodingBitRate.intValue()); + } + if (qualitySelector != null) { + builder.setQualitySelector(qualitySelector); + } + return builder.build(); + } + + @Override + public long getAspectRatio(Recorder pigeonInstance) { + return pigeonInstance.getAspectRatio(); + } + + @Override + public long getTargetVideoEncodingBitRate(Recorder pigeonInstance) { + return pigeonInstance.getTargetVideoEncodingBitRate(); + } + + @NonNull + @Override + public PendingRecording prepareRecording(Recorder pigeonInstance, @NonNull String path) { + final File temporaryCaptureFile = openTempFile(path); + final FileOutputOptions fileOutputOptions = + new FileOutputOptions.Builder(temporaryCaptureFile).build(); + + final PendingRecording pendingRecording = + pigeonInstance.prepareRecording(getPigeonRegistrar().getContext(), fileOutputOptions); + if (ContextCompat.checkSelfPermission( + getPigeonRegistrar().getContext(), Manifest.permission.RECORD_AUDIO) + == PackageManager.PERMISSION_GRANTED) { + pendingRecording.withAudioEnabled(); + } + + return pendingRecording; + } + + @NonNull + File openTempFile(@NonNull String path) throws RuntimeException { + try { + return new File(path); + } catch (NullPointerException | SecurityException e) { + throw new RuntimeException(e); + } + } + + @NonNull + @Override + public QualitySelector getQualitySelector(@NonNull Recorder pigeonInstance) { + return pigeonInstance.getQualitySelector(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecordingFlutterApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecordingFlutterApiImpl.java deleted file mode 100644 index 8fe7082f95c8..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecordingFlutterApiImpl.java +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.camera.video.Recording; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.RecordingFlutterApi; - -public class RecordingFlutterApiImpl extends RecordingFlutterApi { - private final InstanceManager instanceManager; - - public RecordingFlutterApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - super(binaryMessenger); - this.instanceManager = instanceManager; - } - - void create(@NonNull Recording recording, Reply reply) { - create(instanceManager.addHostCreatedInstance(recording), reply); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecordingHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecordingHostApiImpl.java deleted file mode 100644 index 9288464da86b..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecordingHostApiImpl.java +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.camera.video.Recording; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.RecordingHostApi; -import java.util.Objects; - -public class RecordingHostApiImpl implements RecordingHostApi { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - - public RecordingHostApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - } - - @Override - public void close(@NonNull Long identifier) { - Recording recording = getRecordingFromInstanceId(identifier); - recording.close(); - } - - @Override - public void pause(@NonNull Long identifier) { - Recording recording = getRecordingFromInstanceId(identifier); - recording.pause(); - } - - @Override - public void resume(@NonNull Long identifier) { - Recording recording = getRecordingFromInstanceId(identifier); - recording.resume(); - } - - @Override - public void stop(@NonNull Long identifier) { - Recording recording = getRecordingFromInstanceId(identifier); - recording.stop(); - } - - private Recording getRecordingFromInstanceId(Long instanceId) { - return (Recording) Objects.requireNonNull(instanceManager.getInstance(instanceId)); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecordingProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecordingProxyApi.java new file mode 100644 index 000000000000..ced2d70b688e --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/RecordingProxyApi.java @@ -0,0 +1,39 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.camera.video.Recording; + +/** + * ProxyApi implementation for {@link Recording}. This class may handle instantiating native object + * instances that are attached to a Dart instance or handle method calls on the associated native + * class or an instance of that class. + */ +class RecordingProxyApi extends PigeonApiRecording { + RecordingProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @Override + public void close(Recording pigeonInstance) { + pigeonInstance.close(); + } + + @Override + public void pause(Recording pigeonInstance) { + pigeonInstance.pause(); + } + + @Override + public void resume(Recording pigeonInstance) { + pigeonInstance.resume(); + } + + @Override + public void stop(Recording pigeonInstance) { + pigeonInstance.stop(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionFilterHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionFilterHostApiImpl.java deleted file mode 100644 index b2c3c9e69123..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionFilterHostApiImpl.java +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import android.util.Size; -import androidx.annotation.NonNull; -import androidx.annotation.VisibleForTesting; -import androidx.camera.core.resolutionselector.ResolutionFilter; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ResolutionFilterHostApi; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ResolutionInfo; -import java.util.List; - -/** - * Host API implementation for {@link ResolutionFilter}. - * - *

This class handles instantiating and adding native object instances that are attached to a - * Dart instance or handle method calls on the associated native class or an instance of the class. - */ -public class ResolutionFilterHostApiImpl implements ResolutionFilterHostApi { - private final InstanceManager instanceManager; - private final ResolutionFilterFactory resolutionFilterFactory; - - /** - * Proxy for constructing {@link ResolutionFilter}s with particular attributes, as detailed by - * documentation below. - */ - @VisibleForTesting - public static class ResolutionFilterFactory { - /** - * Creates an instance of {@link ResolutionFilter} that moves the {@code preferredSize} to the - * front of the list of supported resolutions so that it can be prioritized by CameraX. - * - *

If the preferred {@code Size} is not found, then this creates a {@link ResolutionFilter} - * that leaves the priority of supported resolutions unadjusted. - */ - @NonNull - public ResolutionFilter createWithOnePreferredSize(@NonNull Size preferredSize) { - return new ResolutionFilter() { - @Override - @NonNull - public List filter(@NonNull List supportedSizes, int rotationDegrees) { - int preferredSizeIndex = supportedSizes.indexOf(preferredSize); - - if (preferredSizeIndex > -1) { - supportedSizes.remove(preferredSizeIndex); - supportedSizes.add(0, preferredSize); - } - - return supportedSizes; - } - }; - } - } - - /** - * Constructs a {@link ResolutionFilterHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - */ - public ResolutionFilterHostApiImpl(@NonNull InstanceManager instanceManager) { - this(instanceManager, new ResolutionFilterFactory()); - } - - /** - * Constructs a {@link ResolutionFilterHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - * @param resolutionFilterFactory proxy for constructing different kinds of {@link - * ResolutionFilter}s - */ - @VisibleForTesting - ResolutionFilterHostApiImpl( - @NonNull InstanceManager instanceManager, - @NonNull ResolutionFilterFactory resolutionFilterFactory) { - this.instanceManager = instanceManager; - this.resolutionFilterFactory = resolutionFilterFactory; - } - - /** - * Creates a {@link ResolutionFilter} that prioritizes the specified {@code preferredResolution} - * over all other resolutions. - */ - @Override - public void createWithOnePreferredSize( - @NonNull Long identifier, @NonNull ResolutionInfo preferredResolution) { - Size preferredSize = - new Size( - preferredResolution.getWidth().intValue(), preferredResolution.getHeight().intValue()); - instanceManager.addDartCreatedInstance( - resolutionFilterFactory.createWithOnePreferredSize(preferredSize), identifier); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionFilterProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionFilterProxyApi.java new file mode 100644 index 000000000000..89b073ed25e2 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionFilterProxyApi.java @@ -0,0 +1,40 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import android.util.Size; +import androidx.annotation.NonNull; +import androidx.camera.core.resolutionselector.ResolutionFilter; +import java.util.List; + +/** + * ProxyApi implementation for {@link ResolutionFilter}. This class may handle instantiating native + * object instances that are attached to a Dart instance or handle method calls on the associated + * native class or an instance of that class. + */ +class ResolutionFilterProxyApi extends PigeonApiResolutionFilter { + ResolutionFilterProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public ResolutionFilter createWithOnePreferredSize(@NonNull Size preferredSize) { + return new ResolutionFilter() { + @Override + @NonNull + public List filter(@NonNull List supportedSizes, int rotationDegrees) { + int preferredSizeIndex = supportedSizes.indexOf(preferredSize); + + if (preferredSizeIndex > -1) { + supportedSizes.remove(preferredSizeIndex); + supportedSizes.add(0, preferredSize); + } + + return supportedSizes; + } + }; + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionInfoProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionInfoProxyApi.java new file mode 100644 index 000000000000..2be20194da15 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionInfoProxyApi.java @@ -0,0 +1,26 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.camera.core.ResolutionInfo; + +/** + * ProxyApi implementation for {@link ResolutionInfo}. + * + *

This class may handle instantiating native object instances that are attached to a Dart + * instance or handle method calls on the associated native class or an instance of that class. + */ +class ResolutionInfoProxyApi extends PigeonApiResolutionInfo { + ResolutionInfoProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public android.util.Size resolution(ResolutionInfo pigeonInstance) { + return pigeonInstance.getResolution(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionSelectorHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionSelectorHostApiImpl.java deleted file mode 100644 index 0a5fe750d163..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionSelectorHostApiImpl.java +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.VisibleForTesting; -import androidx.camera.core.resolutionselector.AspectRatioStrategy; -import androidx.camera.core.resolutionselector.ResolutionFilter; -import androidx.camera.core.resolutionselector.ResolutionSelector; -import androidx.camera.core.resolutionselector.ResolutionStrategy; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ResolutionSelectorHostApi; -import java.util.Objects; - -/** - * Host API implementation for {@link ResolutionSelector}. - * - *

This class handles instantiating and adding native object instances that are attached to a - * Dart instance or handle method calls on the associated native class or an instance of the class. - */ -public class ResolutionSelectorHostApiImpl implements ResolutionSelectorHostApi { - private final InstanceManager instanceManager; - private final ResolutionSelectorProxy proxy; - - /** Proxy for constructor of {@link ResolutionSelector}. */ - @VisibleForTesting - public static class ResolutionSelectorProxy { - /** Creates an instance of {@link ResolutionSelector}. */ - @NonNull - public ResolutionSelector create( - @Nullable ResolutionStrategy resolutionStrategy, - @Nullable AspectRatioStrategy aspectRatioStrategy, - @Nullable ResolutionFilter resolutionFilter) { - final ResolutionSelector.Builder builder = new ResolutionSelector.Builder(); - if (resolutionStrategy != null) { - builder.setResolutionStrategy(resolutionStrategy); - } - if (aspectRatioStrategy != null) { - builder.setAspectRatioStrategy(aspectRatioStrategy); - } - if (resolutionFilter != null) { - builder.setResolutionFilter(resolutionFilter); - } - return builder.build(); - } - } - - /** - * Constructs a {@link ResolutionSelectorHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - */ - public ResolutionSelectorHostApiImpl(@NonNull InstanceManager instanceManager) { - this(instanceManager, new ResolutionSelectorProxy()); - } - - /** - * Constructs a {@link ResolutionSelectorHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - * @param proxy proxy for constructor of {@link ResolutionSelector} - */ - @VisibleForTesting - ResolutionSelectorHostApiImpl( - @NonNull InstanceManager instanceManager, @NonNull ResolutionSelectorProxy proxy) { - this.instanceManager = instanceManager; - this.proxy = proxy; - } - - /** - * Creates a {@link ResolutionSelector} instance with the {@link ResolutionStrategy}, {@link - * ResolutionFilter}, and {@link AspectRatio} that have the identifiers specified if provided. - */ - @Override - public void create( - @NonNull Long identifier, - @Nullable Long resolutionStrategyIdentifier, - @Nullable Long resolutionFilterIdentifier, - @Nullable Long aspectRatioStrategyIdentifier) { - instanceManager.addDartCreatedInstance( - proxy.create( - resolutionStrategyIdentifier == null - ? null - : Objects.requireNonNull(instanceManager.getInstance(resolutionStrategyIdentifier)), - aspectRatioStrategyIdentifier == null - ? null - : Objects.requireNonNull( - instanceManager.getInstance(aspectRatioStrategyIdentifier)), - resolutionFilterIdentifier == null - ? null - : Objects.requireNonNull(instanceManager.getInstance(resolutionFilterIdentifier))), - identifier); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionSelectorProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionSelectorProxyApi.java new file mode 100644 index 000000000000..fe29bd29801f --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionSelectorProxyApi.java @@ -0,0 +1,60 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.camera.core.resolutionselector.AspectRatioStrategy; +import androidx.camera.core.resolutionselector.ResolutionFilter; +import androidx.camera.core.resolutionselector.ResolutionSelector; +import androidx.camera.core.resolutionselector.ResolutionStrategy; + +/** + * ProxyApi implementation for {@link ResolutionSelector}. This class may handle instantiating + * native object instances that are attached to a Dart instance or handle method calls on the + * associated native class or an instance of that class. + */ +class ResolutionSelectorProxyApi extends PigeonApiResolutionSelector { + ResolutionSelectorProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public ResolutionSelector pigeon_defaultConstructor( + @Nullable ResolutionFilter resolutionFilter, + @Nullable ResolutionStrategy resolutionStrategy, + @Nullable AspectRatioStrategy aspectRatioStrategy) { + final ResolutionSelector.Builder builder = new ResolutionSelector.Builder(); + if (aspectRatioStrategy != null) { + builder.setAspectRatioStrategy(aspectRatioStrategy); + } + if (resolutionStrategy != null) { + builder.setResolutionStrategy(resolutionStrategy); + } + if (resolutionFilter != null) { + builder.setResolutionFilter(resolutionFilter); + } + return builder.build(); + } + + @Nullable + @Override + public ResolutionFilter resolutionFilter(@NonNull ResolutionSelector pigeonInstance) { + return pigeonInstance.getResolutionFilter(); + } + + @Nullable + @Override + public ResolutionStrategy resolutionStrategy(@NonNull ResolutionSelector pigeonInstance) { + return pigeonInstance.getResolutionStrategy(); + } + + @NonNull + @Override + public AspectRatioStrategy getAspectRatioStrategy(@NonNull ResolutionSelector pigeonInstance) { + return pigeonInstance.getAspectRatioStrategy(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionStrategyHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionStrategyHostApiImpl.java deleted file mode 100644 index 5c93fe6bd238..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionStrategyHostApiImpl.java +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import android.util.Size; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.VisibleForTesting; -import androidx.camera.core.resolutionselector.ResolutionStrategy; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ResolutionStrategyHostApi; - -/** - * Host API implementation for {@link ResolutionStrategy}. - * - *

This class handles instantiating and adding native object instances that are attached to a - * Dart instance or handle method calls on the associated native class or an instance of the class. - */ -public class ResolutionStrategyHostApiImpl implements ResolutionStrategyHostApi { - private final InstanceManager instanceManager; - private final ResolutionStrategyProxy proxy; - - /** Proxy for constructor of {@link ResolutionStrategy}. */ - @VisibleForTesting - public static class ResolutionStrategyProxy { - - /** Creates an instance of {@link ResolutionStrategy}. */ - @NonNull - public ResolutionStrategy create(@NonNull Size boundSize, @NonNull Long fallbackRule) { - return new ResolutionStrategy(boundSize, fallbackRule.intValue()); - } - } - - /** - * Constructs a {@link ResolutionStrategyHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - */ - public ResolutionStrategyHostApiImpl(@NonNull InstanceManager instanceManager) { - this(instanceManager, new ResolutionStrategyProxy()); - } - - /** - * Constructs a {@link ResolutionStrategyHostApiImpl}. - * - * @param instanceManager maintains instances stored to communicate with attached Dart objects - * @param proxy proxy for constructor of {@link ResolutionStrategy} - */ - @VisibleForTesting - ResolutionStrategyHostApiImpl( - @NonNull InstanceManager instanceManager, @NonNull ResolutionStrategyProxy proxy) { - this.instanceManager = instanceManager; - this.proxy = proxy; - } - - /** - * Creates a {@link ResolutionStrategy} instance with the {@link - * GeneratedCameraXLibrary.ResolutionInfo} bound size and {@code fallbackRule} if specified. - */ - @Override - public void create( - @NonNull Long identifier, - @Nullable GeneratedCameraXLibrary.ResolutionInfo boundSize, - @Nullable Long fallbackRule) { - ResolutionStrategy resolutionStrategy; - if (boundSize == null && fallbackRule == null) { - // Strategy that chooses the highest available resolution does not have a bound size or fallback rule. - resolutionStrategy = ResolutionStrategy.HIGHEST_AVAILABLE_STRATEGY; - } else if (boundSize == null) { - throw new IllegalArgumentException( - "A bound size must be specified if a non-null fallback rule is specified to create a valid ResolutionStrategy."); - } else { - resolutionStrategy = - proxy.create( - new Size(boundSize.getWidth().intValue(), boundSize.getHeight().intValue()), - fallbackRule); - } - instanceManager.addDartCreatedInstance(resolutionStrategy, identifier); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionStrategyProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionStrategyProxyApi.java new file mode 100644 index 000000000000..531753b4eda8 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResolutionStrategyProxyApi.java @@ -0,0 +1,78 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import android.util.Size; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.camera.core.resolutionselector.ResolutionStrategy; + +/** + * ProxyApi implementation for {@link ResolutionStrategy}. This class may handle instantiating + * native object instances that are attached to a Dart instance or handle method calls on the + * associated native class or an instance of that class. + */ +class ResolutionStrategyProxyApi extends PigeonApiResolutionStrategy { + ResolutionStrategyProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public ResolutionStrategy pigeon_defaultConstructor( + @NonNull android.util.Size boundSize, @NonNull ResolutionStrategyFallbackRule fallbackRule) { + int nativeFallbackRule = -1; + switch (fallbackRule) { + case CLOSEST_HIGHER: + nativeFallbackRule = ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER; + break; + case CLOSEST_HIGHER_THEN_LOWER: + nativeFallbackRule = ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER; + break; + case CLOSEST_LOWER: + nativeFallbackRule = ResolutionStrategy.FALLBACK_RULE_CLOSEST_LOWER; + break; + case CLOSEST_LOWER_THEN_HIGHER: + nativeFallbackRule = ResolutionStrategy.FALLBACK_RULE_CLOSEST_LOWER_THEN_HIGHER; + break; + case NONE: + nativeFallbackRule = ResolutionStrategy.FALLBACK_RULE_NONE; + break; + } + return new ResolutionStrategy(boundSize, nativeFallbackRule); + } + + @NonNull + @Override + public ResolutionStrategy highestAvailableStrategy() { + return ResolutionStrategy.HIGHEST_AVAILABLE_STRATEGY; + } + + @Nullable + @Override + public Size getBoundSize(@NonNull ResolutionStrategy pigeonInstance) { + return pigeonInstance.getBoundSize(); + } + + @NonNull + @Override + public ResolutionStrategyFallbackRule getFallbackRule( + @NonNull ResolutionStrategy pigeonInstance) { + switch (pigeonInstance.getFallbackRule()) { + case ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER: + return ResolutionStrategyFallbackRule.CLOSEST_HIGHER; + case ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER: + return ResolutionStrategyFallbackRule.CLOSEST_HIGHER_THEN_LOWER; + case ResolutionStrategy.FALLBACK_RULE_CLOSEST_LOWER: + return ResolutionStrategyFallbackRule.CLOSEST_LOWER; + case ResolutionStrategy.FALLBACK_RULE_CLOSEST_LOWER_THEN_HIGHER: + return ResolutionStrategyFallbackRule.CLOSEST_LOWER_THEN_HIGHER; + case ResolutionStrategy.FALLBACK_RULE_NONE: + return ResolutionStrategyFallbackRule.NONE; + } + + return ResolutionStrategyFallbackRule.UNKNOWN; + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResultCompat.kt b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResultCompat.kt new file mode 100644 index 000000000000..0be491897b88 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ResultCompat.kt @@ -0,0 +1,47 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax + +/** + * Provides Java compatible helper functions for the [kotlin.Result] class. + * + * The Kotlin Result class in used in the pigeon generated Kotlin code and there is no equivalent + * class in Java. The Result class can have weird behavior when passed to Java (e.g. it has a weird + * quirk where it seems to wrap itself). + */ +@Suppress("UNCHECKED_CAST") +class ResultCompat(val result: Result) { + private val value: T? = result.getOrNull() + private val exception = result.exceptionOrNull() + val isSuccess = result.isSuccess + val isFailure = result.isFailure + + companion object { + @JvmStatic + fun success(value: T, callback: Any) { + val castedCallback: (Result) -> Unit = callback as (Result) -> Unit + castedCallback(Result.success(value)) + } + + @JvmStatic + fun failure(exception: Throwable, callback: Any) { + val castedCallback: (Result) -> Unit = callback as (Result) -> Unit + castedCallback(Result.failure(exception)) + } + + @JvmStatic + fun asCompatCallback(result: (ResultCompat) -> Unit): (Result) -> Unit { + return { result(ResultCompat(it)) } + } + } + + fun getOrNull(): T? { + return value + } + + fun exceptionOrNull(): Throwable? { + return exception + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesFlutterApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesFlutterApiImpl.java deleted file mode 100644 index 2cb4ea1b2275..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesFlutterApiImpl.java +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.SystemServicesFlutterApi; - -public class SystemServicesFlutterApiImpl extends SystemServicesFlutterApi { - public SystemServicesFlutterApiImpl(@NonNull BinaryMessenger binaryMessenger) { - super(binaryMessenger); - } - - public void sendCameraError(@NonNull String errorDescription, @NonNull Reply reply) { - super.onCameraError(errorDescription, reply); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesHostApiImpl.java deleted file mode 100644 index d058d62fe224..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesHostApiImpl.java +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import android.app.Activity; -import android.content.Context; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.annotation.VisibleForTesting; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.CameraPermissionsManager.PermissionsRegistry; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraPermissionsErrorData; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.Result; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.SystemServicesHostApi; -import java.io.File; -import java.io.IOException; - -public class SystemServicesHostApiImpl implements SystemServicesHostApi { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - @Nullable private Context context; - - @VisibleForTesting public @NonNull CameraXProxy cameraXProxy = new CameraXProxy(); - @VisibleForTesting public @NonNull SystemServicesFlutterApiImpl systemServicesFlutterApi; - - private Activity activity; - private PermissionsRegistry permissionsRegistry; - - public SystemServicesHostApiImpl( - @NonNull BinaryMessenger binaryMessenger, - @NonNull InstanceManager instanceManager, - @NonNull Context context) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - this.context = context; - this.systemServicesFlutterApi = new SystemServicesFlutterApiImpl(binaryMessenger); - } - - /** Sets the context, which is used to get the cache directory. */ - public void setContext(@NonNull Context context) { - this.context = context; - } - - public void setActivity(@NonNull Activity activity) { - this.activity = activity; - } - - public void setPermissionsRegistry(@Nullable PermissionsRegistry permissionsRegistry) { - this.permissionsRegistry = permissionsRegistry; - } - - /** - * Requests camera permissions using an instance of a {@link CameraPermissionsManager}. - * - *

Will result with {@code null} if permissions were approved or there were no errors; - * otherwise, it will result with the error data explaining what went wrong. - */ - @Override - public void requestCameraPermissions( - @NonNull Boolean enableAudio, @NonNull Result result) { - if (activity == null) { - throw new IllegalStateException("Activity must be set to request camera permissions."); - } - - CameraPermissionsManager cameraPermissionsManager = - cameraXProxy.createCameraPermissionsManager(); - cameraPermissionsManager.requestPermissions( - activity, - permissionsRegistry, - enableAudio, - (String errorCode, String description) -> { - if (errorCode == null) { - result.success(null); - } else { - // If permissions are ongoing or denied, error data will be sent to be handled. - CameraPermissionsErrorData errorData = - new CameraPermissionsErrorData.Builder() - .setErrorCode(errorCode) - .setDescription(description) - .build(); - result.success(errorData); - } - }); - } - - /** Returns a path to be used to create a temp file in the current cache directory. */ - @Override - @NonNull - public String getTempFilePath(@NonNull String prefix, @NonNull String suffix) { - if (context == null) { - throw new IllegalStateException("Context must be set to create a temporary file."); - } - - try { - File path = File.createTempFile(prefix, suffix, context.getCacheDir()); - return path.toString(); - } catch (IOException | SecurityException e) { - throw new GeneratedCameraXLibrary.FlutterError( - "getTempFilePath_failure", - "SystemServicesHostApiImpl.getTempFilePath encountered an exception: " + e.toString(), - null); - } - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesManager.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesManager.java new file mode 100644 index 000000000000..6b3a434177c3 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesManager.java @@ -0,0 +1,60 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import android.app.Activity; +import android.content.Context; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import java.io.File; +import java.io.IOException; + +/** Utility class used to access system services not provided by the camerax library. */ +public abstract class SystemServicesManager { + @NonNull private final CameraPermissionsManager cameraPermissionsManager; + + /** Handles result of a permissions request. */ + public interface PermissionsResultListener { + void onResult(boolean isSuccessful, @Nullable CameraPermissionsError error); + } + + protected SystemServicesManager(@NonNull CameraPermissionsManager cameraPermissionsManager) { + this.cameraPermissionsManager = cameraPermissionsManager; + } + + abstract void onCameraError(@NonNull String description); + + @NonNull + abstract Context getContext(); + + @Nullable + abstract CameraPermissionsManager.PermissionsRegistry getPermissionsRegistry(); + + /** + * Requests camera permissions using an instance of a {@link CameraPermissionsManager}. + * + *

Will result with {@code null} if permissions were approved or there were no errors; + * otherwise, it will result with the error data explaining what went wrong. + */ + public void requestCameraPermissions( + @NonNull Boolean enableAudio, @NonNull PermissionsResultListener listener) { + if (!(getContext() instanceof Activity)) { + throw new IllegalStateException("Activity must be set to request camera permissions."); + } + + cameraPermissionsManager.requestPermissions( + (Activity) getContext(), + getPermissionsRegistry(), + enableAudio, + (CameraPermissionsError error) -> listener.onResult(error == null, error)); + } + + /** Returns a path to be used to create a temp file in the current cache directory. */ + @NonNull + public String getTempFilePath(@NonNull String prefix, @NonNull String suffix) throws IOException { + final File path = File.createTempFile(prefix, suffix, getContext().getCacheDir()); + return path.toString(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesManagerProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesManagerProxyApi.java new file mode 100644 index 000000000000..53a1626414e0 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/SystemServicesManagerProxyApi.java @@ -0,0 +1,110 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import android.content.Context; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import java.io.IOException; +import java.util.Objects; +import kotlin.Result; +import kotlin.Unit; +import kotlin.jvm.functions.Function1; + +/** + * ProxyApi implementation for {@link SystemServicesManager}. This class may handle instantiating + * native object instances that are attached to a Dart instance or handle method calls on the + * associated native class or an instance of that class. + */ +public class SystemServicesManagerProxyApi extends PigeonApiSystemServicesManager { + /** + * Implementation of {@link SystemServicesManager} that passes arguments of callback methods to + * Dart. + */ + static class SystemServicesManagerImpl extends SystemServicesManager { + final SystemServicesManagerProxyApi api; + + SystemServicesManagerImpl(@NonNull SystemServicesManagerProxyApi api) { + super(api.getPigeonRegistrar().getCameraPermissionsManager()); + this.api = api; + } + + @Override + public void onCameraError(@NonNull String errorDescription) { + api.getPigeonRegistrar() + .runOnMainThread( + new ProxyApiRegistrar.FlutterMethodRunnable() { + @Override + public void run() { + api.onCameraError( + SystemServicesManagerImpl.this, + errorDescription, + ResultCompat.asCompatCallback( + result -> { + if (result.isFailure()) { + onFailure( + "SystemServicesManager.onCameraError", + Objects.requireNonNull(result.exceptionOrNull())); + } + return null; + })); + } + }); + } + + @NonNull + @Override + Context getContext() { + return api.getPigeonRegistrar().getContext(); + } + + @Nullable + @Override + CameraPermissionsManager.PermissionsRegistry getPermissionsRegistry() { + return api.getPigeonRegistrar().getPermissionsRegistry(); + } + } + + SystemServicesManagerProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public ProxyApiRegistrar getPigeonRegistrar() { + return (ProxyApiRegistrar) super.getPigeonRegistrar(); + } + + @NonNull + @Override + public SystemServicesManager pigeon_defaultConstructor() { + return new SystemServicesManagerImpl(this); + } + + @Override + public void requestCameraPermissions( + @NonNull SystemServicesManager pigeonInstance, + boolean enableAudio, + @NonNull Function1, Unit> callback) { + pigeonInstance.requestCameraPermissions( + enableAudio, (isSuccessful, error) -> ResultCompat.success(error, callback)); + } + + @NonNull + @Override + public String getTempFilePath( + @NonNull SystemServicesManager pigeonInstance, + @NonNull String prefix, + @NonNull String suffix) { + try { + return pigeonInstance.getTempFilePath(prefix, suffix); + } catch (IOException e) { + throw new RuntimeException( + "getTempFilePath_failure", + new Throwable( + "SystemServicesHostApiImpl.getTempFilePath encountered an exception: " + e)); + } + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoCaptureFlutterApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoCaptureFlutterApiImpl.java deleted file mode 100644 index 3e316fa57746..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoCaptureFlutterApiImpl.java +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.camera.video.Recorder; -import androidx.camera.video.VideoCapture; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.VideoCaptureFlutterApi; - -public class VideoCaptureFlutterApiImpl extends VideoCaptureFlutterApi { - public VideoCaptureFlutterApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - super(binaryMessenger); - this.instanceManager = instanceManager; - } - - private final InstanceManager instanceManager; - - void create(@NonNull VideoCapture videoCapture, Reply reply) { - create(instanceManager.addHostCreatedInstance(videoCapture), reply); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoCaptureHostApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoCaptureHostApiImpl.java deleted file mode 100644 index 1c849ee09379..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoCaptureHostApiImpl.java +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.annotation.VisibleForTesting; -import androidx.camera.video.Recorder; -import androidx.camera.video.VideoCapture; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.VideoCaptureHostApi; -import java.util.Objects; - -public class VideoCaptureHostApiImpl implements VideoCaptureHostApi { - private final BinaryMessenger binaryMessenger; - private final InstanceManager instanceManager; - - public VideoCaptureHostApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - this.binaryMessenger = binaryMessenger; - this.instanceManager = instanceManager; - } - - @Override - @NonNull - public Long withOutput(@NonNull Long videoOutputId) { - Recorder recorder = - (Recorder) Objects.requireNonNull(instanceManager.getInstance(videoOutputId)); - VideoCapture videoCapture = VideoCapture.withOutput(recorder); - final VideoCaptureFlutterApiImpl videoCaptureFlutterApi = - getVideoCaptureFlutterApiImpl(binaryMessenger, instanceManager); - videoCaptureFlutterApi.create(videoCapture, result -> {}); - return Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(videoCapture)); - } - - @Override - @NonNull - public Long getOutput(@NonNull Long identifier) { - VideoCapture videoCapture = getVideoCaptureInstance(identifier); - Recorder recorder = videoCapture.getOutput(); - return Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(recorder)); - } - - @VisibleForTesting - @NonNull - public VideoCaptureFlutterApiImpl getVideoCaptureFlutterApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - return new VideoCaptureFlutterApiImpl(binaryMessenger, instanceManager); - } - - /** Dynamically sets the target rotation of the {@link VideoCapture}. */ - @Override - public void setTargetRotation(@NonNull Long identifier, @NonNull Long rotation) { - VideoCapture videoCapture = getVideoCaptureInstance(identifier); - videoCapture.setTargetRotation(rotation.intValue()); - } - - /** - * Retrieves the {@link VideoCapture} instance associated with the specified {@code identifier}. - */ - private VideoCapture getVideoCaptureInstance(@NonNull Long identifier) { - return Objects.requireNonNull(instanceManager.getInstance(identifier)); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoCaptureProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoCaptureProxyApi.java new file mode 100644 index 000000000000..6d95200b8583 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoCaptureProxyApi.java @@ -0,0 +1,37 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.camera.video.VideoCapture; +import androidx.camera.video.VideoOutput; + +/** + * ProxyApi implementation for {@link VideoCapture}. This class may handle instantiating native + * object instances that are attached to a Dart instance or handle method calls on the associated + * native class or an instance of that class. + */ +class VideoCaptureProxyApi extends PigeonApiVideoCapture { + VideoCaptureProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @NonNull + @Override + public VideoCapture withOutput(@NonNull VideoOutput videoOutput) { + return VideoCapture.withOutput(videoOutput); + } + + @NonNull + @Override + public VideoOutput getOutput(VideoCapture pigeonInstance) { + return pigeonInstance.getOutput(); + } + + @Override + public void setTargetRotation(VideoCapture pigeonInstance, long rotation) { + pigeonInstance.setTargetRotation((int) rotation); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoRecordEventListener.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoRecordEventListener.java new file mode 100644 index 000000000000..61fef6f80578 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoRecordEventListener.java @@ -0,0 +1,12 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.camera.video.VideoRecordEvent; + +public interface VideoRecordEventListener { + void onEvent(@NonNull VideoRecordEvent event); +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoRecordEventListenerProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoRecordEventListenerProxyApi.java new file mode 100644 index 000000000000..58078f7f78fc --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/VideoRecordEventListenerProxyApi.java @@ -0,0 +1,66 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.camera.video.VideoRecordEvent; +import java.util.Objects; + +/** + * ProxyApi implementation for {@link VideoRecordEventListener}. This class may handle instantiating + * native object instances that are attached to a Dart instance or handle method calls on the + * associated native class or an instance of that class. + */ +class VideoRecordEventListenerProxyApi extends PigeonApiVideoRecordEventListener { + VideoRecordEventListenerProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + /** + * Implementation of {@link VideoRecordEventListener} that passes arguments of callback methods to + * Dart. + */ + static class VideoRecordEventListenerImpl implements VideoRecordEventListener { + final VideoRecordEventListenerProxyApi api; + + VideoRecordEventListenerImpl(@NonNull VideoRecordEventListenerProxyApi api) { + this.api = api; + } + + @Override + public void onEvent(@NonNull VideoRecordEvent event) { + api.getPigeonRegistrar() + .runOnMainThread( + new ProxyApiRegistrar.FlutterMethodRunnable() { + @Override + public void run() { + api.onEvent( + VideoRecordEventListenerImpl.this, + event, + ResultCompat.asCompatCallback( + result -> { + if (result.isFailure()) { + onFailure( + "VideoRecordEventListener.onEvent", + Objects.requireNonNull(result.exceptionOrNull())); + } + return null; + })); + } + }); + } + } + + @NonNull + @Override + public ProxyApiRegistrar getPigeonRegistrar() { + return (ProxyApiRegistrar) super.getPigeonRegistrar(); + } + + @NonNull + @Override + public VideoRecordEventListener pigeon_defaultConstructor() { + return new VideoRecordEventListenerImpl(this); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ZoomStateFlutterApiImpl.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ZoomStateFlutterApiImpl.java deleted file mode 100644 index 4f5abdd6d181..000000000000 --- a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ZoomStateFlutterApiImpl.java +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import androidx.annotation.NonNull; -import androidx.camera.core.ZoomState; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ZoomStateFlutterApi; - -public class ZoomStateFlutterApiImpl extends ZoomStateFlutterApi { - private final InstanceManager instanceManager; - - public ZoomStateFlutterApiImpl( - @NonNull BinaryMessenger binaryMessenger, @NonNull InstanceManager instanceManager) { - super(binaryMessenger); - this.instanceManager = instanceManager; - } - - /** - * Creates a {@link ZoomState} on the Dart side with its minimum zoom ratio and maximum zoom - * ratio. - */ - void create(@NonNull ZoomState zoomState, @NonNull Reply reply) { - if (instanceManager.containsInstance(zoomState)) { - return; - } - - final Float minZoomRatio = zoomState.getMinZoomRatio(); - final Float maxZoomRatio = zoomState.getMaxZoomRatio(); - create( - instanceManager.addHostCreatedInstance(zoomState), - minZoomRatio.doubleValue(), - maxZoomRatio.doubleValue(), - reply); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ZoomStateProxyApi.java b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ZoomStateProxyApi.java new file mode 100644 index 000000000000..e8c048ef9b2a --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/main/java/io/flutter/plugins/camerax/ZoomStateProxyApi.java @@ -0,0 +1,29 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import androidx.annotation.NonNull; +import androidx.camera.core.ZoomState; + +/** + * ProxyApi implementation for {@link ZoomState}. This class may handle instantiating native object + * instances that are attached to a Dart instance or handle method calls on the associated native + * class or an instance of that class. + */ +class ZoomStateProxyApi extends PigeonApiZoomState { + ZoomStateProxyApi(@NonNull ProxyApiRegistrar pigeonRegistrar) { + super(pigeonRegistrar); + } + + @Override + public double minZoomRatio(ZoomState pigeonInstance) { + return pigeonInstance.getMinZoomRatio(); + } + + @Override + public double maxZoomRatio(ZoomState pigeonInstance) { + return pigeonInstance.getMaxZoomRatio(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/test/java/android/util/Range.java b/packages/camera/camera_android_camerax/android/src/test/java/android/util/Range.java new file mode 100644 index 000000000000..48f2c5f7d536 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/test/java/android/util/Range.java @@ -0,0 +1,25 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package android.util; + +// Creates an implementation of Range that can be used with unittests and the JVM. +// Typically android.util.Range does nothing when not used with an Android environment. +public final class Range> { + private final T lower; + private final T upper; + + public Range(T lower, T upper) { + this.lower = lower; + this.upper = upper; + } + + public T getLower() { + return lower; + } + + public T getUpper() { + return upper; + } +} diff --git a/packages/camera/camera_android_camerax/android/src/test/java/android/util/Rational.java b/packages/camera/camera_android_camerax/android/src/test/java/android/util/Rational.java new file mode 100644 index 000000000000..66cb22a4049d --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/test/java/android/util/Rational.java @@ -0,0 +1,22 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package android.util; + +// Creates an implementation of Rational that can be used with unittests and the JVM. +// Typically android.util.Rational does nothing when not used with an Android environment. + +public final class Rational { + private final int numerator; + private final int denominator; + + public Rational(int numerator, int denominator) { + this.numerator = numerator; + this.denominator = denominator; + } + + public double doubleValue() { + return (double) numerator / denominator; + } +} diff --git a/packages/camera/camera_android_camerax/android/src/test/java/android/util/Size.java b/packages/camera/camera_android_camerax/android/src/test/java/android/util/Size.java new file mode 100644 index 000000000000..ec007cbcf5ab --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/test/java/android/util/Size.java @@ -0,0 +1,39 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package android.util; + +// Creates an implementation of Range that can be used with unittests and the JVM. +// Typically android.util.Size does nothing when not used with an Android environment. + +public final class Size { + private final int width; + private final int height; + + public Size(int width, int height) { + this.width = width; + this.height = height; + } + + public int getWidth() { + return width; + } + + public int getHeight() { + return height; + } + + public boolean equals(Object obj) { + if (obj instanceof Size) { + return ((Size) obj).width == width && ((Size) obj).height == height; + } + + return false; + } + + @Override + public int hashCode() { + return super.hashCode(); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/AnalyzerTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/AnalyzerTest.java index bcc2648e4eb7..f8f72677e2b1 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/AnalyzerTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/AnalyzerTest.java @@ -4,103 +4,33 @@ package io.flutter.plugins.camerax; -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import androidx.camera.core.ImageProxy; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.AnalyzerFlutterApi; -import java.util.Objects; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; public class AnalyzerTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock public AnalyzerHostApiImpl.AnalyzerImpl mockImageAnalysisAnalyzer; - @Mock public BinaryMessenger mockBinaryMessenger; - @Mock public AnalyzerFlutterApi mockFlutterApi; - @Mock public AnalyzerHostApiImpl.AnalyzerProxy mockProxy; - - InstanceManager instanceManager; - - @Before - public void setUp() { - instanceManager = InstanceManager.create(identifier -> {}); - } - - @After - public void tearDown() { - instanceManager.stopFinalizationListener(); - } - @Test - public void hostApiCreate_makesCallToCreateAnalyzerInstanceWithExpectedIdentifier() { - final AnalyzerHostApiImpl hostApi = - new AnalyzerHostApiImpl(mockBinaryMessenger, instanceManager, mockProxy); - final long instanceIdentifier = 90; - - when(mockProxy.create(mockBinaryMessenger, instanceManager)) - .thenReturn(mockImageAnalysisAnalyzer); + public void pigeon_defaultConstructor_makesCallToCreateAnalyzerInstance() { + final PigeonApiAnalyzer api = new TestProxyApiRegistrar().getPigeonApiAnalyzer(); - hostApi.create(instanceIdentifier); - - assertEquals(instanceManager.getInstance(instanceIdentifier), mockImageAnalysisAnalyzer); - } - - @Test - public void flutterApiCreate_makesCallToDartCreate() { - final AnalyzerFlutterApiImpl flutterApi = - new AnalyzerFlutterApiImpl(mockBinaryMessenger, instanceManager); - - flutterApi.setApi(mockFlutterApi); - - flutterApi.create(mockImageAnalysisAnalyzer, reply -> {}); - final long instanceIdentifier = - Objects.requireNonNull( - instanceManager.getIdentifierForStrongReference(mockImageAnalysisAnalyzer)); - - verify(mockFlutterApi).create(eq(instanceIdentifier), any()); + assertTrue(api.pigeon_defaultConstructor() instanceof AnalyzerProxyApi.AnalyzerImpl); } @Test public void analyze_makesCallToDartAnalyze() { - final AnalyzerFlutterApiImpl flutterApi = - new AnalyzerFlutterApiImpl(mockBinaryMessenger, instanceManager); - final ImageProxy mockImageProxy = mock(ImageProxy.class); - final long mockImageProxyIdentifier = 97; - final AnalyzerHostApiImpl.AnalyzerImpl instance = - new AnalyzerHostApiImpl.AnalyzerImpl(mockBinaryMessenger, instanceManager); - final ImageProxyFlutterApiImpl mockImageProxyApi = - spy(new ImageProxyFlutterApiImpl(mockBinaryMessenger, instanceManager)); - final long instanceIdentifier = 20; - final long format = 3; - final long height = 2; - final long width = 1; - - flutterApi.setApi(mockFlutterApi); - instance.setApi(flutterApi); - instance.imageProxyApi = mockImageProxyApi; - - instanceManager.addDartCreatedInstance(instance, instanceIdentifier); - instanceManager.addDartCreatedInstance(mockImageProxy, mockImageProxyIdentifier); - - when(mockImageProxy.getFormat()).thenReturn(3); - when(mockImageProxy.getHeight()).thenReturn(2); - when(mockImageProxy.getWidth()).thenReturn(1); + final AnalyzerProxyApi mockApi = mock(AnalyzerProxyApi.class); + when(mockApi.getPigeonRegistrar()).thenReturn(new TestProxyApiRegistrar()); - instance.analyze(mockImageProxy); + final AnalyzerProxyApi.AnalyzerImpl instance = new AnalyzerProxyApi.AnalyzerImpl(mockApi); + final androidx.camera.core.ImageProxy image = mock(ImageProxy.class); + instance.analyze(image); - verify(mockFlutterApi).analyze(eq(instanceIdentifier), eq(mockImageProxyIdentifier), any()); - verify(mockImageProxyApi).create(eq(mockImageProxy), eq(format), eq(height), eq(width), any()); + verify(mockApi).analyze(eq(instance), eq(image), any()); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/AspectRatioStrategyTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/AspectRatioStrategyTest.java index 02e757dc39fa..61b9062fb2e0 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/AspectRatioStrategyTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/AspectRatioStrategyTest.java @@ -5,47 +5,49 @@ package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import androidx.camera.core.resolutionselector.AspectRatioStrategy; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; public class AspectRatioStrategyTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock public AspectRatioStrategy mockAspectRatioStrategy; - @Mock public AspectRatioStrategyHostApiImpl.AspectRatioStrategyProxy mockProxy; + @Test + public void pigeon_defaultConstructor_createsExpectedAspectRatioStrategyInstance() { + final PigeonApiAspectRatioStrategy api = + new TestProxyApiRegistrar().getPigeonApiAspectRatioStrategy(); + + final AspectRatioStrategy instance = + api.pigeon_defaultConstructor( + io.flutter.plugins.camerax.AspectRatio.RATIO16TO9, + io.flutter.plugins.camerax.AspectRatioStrategyFallbackRule.AUTO); + assertEquals(instance.getPreferredAspectRatio(), androidx.camera.core.AspectRatio.RATIO_16_9); + assertEquals(instance.getFallbackRule(), AspectRatioStrategy.FALLBACK_RULE_AUTO); + } - InstanceManager instanceManager; + @Test + public void getFallbackRule_returnsFallbackRuleOfInstance() { + final PigeonApiAspectRatioStrategy api = + new TestProxyApiRegistrar().getPigeonApiAspectRatioStrategy(); - @Before - public void setUp() { - instanceManager = InstanceManager.create(identifier -> {}); - } + final AspectRatioStrategy instance = mock(AspectRatioStrategy.class); + final AspectRatioStrategyFallbackRule value = + io.flutter.plugins.camerax.AspectRatioStrategyFallbackRule.AUTO; + when(instance.getFallbackRule()).thenReturn(AspectRatioStrategy.FALLBACK_RULE_AUTO); - @After - public void tearDown() { - instanceManager.stopFinalizationListener(); + assertEquals(value, api.getFallbackRule(instance)); } @Test - public void hostApiCreate_createsExpectedAspectRatioStrategyInstance() { - final Long preferredAspectRatio = 0L; - final Long fallbackRule = 1L; - - when(mockProxy.create(preferredAspectRatio, fallbackRule)).thenReturn(mockAspectRatioStrategy); - - final AspectRatioStrategyHostApiImpl hostApi = - new AspectRatioStrategyHostApiImpl(instanceManager, mockProxy); + public void getPreferredAspectRatio_returnAspectRatioOfInstance() { + final PigeonApiAspectRatioStrategy api = + new TestProxyApiRegistrar().getPigeonApiAspectRatioStrategy(); - final long instanceIdentifier = 0; - hostApi.create(instanceIdentifier, preferredAspectRatio, fallbackRule); + final AspectRatioStrategy instance = mock(AspectRatioStrategy.class); + final AspectRatio value = io.flutter.plugins.camerax.AspectRatio.RATIO16TO9; + when(instance.getPreferredAspectRatio()) + .thenReturn(androidx.camera.core.AspectRatio.RATIO_16_9); - assertEquals(instanceManager.getInstance(instanceIdentifier), mockAspectRatioStrategy); + assertEquals(value, api.getPreferredAspectRatio(instance)); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/Camera2CameraControlTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/Camera2CameraControlTest.java index bec9d9a22a72..2de54a180493 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/Camera2CameraControlTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/Camera2CameraControlTest.java @@ -5,126 +5,123 @@ package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import android.content.Context; import androidx.camera.camera2.interop.Camera2CameraControl; import androidx.camera.camera2.interop.CaptureRequestOptions; import androidx.camera.core.CameraControl; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; -import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; import org.mockito.stubbing.Answer; public class Camera2CameraControlTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public Camera2CameraControl mockCamera2CameraControl; - - InstanceManager testInstanceManager; - - @Before - public void setUp() { - testInstanceManager = InstanceManager.create(identifier -> {}); - } - - @After - public void tearDown() { - testInstanceManager.stopFinalizationListener(); - } - @Test - public void create_createsInstanceFromCameraControlInstance() { - final Camera2CameraControlHostApiImpl hostApi = - new Camera2CameraControlHostApiImpl(testInstanceManager, mock(Context.class)); - final long instanceIdentifier = 40; + public void from_createsInstanceFromCameraControlInstance() { + final PigeonApiCamera2CameraControl api = + new TestProxyApiRegistrar().getPigeonApiCamera2CameraControl(); + final CameraControl mockCameraControl = mock(CameraControl.class); - final long cameraControlIdentifier = 29; + final Camera2CameraControl mockCamera2CameraControl = mock(Camera2CameraControl.class); - testInstanceManager.addDartCreatedInstance(mockCameraControl, cameraControlIdentifier); try (MockedStatic mockedCamera2CameraControl = Mockito.mockStatic(Camera2CameraControl.class)) { mockedCamera2CameraControl .when(() -> Camera2CameraControl.from(mockCameraControl)) .thenAnswer((Answer) invocation -> mockCamera2CameraControl); - hostApi.create(instanceIdentifier, cameraControlIdentifier); - assertEquals(testInstanceManager.getInstance(instanceIdentifier), mockCamera2CameraControl); + assertEquals(api.from(mockCameraControl), mockCamera2CameraControl); } } + @SuppressWarnings("unchecked") @Test - public void addCaptureRequestOptions_respondsAsExpectedToSuccessfulAndFailedAttempts() { - final Camera2CameraControlHostApiImpl hostApi = - new Camera2CameraControlHostApiImpl(testInstanceManager, mock(Context.class)); - final long instanceIdentifier = 0; + public void addCaptureRequestOptions_respondsAsExpectedToSuccessful() { + final PigeonApiCamera2CameraControl api = + new TestProxyApiRegistrar().getPigeonApiCamera2CameraControl(); - final CaptureRequestOptions mockCaptureRequestOptions = mock(CaptureRequestOptions.class); - final long captureRequestOptionsIdentifier = 8; + final Camera2CameraControl instance = mock(Camera2CameraControl.class); + final androidx.camera.camera2.interop.CaptureRequestOptions bundle = + mock(CaptureRequestOptions.class); - testInstanceManager.addDartCreatedInstance(mockCamera2CameraControl, instanceIdentifier); - testInstanceManager.addDartCreatedInstance( - mockCaptureRequestOptions, captureRequestOptionsIdentifier); + final ListenableFuture addCaptureRequestOptionsFuture = mock(ListenableFuture.class); + when(instance.addCaptureRequestOptions(bundle)).thenReturn(addCaptureRequestOptionsFuture); try (MockedStatic mockedFutures = Mockito.mockStatic(Futures.class)) { - @SuppressWarnings("unchecked") - final ListenableFuture addCaptureRequestOptionsFuture = mock(ListenableFuture.class); - - when(mockCamera2CameraControl.addCaptureRequestOptions(mockCaptureRequestOptions)) - .thenReturn(addCaptureRequestOptionsFuture); - - @SuppressWarnings("unchecked") final ArgumentCaptor> futureCallbackCaptor = ArgumentCaptor.forClass(FutureCallback.class); - // Test successfully adding capture request options. - @SuppressWarnings("unchecked") - final GeneratedCameraXLibrary.Result successfulMockResult = - mock(GeneratedCameraXLibrary.Result.class); - - hostApi.addCaptureRequestOptions( - instanceIdentifier, captureRequestOptionsIdentifier, successfulMockResult); + final boolean[] isSuccess = {false}; + api.addCaptureRequestOptions( + instance, + bundle, + ResultCompat.asCompatCallback( + reply -> { + isSuccess[0] = reply.isSuccess(); + return null; + })); + + verify(instance).addCaptureRequestOptions(bundle); mockedFutures.verify( () -> Futures.addCallback( eq(addCaptureRequestOptionsFuture), futureCallbackCaptor.capture(), any())); mockedFutures.clearInvocations(); - FutureCallback successfulCallback = futureCallbackCaptor.getValue(); + final FutureCallback successfulCallback = futureCallbackCaptor.getValue(); successfulCallback.onSuccess(mock(Void.class)); - verify(successfulMockResult).success(null); - - // Test failed attempt to add capture request options. - @SuppressWarnings("unchecked") - final GeneratedCameraXLibrary.Result failedMockResult = - mock(GeneratedCameraXLibrary.Result.class); - final Throwable testThrowable = new Throwable(); - hostApi.addCaptureRequestOptions( - instanceIdentifier, captureRequestOptionsIdentifier, failedMockResult); + assertTrue(isSuccess[0]); + } + } + + @SuppressWarnings("unchecked") + @Test + public void addCaptureRequestOptions_respondsAsExpectedToFailure() { + final PigeonApiCamera2CameraControl api = + new TestProxyApiRegistrar().getPigeonApiCamera2CameraControl(); + + final Camera2CameraControl instance = mock(Camera2CameraControl.class); + final androidx.camera.camera2.interop.CaptureRequestOptions bundle = + mock(CaptureRequestOptions.class); + + final ListenableFuture addCaptureRequestOptionsFuture = mock(ListenableFuture.class); + when(instance.addCaptureRequestOptions(bundle)).thenReturn(addCaptureRequestOptionsFuture); + + try (MockedStatic mockedFutures = Mockito.mockStatic(Futures.class)) { + final ArgumentCaptor> futureCallbackCaptor = + ArgumentCaptor.forClass(FutureCallback.class); + + final boolean[] isFailure = {false}; + api.addCaptureRequestOptions( + instance, + bundle, + ResultCompat.asCompatCallback( + reply -> { + isFailure[0] = reply.isFailure(); + return null; + })); + + verify(instance).addCaptureRequestOptions(bundle); mockedFutures.verify( () -> Futures.addCallback( eq(addCaptureRequestOptionsFuture), futureCallbackCaptor.capture(), any())); + mockedFutures.clearInvocations(); - FutureCallback failedCallback = futureCallbackCaptor.getValue(); + final FutureCallback successfulCallback = futureCallbackCaptor.getValue(); - failedCallback.onFailure(testThrowable); - verify(failedMockResult).error(testThrowable); + successfulCallback.onFailure(new Throwable()); + assertTrue(isFailure[0]); } } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/Camera2CameraInfoTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/Camera2CameraInfoTest.java index a5ab10ff79bd..8056de6496c6 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/Camera2CameraInfoTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/Camera2CameraInfoTest.java @@ -5,57 +5,25 @@ package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.hardware.camera2.CameraCharacteristics; -import android.hardware.camera2.CameraMetadata; import androidx.camera.camera2.interop.Camera2CameraInfo; import androidx.camera.core.CameraInfo; -import io.flutter.plugin.common.BinaryMessenger; -import java.util.Objects; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; import org.mockito.stubbing.Answer; public class Camera2CameraInfoTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public Camera2CameraInfo mockCamera2CameraInfo; - - InstanceManager testInstanceManager; - - @Before - public void setUp() { - testInstanceManager = InstanceManager.create(identifier -> {}); - } - - @After - public void tearDown() { - testInstanceManager.stopFinalizationListener(); - } - @Test - public void createFrom_createsInstanceFromCameraInfoInstance() { - final Camera2CameraInfoHostApiImpl hostApi = - new Camera2CameraInfoHostApiImpl(mock(BinaryMessenger.class), testInstanceManager); - final long camera2CameraInfoIdentifier = 60; - final CameraInfo mockCameraInfo = mock(CameraInfo.class); - final long cameraInfoIdentifier = 92; + public void from_createsInstanceFromCameraInfoInstance() { + final PigeonApiCamera2CameraInfo api = + new TestProxyApiRegistrar().getPigeonApiCamera2CameraInfo(); - testInstanceManager.addDartCreatedInstance(mockCameraInfo, cameraInfoIdentifier); - testInstanceManager.addDartCreatedInstance(mockCamera2CameraInfo, camera2CameraInfoIdentifier); + final CameraInfo mockCameraInfo = mock(CameraInfo.class); + final Camera2CameraInfo mockCamera2CameraInfo = mock(Camera2CameraInfo.class); try (MockedStatic mockedCamera2CameraInfo = Mockito.mockStatic(Camera2CameraInfo.class)) { @@ -63,52 +31,33 @@ public void createFrom_createsInstanceFromCameraInfoInstance() { .when(() -> Camera2CameraInfo.from(mockCameraInfo)) .thenAnswer((Answer) invocation -> mockCamera2CameraInfo); - hostApi.createFrom(cameraInfoIdentifier); - assertEquals( - testInstanceManager.getInstance(camera2CameraInfoIdentifier), mockCamera2CameraInfo); + assertEquals(api.from(mockCameraInfo), mockCamera2CameraInfo); } } - @Test - public void getSupportedHardwareLevel_returnsExpectedLevel() { - final Camera2CameraInfoHostApiImpl hostApi = - new Camera2CameraInfoHostApiImpl(mock(BinaryMessenger.class), testInstanceManager); - final long camera2CameraInfoIdentifier = 3; - final int expectedHardwareLevel = CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_FULL; - - testInstanceManager.addDartCreatedInstance(mockCamera2CameraInfo, camera2CameraInfoIdentifier); - when(mockCamera2CameraInfo.getCameraCharacteristic( - CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL)) - .thenReturn(expectedHardwareLevel); - - assertEquals( - expectedHardwareLevel, - hostApi.getSupportedHardwareLevel(camera2CameraInfoIdentifier).intValue()); - } - @Test public void getCameraId_returnsExpectedId() { - final Camera2CameraInfoHostApiImpl hostApi = - new Camera2CameraInfoHostApiImpl(mock(BinaryMessenger.class), testInstanceManager); - final long camera2CameraInfoIdentifier = 13; - final String expectedCameraId = "testCameraId"; + final PigeonApiCamera2CameraInfo api = + new TestProxyApiRegistrar().getPigeonApiCamera2CameraInfo(); - testInstanceManager.addDartCreatedInstance(mockCamera2CameraInfo, camera2CameraInfoIdentifier); - when(mockCamera2CameraInfo.getCameraId()).thenReturn(expectedCameraId); + final Camera2CameraInfo instance = mock(Camera2CameraInfo.class); + final String value = "myString"; + when(instance.getCameraId()).thenReturn(value); - assertEquals(expectedCameraId, hostApi.getCameraId(camera2CameraInfoIdentifier)); + assertEquals(value, api.getCameraId(instance)); } + @SuppressWarnings("unchecked") @Test - public void flutterApiCreate_makesCallToCreateInstanceOnDartSide() { - final Camera2CameraInfoFlutterApiImpl spyFlutterApi = - spy(new Camera2CameraInfoFlutterApiImpl(mock(BinaryMessenger.class), testInstanceManager)); + public void getCameraCharacteristic_returnsCorrespondingValueOfKey() { + final PigeonApiCamera2CameraInfo api = + new TestProxyApiRegistrar().getPigeonApiCamera2CameraInfo(); - spyFlutterApi.create(mockCamera2CameraInfo, reply -> {}); + final Camera2CameraInfo instance = mock(Camera2CameraInfo.class); + final CameraCharacteristics.Key key = mock(CameraCharacteristics.Key.class); + final int value = -1; + when(instance.getCameraCharacteristic(key)).thenReturn(value); - final long identifier = - Objects.requireNonNull( - testInstanceManager.getIdentifierForStrongReference(mockCamera2CameraInfo)); - verify(spyFlutterApi).create(eq(identifier), any()); + assertEquals(value, api.getCameraCharacteristic(instance, key)); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraAndroidCameraxPluginTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraAndroidCameraxPluginTest.java index fcca0f8eb0bc..d94e13dffd09 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraAndroidCameraxPluginTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraAndroidCameraxPluginTest.java @@ -4,13 +4,11 @@ package io.flutter.plugins.camerax; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.Mockito.withSettings; @@ -20,10 +18,10 @@ import androidx.lifecycle.LifecycleOwner; import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; -import io.flutter.plugins.camerax.CameraPermissionsManager.PermissionsRegistry; +import io.flutter.plugin.common.BinaryMessenger; +import io.flutter.view.TextureRegistry; import org.junit.Rule; import org.junit.Test; -import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; @@ -36,352 +34,184 @@ public class CameraAndroidCameraxPluginTest { @Test public void onAttachedToActivity_setsLifecycleOwnerAsActivityIfLifecycleOwnerAsNeeded() { - final CameraAndroidCameraxPlugin plugin = spy(new CameraAndroidCameraxPlugin()); final Activity mockActivity = mock(Activity.class, withSettings().extraInterfaces(LifecycleOwner.class)); - final ProcessCameraProviderHostApiImpl mockProcessCameraProviderHostApiImpl = - mock(ProcessCameraProviderHostApiImpl.class); - final LiveDataHostApiImpl mockLiveDataHostApiImpl = mock(LiveDataHostApiImpl.class); - doNothing().when(plugin).setUp(any(), any(), any()); + when(flutterPluginBinding.getBinaryMessenger()).thenReturn(mock(BinaryMessenger.class)); + when(flutterPluginBinding.getApplicationContext()).thenReturn(mock(Context.class)); + when(flutterPluginBinding.getTextureRegistry()).thenReturn(mock(TextureRegistry.class)); when(activityPluginBinding.getActivity()).thenReturn(mockActivity); - plugin.processCameraProviderHostApiImpl = mockProcessCameraProviderHostApiImpl; - plugin.liveDataHostApiImpl = mockLiveDataHostApiImpl; - plugin.systemServicesHostApiImpl = mock(SystemServicesHostApiImpl.class); - plugin.deviceOrientationManagerHostApiImpl = mock(DeviceOrientationManagerHostApiImpl.class); - + final CameraAndroidCameraxPlugin plugin = new CameraAndroidCameraxPlugin(); plugin.onAttachedToEngine(flutterPluginBinding); plugin.onAttachedToActivity(activityPluginBinding); - verify(mockProcessCameraProviderHostApiImpl).setLifecycleOwner(any(LifecycleOwner.class)); - verify(mockLiveDataHostApiImpl).setLifecycleOwner(any(LifecycleOwner.class)); + assertNotNull(plugin.proxyApiRegistrar); + assertEquals(plugin.proxyApiRegistrar.getActivity(), mockActivity); + assertEquals(plugin.proxyApiRegistrar.getLifecycleOwner(), mockActivity); } @Test public void onAttachedToActivity_setsLifecycleOwnerAsProxyLifecycleProviderIfActivityNotLifecycleOwnerAsNeeded() { - final CameraAndroidCameraxPlugin plugin = spy(new CameraAndroidCameraxPlugin()); final Activity mockActivity = mock(Activity.class); - final ProcessCameraProviderHostApiImpl mockProcessCameraProviderHostApiImpl = - mock(ProcessCameraProviderHostApiImpl.class); - final LiveDataHostApiImpl mockLiveDataHostApiImpl = mock(LiveDataHostApiImpl.class); - - doNothing().when(plugin).setUp(any(), any(), any()); - when(activityPluginBinding.getActivity()).thenReturn(mockActivity); when(mockActivity.getApplication()).thenReturn(mock(Application.class)); - plugin.processCameraProviderHostApiImpl = mockProcessCameraProviderHostApiImpl; - plugin.liveDataHostApiImpl = mockLiveDataHostApiImpl; - plugin.systemServicesHostApiImpl = mock(SystemServicesHostApiImpl.class); - plugin.deviceOrientationManagerHostApiImpl = mock(DeviceOrientationManagerHostApiImpl.class); + when(flutterPluginBinding.getBinaryMessenger()).thenReturn(mock(BinaryMessenger.class)); + when(flutterPluginBinding.getApplicationContext()).thenReturn(mock(Context.class)); + when(flutterPluginBinding.getTextureRegistry()).thenReturn(mock(TextureRegistry.class)); + when(activityPluginBinding.getActivity()).thenReturn(mockActivity); + final CameraAndroidCameraxPlugin plugin = new CameraAndroidCameraxPlugin(); plugin.onAttachedToEngine(flutterPluginBinding); plugin.onAttachedToActivity(activityPluginBinding); - verify(mockProcessCameraProviderHostApiImpl) - .setLifecycleOwner(any(ProxyLifecycleProvider.class)); - verify(mockLiveDataHostApiImpl).setLifecycleOwner(any(ProxyLifecycleProvider.class)); + assertNotNull(plugin.proxyApiRegistrar); + assertTrue(plugin.proxyApiRegistrar.getLifecycleOwner() instanceof ProxyLifecycleProvider); } @Test public void onAttachedToActivity_setsActivityAsNeededAndPermissionsRegistry() { - final CameraAndroidCameraxPlugin plugin = spy(new CameraAndroidCameraxPlugin()); - final Activity mockActivity = mock(Activity.class); - final SystemServicesHostApiImpl mockSystemServicesHostApiImpl = - mock(SystemServicesHostApiImpl.class); - final DeviceOrientationManagerHostApiImpl mockDeviceOrientationManagerHostApiImpl = - mock(DeviceOrientationManagerHostApiImpl.class); - final MeteringPointHostApiImpl mockMeteringPointHostApiImpl = - mock(MeteringPointHostApiImpl.class); - final ArgumentCaptor permissionsRegistryCaptor = - ArgumentCaptor.forClass(PermissionsRegistry.class); - - doNothing().when(plugin).setUp(any(), any(), any()); - when(activityPluginBinding.getActivity()).thenReturn(mockActivity); - when(mockActivity.getApplication()).thenReturn(mock(Application.class)); + final Activity mockActivity = + mock(Activity.class, withSettings().extraInterfaces(LifecycleOwner.class)); - plugin.processCameraProviderHostApiImpl = mock(ProcessCameraProviderHostApiImpl.class); - plugin.liveDataHostApiImpl = mock(LiveDataHostApiImpl.class); - plugin.systemServicesHostApiImpl = mockSystemServicesHostApiImpl; - plugin.deviceOrientationManagerHostApiImpl = mockDeviceOrientationManagerHostApiImpl; - plugin.meteringPointHostApiImpl = mockMeteringPointHostApiImpl; + when(flutterPluginBinding.getBinaryMessenger()).thenReturn(mock(BinaryMessenger.class)); + when(flutterPluginBinding.getApplicationContext()).thenReturn(mock(Context.class)); + when(flutterPluginBinding.getTextureRegistry()).thenReturn(mock(TextureRegistry.class)); + when(activityPluginBinding.getActivity()).thenReturn(mockActivity); + final CameraAndroidCameraxPlugin plugin = new CameraAndroidCameraxPlugin(); plugin.onAttachedToEngine(flutterPluginBinding); plugin.onAttachedToActivity(activityPluginBinding); - // Check Activity references are set. - verify(mockSystemServicesHostApiImpl).setActivity(mockActivity); - verify(mockDeviceOrientationManagerHostApiImpl).setActivity(mockActivity); - verify(mockMeteringPointHostApiImpl).setActivity(mockActivity); - - // Check permissions registry reference is set. - verify(mockSystemServicesHostApiImpl) - .setPermissionsRegistry(permissionsRegistryCaptor.capture()); - assertNotNull(permissionsRegistryCaptor.getValue()); - assertTrue(permissionsRegistryCaptor.getValue() instanceof PermissionsRegistry); + assertNotNull(plugin.proxyApiRegistrar); + assertEquals(plugin.proxyApiRegistrar.getActivity(), mockActivity); + assertEquals(plugin.proxyApiRegistrar.getLifecycleOwner(), mockActivity); + assertNotNull(plugin.proxyApiRegistrar.getPermissionsRegistry()); } @Test public void onDetachedFromActivityForConfigChanges_removesReferencesToActivityPluginBindingAndActivity() { - final CameraAndroidCameraxPlugin plugin = spy(new CameraAndroidCameraxPlugin()); - final ProcessCameraProviderHostApiImpl mockProcessCameraProviderHostApiImpl = - mock(ProcessCameraProviderHostApiImpl.class); - final LiveDataHostApiImpl mockLiveDataHostApiImpl = mock(LiveDataHostApiImpl.class); - final SystemServicesHostApiImpl mockSystemServicesHostApiImpl = - mock(SystemServicesHostApiImpl.class); - final DeviceOrientationManagerHostApiImpl mockDeviceOrientationManagerHostApiImpl = - mock(DeviceOrientationManagerHostApiImpl.class); - final MeteringPointHostApiImpl mockMeteringPointHostApiImpl = - mock(MeteringPointHostApiImpl.class); - - plugin.processCameraProviderHostApiImpl = mockProcessCameraProviderHostApiImpl; - plugin.liveDataHostApiImpl = mockLiveDataHostApiImpl; - plugin.systemServicesHostApiImpl = mockSystemServicesHostApiImpl; - plugin.deviceOrientationManagerHostApiImpl = mockDeviceOrientationManagerHostApiImpl; - plugin.meteringPointHostApiImpl = mockMeteringPointHostApiImpl; + final Activity mockActivity = + mock(Activity.class, withSettings().extraInterfaces(LifecycleOwner.class)); + + when(flutterPluginBinding.getBinaryMessenger()).thenReturn(mock(BinaryMessenger.class)); + when(flutterPluginBinding.getApplicationContext()).thenReturn(mock(Context.class)); + when(flutterPluginBinding.getTextureRegistry()).thenReturn(mock(TextureRegistry.class)); + when(activityPluginBinding.getActivity()).thenReturn(mockActivity); + final CameraAndroidCameraxPlugin plugin = new CameraAndroidCameraxPlugin(); plugin.onAttachedToEngine(flutterPluginBinding); - plugin.onDetachedFromActivityForConfigChanges(); + plugin.onAttachedToActivity(activityPluginBinding); + plugin.onDetachedFromActivity(); - verify(mockProcessCameraProviderHostApiImpl).setLifecycleOwner(null); - verify(mockLiveDataHostApiImpl).setLifecycleOwner(null); - verify(mockSystemServicesHostApiImpl).setActivity(null); - verify(mockDeviceOrientationManagerHostApiImpl).setActivity(null); - verify(mockMeteringPointHostApiImpl).setActivity(null); + assertNotNull(plugin.proxyApiRegistrar); + assertNull(plugin.proxyApiRegistrar.getActivity()); + assertNull(plugin.proxyApiRegistrar.getLifecycleOwner()); } @Test public void onDetachedFromActivityForConfigChanges_setsContextReferencesBasedOnFlutterPluginBinding() { - final CameraAndroidCameraxPlugin plugin = spy(new CameraAndroidCameraxPlugin()); final Context mockContext = mock(Context.class); - final ProcessCameraProviderHostApiImpl mockProcessCameraProviderHostApiImpl = - mock(ProcessCameraProviderHostApiImpl.class); - final RecorderHostApiImpl mockRecorderHostApiImpl = mock(RecorderHostApiImpl.class); - final PendingRecordingHostApiImpl mockPendingRecordingHostApiImpl = - mock(PendingRecordingHostApiImpl.class); - final SystemServicesHostApiImpl mockSystemServicesHostApiImpl = - mock(SystemServicesHostApiImpl.class); - final ImageCaptureHostApiImpl mockImageCaptureHostApiImpl = mock(ImageCaptureHostApiImpl.class); - final ImageAnalysisHostApiImpl mockImageAnalysisHostApiImpl = - mock(ImageAnalysisHostApiImpl.class); - final CameraControlHostApiImpl mockCameraControlHostApiImpl = - mock(CameraControlHostApiImpl.class); - final Camera2CameraControlHostApiImpl mockCamera2CameraControlHostApiImpl = - mock(Camera2CameraControlHostApiImpl.class); + final Activity mockActivity = + mock(Activity.class, withSettings().extraInterfaces(LifecycleOwner.class)); + when(flutterPluginBinding.getBinaryMessenger()).thenReturn(mock(BinaryMessenger.class)); when(flutterPluginBinding.getApplicationContext()).thenReturn(mockContext); + when(flutterPluginBinding.getTextureRegistry()).thenReturn(mock(TextureRegistry.class)); + when(activityPluginBinding.getActivity()).thenReturn(mockActivity); - plugin.processCameraProviderHostApiImpl = mockProcessCameraProviderHostApiImpl; - plugin.recorderHostApiImpl = mockRecorderHostApiImpl; - plugin.pendingRecordingHostApiImpl = mockPendingRecordingHostApiImpl; - plugin.systemServicesHostApiImpl = mockSystemServicesHostApiImpl; - plugin.imageCaptureHostApiImpl = mockImageCaptureHostApiImpl; - plugin.imageAnalysisHostApiImpl = mockImageAnalysisHostApiImpl; - plugin.cameraControlHostApiImpl = mockCameraControlHostApiImpl; - plugin.liveDataHostApiImpl = mock(LiveDataHostApiImpl.class); - plugin.camera2CameraControlHostApiImpl = mockCamera2CameraControlHostApiImpl; - + final CameraAndroidCameraxPlugin plugin = new CameraAndroidCameraxPlugin(); plugin.onAttachedToEngine(flutterPluginBinding); + plugin.onAttachedToActivity(activityPluginBinding); plugin.onDetachedFromActivityForConfigChanges(); - verify(mockProcessCameraProviderHostApiImpl).setContext(mockContext); - verify(mockRecorderHostApiImpl).setContext(mockContext); - verify(mockPendingRecordingHostApiImpl).setContext(mockContext); - verify(mockSystemServicesHostApiImpl).setContext(mockContext); - verify(mockImageCaptureHostApiImpl).setContext(mockContext); - verify(mockImageAnalysisHostApiImpl).setContext(mockContext); - verify(mockCameraControlHostApiImpl).setContext(mockContext); - verify(mockCamera2CameraControlHostApiImpl).setContext(mockContext); + assertNotNull(plugin.proxyApiRegistrar); + assertEquals(plugin.proxyApiRegistrar.getContext(), mockContext); + assertNull(plugin.proxyApiRegistrar.getActivity()); + assertNull(plugin.proxyApiRegistrar.getLifecycleOwner()); } @Test public void onReattachedToActivityForConfigChanges_setsLifecycleOwnerAsActivityIfLifecycleOwnerAsNeeded() { - final CameraAndroidCameraxPlugin plugin = spy(new CameraAndroidCameraxPlugin()); final Activity mockActivity = mock(Activity.class, withSettings().extraInterfaces(LifecycleOwner.class)); - final ProcessCameraProviderHostApiImpl mockProcessCameraProviderHostApiImpl = - mock(ProcessCameraProviderHostApiImpl.class); - final LiveDataHostApiImpl mockLiveDataHostApiImpl = mock(LiveDataHostApiImpl.class); + when(flutterPluginBinding.getBinaryMessenger()).thenReturn(mock(BinaryMessenger.class)); + when(flutterPluginBinding.getApplicationContext()).thenReturn(mock(Context.class)); + when(flutterPluginBinding.getTextureRegistry()).thenReturn(mock(TextureRegistry.class)); when(activityPluginBinding.getActivity()).thenReturn(mockActivity); - plugin.processCameraProviderHostApiImpl = mockProcessCameraProviderHostApiImpl; - plugin.liveDataHostApiImpl = mockLiveDataHostApiImpl; - plugin.systemServicesHostApiImpl = mock(SystemServicesHostApiImpl.class); - plugin.deviceOrientationManagerHostApiImpl = mock(DeviceOrientationManagerHostApiImpl.class); - - plugin.onReattachedToActivityForConfigChanges(activityPluginBinding); + final CameraAndroidCameraxPlugin plugin = new CameraAndroidCameraxPlugin(); + plugin.onAttachedToEngine(flutterPluginBinding); + plugin.onAttachedToActivity(activityPluginBinding); - verify(mockProcessCameraProviderHostApiImpl).setLifecycleOwner(any(LifecycleOwner.class)); - verify(mockLiveDataHostApiImpl).setLifecycleOwner(any(LifecycleOwner.class)); + assertNotNull(plugin.proxyApiRegistrar); + assertEquals(plugin.proxyApiRegistrar.getActivity(), mockActivity); + assertEquals(plugin.proxyApiRegistrar.getLifecycleOwner(), mockActivity); } @Test public void onReattachedToActivityForConfigChanges_setsLifecycleOwnerAsProxyLifecycleProviderIfActivityNotLifecycleOwnerAsNeeded() { - final CameraAndroidCameraxPlugin plugin = spy(new CameraAndroidCameraxPlugin()); final Activity mockActivity = mock(Activity.class); - final ProcessCameraProviderHostApiImpl mockProcessCameraProviderHostApiImpl = - mock(ProcessCameraProviderHostApiImpl.class); - final LiveDataHostApiImpl mockLiveDataHostApiImpl = mock(LiveDataHostApiImpl.class); - - when(activityPluginBinding.getActivity()).thenReturn(mockActivity); when(mockActivity.getApplication()).thenReturn(mock(Application.class)); - plugin.processCameraProviderHostApiImpl = mockProcessCameraProviderHostApiImpl; - plugin.liveDataHostApiImpl = mockLiveDataHostApiImpl; - plugin.systemServicesHostApiImpl = mock(SystemServicesHostApiImpl.class); - plugin.deviceOrientationManagerHostApiImpl = mock(DeviceOrientationManagerHostApiImpl.class); + when(flutterPluginBinding.getBinaryMessenger()).thenReturn(mock(BinaryMessenger.class)); + when(flutterPluginBinding.getApplicationContext()).thenReturn(mock(Context.class)); + when(flutterPluginBinding.getTextureRegistry()).thenReturn(mock(TextureRegistry.class)); + when(activityPluginBinding.getActivity()).thenReturn(mockActivity); + final CameraAndroidCameraxPlugin plugin = new CameraAndroidCameraxPlugin(); plugin.onAttachedToEngine(flutterPluginBinding); plugin.onReattachedToActivityForConfigChanges(activityPluginBinding); - verify(mockProcessCameraProviderHostApiImpl) - .setLifecycleOwner(any(ProxyLifecycleProvider.class)); - verify(mockLiveDataHostApiImpl).setLifecycleOwner(any(ProxyLifecycleProvider.class)); + assertNotNull(plugin.proxyApiRegistrar); + assertTrue(plugin.proxyApiRegistrar.getLifecycleOwner() instanceof ProxyLifecycleProvider); } @Test public void onReattachedToActivityForConfigChanges_setsActivityAndPermissionsRegistryAsNeeded() { - final CameraAndroidCameraxPlugin plugin = spy(new CameraAndroidCameraxPlugin()); - final Activity mockActivity = mock(Activity.class); - final ProcessCameraProviderHostApiImpl mockProcessCameraProviderHostApiImpl = - mock(ProcessCameraProviderHostApiImpl.class); - final RecorderHostApiImpl mockRecorderHostApiImpl = mock(RecorderHostApiImpl.class); - final PendingRecordingHostApiImpl mockPendingRecordingHostApiImpl = - mock(PendingRecordingHostApiImpl.class); - final SystemServicesHostApiImpl mockSystemServicesHostApiImpl = - mock(SystemServicesHostApiImpl.class); - final ImageAnalysisHostApiImpl mockImageAnalysisHostApiImpl = - mock(ImageAnalysisHostApiImpl.class); - final ImageCaptureHostApiImpl mockImageCaptureHostApiImpl = mock(ImageCaptureHostApiImpl.class); - final CameraControlHostApiImpl mockCameraControlHostApiImpl = - mock(CameraControlHostApiImpl.class); - final DeviceOrientationManagerHostApiImpl mockDeviceOrientationManagerHostApiImpl = - mock(DeviceOrientationManagerHostApiImpl.class); - final Camera2CameraControlHostApiImpl mockCamera2CameraControlHostApiImpl = - mock(Camera2CameraControlHostApiImpl.class); - final MeteringPointHostApiImpl mockMeteringPointHostApiImpl = - mock(MeteringPointHostApiImpl.class); - final ArgumentCaptor permissionsRegistryCaptor = - ArgumentCaptor.forClass(PermissionsRegistry.class); + final Activity mockActivity = + mock(Activity.class, withSettings().extraInterfaces(LifecycleOwner.class)); + when(flutterPluginBinding.getBinaryMessenger()).thenReturn(mock(BinaryMessenger.class)); + when(flutterPluginBinding.getApplicationContext()).thenReturn(mock(Context.class)); + when(flutterPluginBinding.getTextureRegistry()).thenReturn(mock(TextureRegistry.class)); when(activityPluginBinding.getActivity()).thenReturn(mockActivity); - when(mockActivity.getApplication()).thenReturn(mock(Application.class)); - - plugin.processCameraProviderHostApiImpl = mockProcessCameraProviderHostApiImpl; - plugin.recorderHostApiImpl = mockRecorderHostApiImpl; - plugin.pendingRecordingHostApiImpl = mockPendingRecordingHostApiImpl; - plugin.systemServicesHostApiImpl = mockSystemServicesHostApiImpl; - plugin.imageCaptureHostApiImpl = mockImageCaptureHostApiImpl; - plugin.imageAnalysisHostApiImpl = mockImageAnalysisHostApiImpl; - plugin.cameraControlHostApiImpl = mockCameraControlHostApiImpl; - plugin.deviceOrientationManagerHostApiImpl = mockDeviceOrientationManagerHostApiImpl; - plugin.meteringPointHostApiImpl = mockMeteringPointHostApiImpl; - plugin.liveDataHostApiImpl = mock(LiveDataHostApiImpl.class); - plugin.camera2CameraControlHostApiImpl = mockCamera2CameraControlHostApiImpl; + final CameraAndroidCameraxPlugin plugin = new CameraAndroidCameraxPlugin(); plugin.onAttachedToEngine(flutterPluginBinding); plugin.onReattachedToActivityForConfigChanges(activityPluginBinding); - // Check Activity references are set. - verify(mockSystemServicesHostApiImpl).setActivity(mockActivity); - verify(mockDeviceOrientationManagerHostApiImpl).setActivity(mockActivity); - verify(mockMeteringPointHostApiImpl).setActivity(mockActivity); - - // Check Activity as Context references are set. - verify(mockProcessCameraProviderHostApiImpl).setContext(mockActivity); - verify(mockRecorderHostApiImpl).setContext(mockActivity); - verify(mockPendingRecordingHostApiImpl).setContext(mockActivity); - verify(mockSystemServicesHostApiImpl).setContext(mockActivity); - verify(mockImageCaptureHostApiImpl).setContext(mockActivity); - verify(mockImageAnalysisHostApiImpl).setContext(mockActivity); - verify(mockCameraControlHostApiImpl).setContext(mockActivity); - verify(mockCamera2CameraControlHostApiImpl).setContext(mockActivity); - - // Check permissions registry reference is set. - verify(mockSystemServicesHostApiImpl) - .setPermissionsRegistry(permissionsRegistryCaptor.capture()); - assertNotNull(permissionsRegistryCaptor.getValue()); - assertTrue(permissionsRegistryCaptor.getValue() instanceof PermissionsRegistry); - } - - @Test - public void onDetachedFromActivity_removesReferencesToActivityPluginBindingAndActivity() { - final CameraAndroidCameraxPlugin plugin = spy(new CameraAndroidCameraxPlugin()); - final ProcessCameraProviderHostApiImpl mockProcessCameraProviderHostApiImpl = - mock(ProcessCameraProviderHostApiImpl.class); - final SystemServicesHostApiImpl mockSystemServicesHostApiImpl = - mock(SystemServicesHostApiImpl.class); - final LiveDataHostApiImpl mockLiveDataHostApiImpl = mock(LiveDataHostApiImpl.class); - final DeviceOrientationManagerHostApiImpl mockDeviceOrientationManagerHostApiImpl = - mock(DeviceOrientationManagerHostApiImpl.class); - final MeteringPointHostApiImpl mockMeteringPointHostApiImpl = - mock(MeteringPointHostApiImpl.class); - - plugin.processCameraProviderHostApiImpl = mockProcessCameraProviderHostApiImpl; - plugin.liveDataHostApiImpl = mockLiveDataHostApiImpl; - plugin.systemServicesHostApiImpl = mockSystemServicesHostApiImpl; - plugin.deviceOrientationManagerHostApiImpl = mockDeviceOrientationManagerHostApiImpl; - plugin.meteringPointHostApiImpl = mockMeteringPointHostApiImpl; - - plugin.onAttachedToEngine(flutterPluginBinding); - plugin.onDetachedFromActivityForConfigChanges(); - - verify(mockProcessCameraProviderHostApiImpl).setLifecycleOwner(null); - verify(mockLiveDataHostApiImpl).setLifecycleOwner(null); - verify(mockSystemServicesHostApiImpl).setActivity(null); - verify(mockDeviceOrientationManagerHostApiImpl).setActivity(null); - verify(mockMeteringPointHostApiImpl).setActivity(null); + assertNotNull(plugin.proxyApiRegistrar); + assertEquals(plugin.proxyApiRegistrar.getActivity(), mockActivity); + assertEquals(plugin.proxyApiRegistrar.getLifecycleOwner(), mockActivity); + assertNotNull(plugin.proxyApiRegistrar.getPermissionsRegistry()); } @Test public void onDetachedFromActivity_setsContextReferencesBasedOnFlutterPluginBinding() { - final CameraAndroidCameraxPlugin plugin = spy(new CameraAndroidCameraxPlugin()); final Context mockContext = mock(Context.class); - final ProcessCameraProviderHostApiImpl mockProcessCameraProviderHostApiImpl = - mock(ProcessCameraProviderHostApiImpl.class); - final RecorderHostApiImpl mockRecorderHostApiImpl = mock(RecorderHostApiImpl.class); - final PendingRecordingHostApiImpl mockPendingRecordingHostApiImpl = - mock(PendingRecordingHostApiImpl.class); - final SystemServicesHostApiImpl mockSystemServicesHostApiImpl = - mock(SystemServicesHostApiImpl.class); - final ImageAnalysisHostApiImpl mockImageAnalysisHostApiImpl = - mock(ImageAnalysisHostApiImpl.class); - final ImageCaptureHostApiImpl mockImageCaptureHostApiImpl = mock(ImageCaptureHostApiImpl.class); - final CameraControlHostApiImpl mockCameraControlHostApiImpl = - mock(CameraControlHostApiImpl.class); - final Camera2CameraControlHostApiImpl mockCamera2CameraControlHostApiImpl = - mock(Camera2CameraControlHostApiImpl.class); - final ArgumentCaptor permissionsRegistryCaptor = - ArgumentCaptor.forClass(PermissionsRegistry.class); + final Activity mockActivity = + mock(Activity.class, withSettings().extraInterfaces(LifecycleOwner.class)); + when(flutterPluginBinding.getBinaryMessenger()).thenReturn(mock(BinaryMessenger.class)); when(flutterPluginBinding.getApplicationContext()).thenReturn(mockContext); + when(flutterPluginBinding.getTextureRegistry()).thenReturn(mock(TextureRegistry.class)); + when(activityPluginBinding.getActivity()).thenReturn(mockActivity); - plugin.processCameraProviderHostApiImpl = mockProcessCameraProviderHostApiImpl; - plugin.recorderHostApiImpl = mockRecorderHostApiImpl; - plugin.pendingRecordingHostApiImpl = mockPendingRecordingHostApiImpl; - plugin.systemServicesHostApiImpl = mockSystemServicesHostApiImpl; - plugin.imageCaptureHostApiImpl = mockImageCaptureHostApiImpl; - plugin.imageAnalysisHostApiImpl = mockImageAnalysisHostApiImpl; - plugin.cameraControlHostApiImpl = mockCameraControlHostApiImpl; - plugin.liveDataHostApiImpl = mock(LiveDataHostApiImpl.class); - plugin.camera2CameraControlHostApiImpl = mockCamera2CameraControlHostApiImpl; - + final CameraAndroidCameraxPlugin plugin = new CameraAndroidCameraxPlugin(); plugin.onAttachedToEngine(flutterPluginBinding); + plugin.onAttachedToActivity(activityPluginBinding); plugin.onDetachedFromActivity(); - verify(mockProcessCameraProviderHostApiImpl).setContext(mockContext); - verify(mockRecorderHostApiImpl).setContext(mockContext); - verify(mockPendingRecordingHostApiImpl).setContext(mockContext); - verify(mockSystemServicesHostApiImpl).setContext(mockContext); - verify(mockImageCaptureHostApiImpl).setContext(mockContext); - verify(mockImageAnalysisHostApiImpl).setContext(mockContext); - verify(mockCameraControlHostApiImpl).setContext(mockContext); - verify(mockCamera2CameraControlHostApiImpl).setContext(mockContext); + assertNotNull(plugin.proxyApiRegistrar); + assertEquals(plugin.proxyApiRegistrar.getContext(), mockContext); + assertNull(plugin.proxyApiRegistrar.getActivity()); + assertNull(plugin.proxyApiRegistrar.getLifecycleOwner()); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraControlTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraControlTest.java index a0fe8f977ee0..0b7d8f99a524 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraControlTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraControlTest.java @@ -4,394 +4,213 @@ package io.flutter.plugins.camerax; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import android.content.Context; import androidx.camera.core.CameraControl; import androidx.camera.core.FocusMeteringAction; import androidx.camera.core.FocusMeteringResult; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; -import io.flutter.plugin.common.BinaryMessenger; -import java.util.Objects; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; -import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; public class CameraControlTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public BinaryMessenger mockBinaryMessenger; - @Mock public CameraControl cameraControl; - - InstanceManager testInstanceManager; - - @Before - public void setUp() { - testInstanceManager = InstanceManager.create(identifier -> {}); - } - - @After - public void tearDown() { - testInstanceManager.stopFinalizationListener(); - } - + @SuppressWarnings("unchecked") @Test public void enableTorch_turnsTorchModeOnAndOffAsExpected() { - try (MockedStatic mockedFutures = Mockito.mockStatic(Futures.class)) { - final CameraControlHostApiImpl cameraControlHostApiImpl = - new CameraControlHostApiImpl( - mockBinaryMessenger, testInstanceManager, mock(Context.class)); - final Long cameraControlIdentifier = 88L; - final boolean enableTorch = true; + final PigeonApiCameraControl api = new TestProxyApiRegistrar().getPigeonApiCameraControl(); - @SuppressWarnings("unchecked") - final ListenableFuture enableTorchFuture = mock(ListenableFuture.class); + final CameraControl instance = mock(CameraControl.class); - testInstanceManager.addDartCreatedInstance(cameraControl, cameraControlIdentifier); + final ListenableFuture mockListenableFuture = mock(ListenableFuture.class); + final boolean enable = true; + when(instance.enableTorch(enable)).thenReturn(mockListenableFuture); - when(cameraControl.enableTorch(true)).thenReturn(enableTorchFuture); - - @SuppressWarnings("unchecked") + try (MockedStatic mockedFutures = Mockito.mockStatic(Futures.class)) { final ArgumentCaptor> futureCallbackCaptor = ArgumentCaptor.forClass(FutureCallback.class); - // Test successful behavior. - @SuppressWarnings("unchecked") - final GeneratedCameraXLibrary.Result successfulMockResult = - mock(GeneratedCameraXLibrary.Result.class); - cameraControlHostApiImpl.enableTorch( - cameraControlIdentifier, enableTorch, successfulMockResult); + final boolean[] isSuccess = {false}; + api.enableTorch( + instance, + enable, + ResultCompat.asCompatCallback( + reply -> { + isSuccess[0] = reply.isSuccess(); + return null; + })); + + verify(instance).enableTorch(enable); mockedFutures.verify( - () -> Futures.addCallback(eq(enableTorchFuture), futureCallbackCaptor.capture(), any())); + () -> + Futures.addCallback(eq(mockListenableFuture), futureCallbackCaptor.capture(), any())); mockedFutures.clearInvocations(); - FutureCallback successfulEnableTorchCallback = futureCallbackCaptor.getValue(); - - successfulEnableTorchCallback.onSuccess(mock(Void.class)); - verify(successfulMockResult).success(null); - - // Test failed behavior. - @SuppressWarnings("unchecked") - final GeneratedCameraXLibrary.Result failedMockResult = - mock(GeneratedCameraXLibrary.Result.class); - final Throwable testThrowable = new Throwable(); - cameraControlHostApiImpl.enableTorch(cameraControlIdentifier, enableTorch, failedMockResult); - mockedFutures.verify( - () -> Futures.addCallback(eq(enableTorchFuture), futureCallbackCaptor.capture(), any())); - - FutureCallback failedEnableTorchCallback = futureCallbackCaptor.getValue(); + final FutureCallback successfulCallback = futureCallbackCaptor.getValue(); - failedEnableTorchCallback.onFailure(testThrowable); - verify(failedMockResult).error(testThrowable); + successfulCallback.onSuccess(mock(Void.class)); + assertTrue(isSuccess[0]); } } + @SuppressWarnings("unchecked") @Test public void setZoomRatio_setsZoomAsExpected() { - try (MockedStatic mockedFutures = Mockito.mockStatic(Futures.class)) { - final CameraControlHostApiImpl cameraControlHostApiImpl = - new CameraControlHostApiImpl( - mockBinaryMessenger, testInstanceManager, mock(Context.class)); - final Long cameraControlIdentifier = 33L; - final Double zoomRatio = 0.2D; + final PigeonApiCameraControl api = new TestProxyApiRegistrar().getPigeonApiCameraControl(); - @SuppressWarnings("unchecked") - final ListenableFuture setZoomRatioFuture = mock(ListenableFuture.class); + final CameraControl instance = mock(CameraControl.class); - testInstanceManager.addDartCreatedInstance(cameraControl, cameraControlIdentifier); + final ListenableFuture mockListenableFuture = mock(ListenableFuture.class); + final float ratio = 1.0f; + when(instance.setZoomRatio(ratio)).thenReturn(mockListenableFuture); - when(cameraControl.setZoomRatio(zoomRatio.floatValue())).thenReturn(setZoomRatioFuture); - - @SuppressWarnings("unchecked") + try (MockedStatic mockedFutures = Mockito.mockStatic(Futures.class)) { final ArgumentCaptor> futureCallbackCaptor = ArgumentCaptor.forClass(FutureCallback.class); - // Test successful behavior. - @SuppressWarnings("unchecked") - final GeneratedCameraXLibrary.Result successfulMockResult = - mock(GeneratedCameraXLibrary.Result.class); - cameraControlHostApiImpl.setZoomRatio( - cameraControlIdentifier, zoomRatio, successfulMockResult); + final boolean[] isSuccess = {false}; + api.setZoomRatio( + instance, + ratio, + ResultCompat.asCompatCallback( + reply -> { + isSuccess[0] = reply.isSuccess(); + return null; + })); + + verify(instance).setZoomRatio(ratio); mockedFutures.verify( - () -> Futures.addCallback(eq(setZoomRatioFuture), futureCallbackCaptor.capture(), any())); - mockedFutures.clearInvocations(); - - FutureCallback successfulSetZoomRatioCallback = futureCallbackCaptor.getValue(); - - successfulSetZoomRatioCallback.onSuccess(mock(Void.class)); - verify(successfulMockResult).success(null); - - // Test failed behavior. - @SuppressWarnings("unchecked") - final GeneratedCameraXLibrary.Result failedMockResult = - mock(GeneratedCameraXLibrary.Result.class); - final Throwable testThrowable = new Throwable(); - cameraControlHostApiImpl.setZoomRatio(cameraControlIdentifier, zoomRatio, failedMockResult); - mockedFutures.verify( - () -> Futures.addCallback(eq(setZoomRatioFuture), futureCallbackCaptor.capture(), any())); - mockedFutures.clearInvocations(); - - FutureCallback failedSetZoomRatioCallback = futureCallbackCaptor.getValue(); - - failedSetZoomRatioCallback.onFailure(testThrowable); - verify(failedMockResult).error(testThrowable); - - // Test response to canceled operation. - @SuppressWarnings("unchecked") - final GeneratedCameraXLibrary.Result canceledOpResult = - mock(GeneratedCameraXLibrary.Result.class); - final CameraControl.OperationCanceledException canceledOpThrowable = - mock(CameraControl.OperationCanceledException.class); - cameraControlHostApiImpl.setZoomRatio(cameraControlIdentifier, zoomRatio, canceledOpResult); - mockedFutures.verify( - () -> Futures.addCallback(eq(setZoomRatioFuture), futureCallbackCaptor.capture(), any())); + () -> + Futures.addCallback(eq(mockListenableFuture), futureCallbackCaptor.capture(), any())); mockedFutures.clearInvocations(); - FutureCallback canceledOpCallback = futureCallbackCaptor.getValue(); + final FutureCallback successfulCallback = futureCallbackCaptor.getValue(); - canceledOpCallback.onFailure(canceledOpThrowable); - verify(canceledOpResult).success(null); + successfulCallback.onSuccess(mock(Void.class)); + assertTrue(isSuccess[0]); } } + @SuppressWarnings("unchecked") @Test public void startFocusAndMetering_startsFocusAndMeteringAsExpected() { - try (MockedStatic mockedFutures = Mockito.mockStatic(Futures.class)) { - final CameraControlHostApiImpl cameraControlHostApiImpl = - new CameraControlHostApiImpl( - mockBinaryMessenger, testInstanceManager, mock(Context.class)); - final Long cameraControlIdentifier = 90L; - final FocusMeteringAction mockAction = mock(FocusMeteringAction.class); - final Long mockActionId = 44L; - final FocusMeteringResult mockResult = mock(FocusMeteringResult.class); - final Long mockResultId = 33L; - - @SuppressWarnings("unchecked") - final ListenableFuture startFocusAndMeteringFuture = - mock(ListenableFuture.class); - - testInstanceManager.addDartCreatedInstance(cameraControl, cameraControlIdentifier); - testInstanceManager.addDartCreatedInstance(mockResult, mockResultId); - testInstanceManager.addDartCreatedInstance(mockAction, mockActionId); - - when(cameraControl.startFocusAndMetering(mockAction)).thenReturn(startFocusAndMeteringFuture); - - @SuppressWarnings("unchecked") - final ArgumentCaptor> futureCallbackCaptor = - ArgumentCaptor.forClass(FutureCallback.class); - - // Test successful behavior. - @SuppressWarnings("unchecked") - final GeneratedCameraXLibrary.Result successfulMockResult = - mock(GeneratedCameraXLibrary.Result.class); - cameraControlHostApiImpl.startFocusAndMetering( - cameraControlIdentifier, mockActionId, successfulMockResult); - mockedFutures.verify( - () -> - Futures.addCallback( - eq(startFocusAndMeteringFuture), futureCallbackCaptor.capture(), any())); - mockedFutures.clearInvocations(); - - FutureCallback successfulCallback = futureCallbackCaptor.getValue(); - - successfulCallback.onSuccess(mockResult); - verify(successfulMockResult).success(mockResultId); + final PigeonApiCameraControl api = new TestProxyApiRegistrar().getPigeonApiCameraControl(); - // Test failed behavior. - @SuppressWarnings("unchecked") - final GeneratedCameraXLibrary.Result failedMockResult = - mock(GeneratedCameraXLibrary.Result.class); - final Throwable testThrowable = new Throwable(); - cameraControlHostApiImpl.startFocusAndMetering( - cameraControlIdentifier, mockActionId, failedMockResult); - mockedFutures.verify( - () -> - Futures.addCallback( - eq(startFocusAndMeteringFuture), futureCallbackCaptor.capture(), any())); - mockedFutures.clearInvocations(); + final CameraControl instance = mock(CameraControl.class); - FutureCallback failedCallback = futureCallbackCaptor.getValue(); + final ListenableFuture mockListenableFuture = mock(ListenableFuture.class); + final androidx.camera.core.FocusMeteringAction action = mock(FocusMeteringAction.class); + when(instance.startFocusAndMetering(action)).thenReturn(mockListenableFuture); - failedCallback.onFailure(testThrowable); - verify(failedMockResult).error(testThrowable); + try (MockedStatic mockedFutures = Mockito.mockStatic(Futures.class)) { + final ArgumentCaptor> futureCallbackCaptor = + ArgumentCaptor.forClass(FutureCallback.class); - // Test response to canceled operation. - @SuppressWarnings("unchecked") - final GeneratedCameraXLibrary.Result canceledOpResult = - mock(GeneratedCameraXLibrary.Result.class); - final CameraControl.OperationCanceledException canceledOpThrowable = - mock(CameraControl.OperationCanceledException.class); - cameraControlHostApiImpl.startFocusAndMetering( - cameraControlIdentifier, mockActionId, canceledOpResult); + final FocusMeteringResult[] resultArray = {null}; + api.startFocusAndMetering( + instance, + action, + ResultCompat.asCompatCallback( + reply -> { + resultArray[0] = reply.getOrNull(); + return null; + })); + + verify(instance).startFocusAndMetering(action); mockedFutures.verify( () -> - Futures.addCallback( - eq(startFocusAndMeteringFuture), futureCallbackCaptor.capture(), any())); + Futures.addCallback(eq(mockListenableFuture), futureCallbackCaptor.capture(), any())); mockedFutures.clearInvocations(); - FutureCallback canceledOpCallback = futureCallbackCaptor.getValue(); + final FutureCallback successfulCallback = + futureCallbackCaptor.getValue(); - canceledOpCallback.onFailure(canceledOpThrowable); - verify(canceledOpResult).success(null); + final FocusMeteringResult result = mock(FocusMeteringResult.class); + successfulCallback.onSuccess(result); + assertEquals(resultArray[0], result); } } + @SuppressWarnings("unchecked") @Test public void cancelFocusAndMetering_cancelsFocusAndMeteringAsExpected() { - try (MockedStatic mockedFutures = Mockito.mockStatic(Futures.class)) { - final CameraControlHostApiImpl cameraControlHostApiImpl = - new CameraControlHostApiImpl( - mockBinaryMessenger, testInstanceManager, mock(Context.class)); - final Long cameraControlIdentifier = 8L; + final PigeonApiCameraControl api = new TestProxyApiRegistrar().getPigeonApiCameraControl(); - @SuppressWarnings("unchecked") - final ListenableFuture cancelFocusAndMeteringFuture = mock(ListenableFuture.class); + final CameraControl instance = mock(CameraControl.class); - testInstanceManager.addDartCreatedInstance(cameraControl, cameraControlIdentifier); + final ListenableFuture mockListenableFuture = mock(ListenableFuture.class); + when(instance.cancelFocusAndMetering()).thenReturn(mockListenableFuture); - when(cameraControl.cancelFocusAndMetering()).thenReturn(cancelFocusAndMeteringFuture); - - @SuppressWarnings("unchecked") + try (MockedStatic mockedFutures = Mockito.mockStatic(Futures.class)) { final ArgumentCaptor> futureCallbackCaptor = ArgumentCaptor.forClass(FutureCallback.class); - // Test successful behavior. - @SuppressWarnings("unchecked") - final GeneratedCameraXLibrary.Result successfulMockResult = - mock(GeneratedCameraXLibrary.Result.class); - cameraControlHostApiImpl.cancelFocusAndMetering( - cameraControlIdentifier, successfulMockResult); + final boolean[] isSuccess = {false}; + api.cancelFocusAndMetering( + instance, + ResultCompat.asCompatCallback( + reply -> { + isSuccess[0] = reply.isSuccess(); + return null; + })); + + verify(instance).cancelFocusAndMetering(); mockedFutures.verify( () -> - Futures.addCallback( - eq(cancelFocusAndMeteringFuture), futureCallbackCaptor.capture(), any())); + Futures.addCallback(eq(mockListenableFuture), futureCallbackCaptor.capture(), any())); mockedFutures.clearInvocations(); - FutureCallback successfulCallback = futureCallbackCaptor.getValue(); + final FutureCallback successfulCallback = futureCallbackCaptor.getValue(); successfulCallback.onSuccess(mock(Void.class)); - verify(successfulMockResult).success(null); - - // Test failed behavior. - @SuppressWarnings("unchecked") - final GeneratedCameraXLibrary.Result failedMockResult = - mock(GeneratedCameraXLibrary.Result.class); - final Throwable testThrowable = new Throwable(); - cameraControlHostApiImpl.cancelFocusAndMetering(cameraControlIdentifier, failedMockResult); - mockedFutures.verify( - () -> - Futures.addCallback( - eq(cancelFocusAndMeteringFuture), futureCallbackCaptor.capture(), any())); - - FutureCallback failedCallback = futureCallbackCaptor.getValue(); - - failedCallback.onFailure(testThrowable); - verify(failedMockResult).error(testThrowable); + assertTrue(isSuccess[0]); } } + @SuppressWarnings("unchecked") @Test public void setExposureCompensationIndex_setsExposureCompensationIndexAsExpected() { - try (MockedStatic mockedFutures = Mockito.mockStatic(Futures.class)) { - final CameraControlHostApiImpl cameraControlHostApiImpl = - new CameraControlHostApiImpl( - mockBinaryMessenger, testInstanceManager, mock(Context.class)); - final Long cameraControlIdentifier = 53L; - final Long index = 2L; - - @SuppressWarnings("unchecked") - final ListenableFuture setExposureCompensationIndexFuture = - mock(ListenableFuture.class); + final PigeonApiCameraControl api = new TestProxyApiRegistrar().getPigeonApiCameraControl(); - testInstanceManager.addDartCreatedInstance(cameraControl, cameraControlIdentifier); + final CameraControl instance = mock(CameraControl.class); - when(cameraControl.setExposureCompensationIndex(index.intValue())) - .thenReturn(setExposureCompensationIndexFuture); + final ListenableFuture mockListenableFuture = mock(ListenableFuture.class); + final int index = 1; + when(instance.setExposureCompensationIndex(index)).thenReturn(mockListenableFuture); - @SuppressWarnings("unchecked") + try (MockedStatic mockedFutures = Mockito.mockStatic(Futures.class)) { final ArgumentCaptor> futureCallbackCaptor = ArgumentCaptor.forClass(FutureCallback.class); - // Test successful behavior. - @SuppressWarnings("unchecked") - final GeneratedCameraXLibrary.Result successfulMockResult = - mock(GeneratedCameraXLibrary.Result.class); - cameraControlHostApiImpl.setExposureCompensationIndex( - cameraControlIdentifier, index, successfulMockResult); - mockedFutures.verify( - () -> - Futures.addCallback( - eq(setExposureCompensationIndexFuture), futureCallbackCaptor.capture(), any())); - mockedFutures.clearInvocations(); - - FutureCallback successfulCallback = futureCallbackCaptor.getValue(); - final Integer fakeResult = 4; - - successfulCallback.onSuccess(fakeResult); - verify(successfulMockResult).success(fakeResult.longValue()); - - // Test failed behavior. - @SuppressWarnings("unchecked") - final GeneratedCameraXLibrary.Result failedMockResult = - mock(GeneratedCameraXLibrary.Result.class); - final Throwable testThrowable = new Throwable(); - cameraControlHostApiImpl.setExposureCompensationIndex( - cameraControlIdentifier, index, failedMockResult); - mockedFutures.verify( - () -> - Futures.addCallback( - eq(setExposureCompensationIndexFuture), futureCallbackCaptor.capture(), any())); - mockedFutures.clearInvocations(); - - FutureCallback failedCallback = futureCallbackCaptor.getValue(); - - failedCallback.onFailure(testThrowable); - verify(failedMockResult).error(testThrowable); - - // Test response to canceled operation. - @SuppressWarnings("unchecked") - final GeneratedCameraXLibrary.Result canceledOpResult = - mock(GeneratedCameraXLibrary.Result.class); - final CameraControl.OperationCanceledException canceledOpThrowable = - mock(CameraControl.OperationCanceledException.class); - cameraControlHostApiImpl.setExposureCompensationIndex( - cameraControlIdentifier, index, canceledOpResult); + final Long[] resultArray = {-1L}; + api.setExposureCompensationIndex( + instance, + index, + ResultCompat.asCompatCallback( + reply -> { + resultArray[0] = reply.getOrNull(); + return null; + })); + + verify(instance).setExposureCompensationIndex(index); mockedFutures.verify( () -> - Futures.addCallback( - eq(setExposureCompensationIndexFuture), futureCallbackCaptor.capture(), any())); + Futures.addCallback(eq(mockListenableFuture), futureCallbackCaptor.capture(), any())); mockedFutures.clearInvocations(); - FutureCallback canceledOpCallback = futureCallbackCaptor.getValue(); + final FutureCallback successfulCallback = futureCallbackCaptor.getValue(); - canceledOpCallback.onFailure(canceledOpThrowable); - verify(canceledOpResult).success(null); + successfulCallback.onSuccess(index); + assertEquals(resultArray[0], Long.valueOf(index)); } } - - @Test - public void flutterApiCreate_makesCallToCreateInstanceOnDartSide() { - final CameraControlFlutterApiImpl spyFlutterApi = - spy(new CameraControlFlutterApiImpl(mockBinaryMessenger, testInstanceManager)); - - spyFlutterApi.create(cameraControl, reply -> {}); - - final long cameraControlIdentifier = - Objects.requireNonNull(testInstanceManager.getIdentifierForStrongReference(cameraControl)); - verify(spyFlutterApi).create(eq(cameraControlIdentifier), any()); - } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraInfoTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraInfoTest.java index e3cabcf4fde8..efedf52fa695 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraInfoTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraInfoTest.java @@ -5,11 +5,7 @@ package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import androidx.camera.core.CameraInfo; @@ -17,120 +13,52 @@ import androidx.camera.core.ExposureState; import androidx.camera.core.ZoomState; import androidx.lifecycle.LiveData; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.LiveDataSupportedType; -import java.util.Objects; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; public class CameraInfoTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public CameraInfo mockCameraInfo; - @Mock public BinaryMessenger mockBinaryMessenger; - - InstanceManager testInstanceManager; - - @Before - public void setUp() { - testInstanceManager = InstanceManager.create(identifier -> {}); - } - - @After - public void tearDown() { - testInstanceManager.stopFinalizationListener(); - } - @Test public void getSensorRotationDegrees_makesCallToRetrieveSensorRotationDegrees() { - final CameraInfoHostApiImpl cameraInfoHostApi = - new CameraInfoHostApiImpl(mockBinaryMessenger, testInstanceManager); - - testInstanceManager.addDartCreatedInstance(mockCameraInfo, 1); + final PigeonApiCameraInfo api = new TestProxyApiRegistrar().getPigeonApiCameraInfo(); - when(mockCameraInfo.getSensorRotationDegrees()).thenReturn(90); + final CameraInfo instance = mock(CameraInfo.class); + final long value = 0; + when(instance.getSensorRotationDegrees()).thenReturn((int) value); - assertEquals((long) cameraInfoHostApi.getSensorRotationDegrees(1L), 90L); - verify(mockCameraInfo).getSensorRotationDegrees(); + assertEquals(value, api.sensorRotationDegrees(instance)); } + @SuppressWarnings("unchecked") @Test public void getCameraState_makesCallToRetrieveLiveCameraState() { - final CameraInfoHostApiImpl cameraInfoHostApiImpl = - new CameraInfoHostApiImpl(mockBinaryMessenger, testInstanceManager); - final LiveDataFlutterApiWrapper mockLiveDataFlutterApiWrapper = - mock(LiveDataFlutterApiWrapper.class); - final Long mockCameraInfoIdentifier = 27L; - @SuppressWarnings("unchecked") - final LiveData mockLiveCameraState = (LiveData) mock(LiveData.class); - - testInstanceManager.addDartCreatedInstance(mockCameraInfo, mockCameraInfoIdentifier); - cameraInfoHostApiImpl.liveDataFlutterApiWrapper = mockLiveDataFlutterApiWrapper; - when(mockCameraInfo.getCameraState()).thenReturn(mockLiveCameraState); + final PigeonApiCameraInfo api = new TestProxyApiRegistrar().getPigeonApiCameraInfo(); - final Long liveCameraStateIdentifier = - cameraInfoHostApiImpl.getCameraState(mockCameraInfoIdentifier); + final CameraInfo instance = mock(CameraInfo.class); + final LiveData value = mock(LiveData.class); + when(instance.getCameraState()).thenReturn(value); - verify(mockLiveDataFlutterApiWrapper) - .create(eq(mockLiveCameraState), eq(LiveDataSupportedType.CAMERA_STATE), any()); - assertEquals( - liveCameraStateIdentifier, - testInstanceManager.getIdentifierForStrongReference(mockLiveCameraState)); + assertEquals(value, api.getCameraState(instance).getLiveData()); } @Test public void getExposureState_retrievesExpectedExposureState() { - final CameraInfoHostApiImpl cameraInfoHostApiImpl = - new CameraInfoHostApiImpl(mockBinaryMessenger, testInstanceManager); - final ExposureState mockExposureState = mock(ExposureState.class); - final Long mockCameraInfoIdentifier = 27L; - final Long mockExposureStateIdentifier = 47L; + final PigeonApiCameraInfo api = new TestProxyApiRegistrar().getPigeonApiCameraInfo(); - testInstanceManager.addDartCreatedInstance(mockCameraInfo, mockCameraInfoIdentifier); - testInstanceManager.addDartCreatedInstance(mockExposureState, mockExposureStateIdentifier); + final CameraInfo instance = mock(CameraInfo.class); + final androidx.camera.core.ExposureState value = mock(ExposureState.class); + when(instance.getExposureState()).thenReturn(value); - when(mockCameraInfo.getExposureState()).thenReturn(mockExposureState); - - assertEquals( - cameraInfoHostApiImpl.getExposureState(mockCameraInfoIdentifier), - mockExposureStateIdentifier); - verify(mockCameraInfo).getExposureState(); + assertEquals(value, api.exposureState(instance)); } - @Test @SuppressWarnings("unchecked") - public void getZoomState_retrievesExpectedZoomState() { - final CameraInfoHostApiImpl cameraInfoHostApiImpl = - new CameraInfoHostApiImpl(mockBinaryMessenger, testInstanceManager); - final LiveData mockLiveZoomState = (LiveData) mock(LiveData.class); - final ZoomState mockZoomState = mock(ZoomState.class); - final Long mockCameraInfoIdentifier = 20L; - final Long mockLiveZoomStateIdentifier = 74L; - - testInstanceManager.addDartCreatedInstance(mockCameraInfo, mockCameraInfoIdentifier); - testInstanceManager.addDartCreatedInstance(mockLiveZoomState, mockLiveZoomStateIdentifier); - - when(mockCameraInfo.getZoomState()).thenReturn(mockLiveZoomState); - - assertEquals( - cameraInfoHostApiImpl.getZoomState(mockCameraInfoIdentifier), mockLiveZoomStateIdentifier); - verify(mockCameraInfo).getZoomState(); - } - @Test - public void flutterApiCreate_makesCallToCreateInstanceOnDartSide() { - final CameraInfoFlutterApiImpl spyFlutterApi = - spy(new CameraInfoFlutterApiImpl(mockBinaryMessenger, testInstanceManager)); + public void getZoomState_retrievesExpectedZoomState() { + final PigeonApiCameraInfo api = new TestProxyApiRegistrar().getPigeonApiCameraInfo(); - spyFlutterApi.create(mockCameraInfo, reply -> {}); + final CameraInfo instance = mock(CameraInfo.class); + final LiveData value = mock(LiveData.class); + when(instance.getZoomState()).thenReturn(value); - final long identifier = - Objects.requireNonNull(testInstanceManager.getIdentifierForStrongReference(mockCameraInfo)); - verify(spyFlutterApi).create(eq(identifier), any()); + assertEquals(value, api.getZoomState(instance).getLiveData()); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraIntegerRangeTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraIntegerRangeTest.java new file mode 100644 index 000000000000..35c1099ecd9a --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraIntegerRangeTest.java @@ -0,0 +1,48 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import static org.junit.Assert.assertEquals; + +import android.util.Range; +import org.junit.Test; + +public class CameraIntegerRangeTest { + @SuppressWarnings("unchecked") + @Test + public void pigeon_defaultConstructor_createsInstanceWithConstructorValues() { + final PigeonApiCameraIntegerRange api = + new TestProxyApiRegistrar().getPigeonApiCameraIntegerRange(); + + final long lower = 2; + final long upper = 1; + + final Range instance = (Range) api.pigeon_defaultConstructor(lower, upper); + assertEquals((int) instance.getLower(), (int) lower); + assertEquals((int) instance.getUpper(), (int) upper); + } + + @Test + public void lower_returnsValueOfLowerFromInstance() { + final PigeonApiCameraIntegerRange api = + new TestProxyApiRegistrar().getPigeonApiCameraIntegerRange(); + + final int lower = 3; + final Range instance = new Range<>(lower, 4); + + assertEquals(lower, api.lower(instance)); + } + + @Test + public void upper_returnsValueOfUpperFromInstance() { + final PigeonApiCameraIntegerRange api = + new TestProxyApiRegistrar().getPigeonApiCameraIntegerRange(); + + final int upper = 4; + final Range instance = new Range<>(0, upper); + + assertEquals(upper, api.upper(instance)); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraPermissionsErrorTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraPermissionsErrorTest.java new file mode 100644 index 000000000000..f07922d00a62 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraPermissionsErrorTest.java @@ -0,0 +1,33 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class CameraPermissionsErrorTest { + @Test + public void errorCode_returnsValueOfErrorCodeFromInstance() { + final PigeonApiCameraPermissionsError api = + new TestProxyApiRegistrar().getPigeonApiCameraPermissionsError(); + + final String errorCode = "errorCode"; + final CameraPermissionsError instance = new CameraPermissionsError(errorCode, "desc"); + + assertEquals(errorCode, api.errorCode(instance)); + } + + @Test + public void description_returnsValueOfDescriptionFromInstance() { + final PigeonApiCameraPermissionsError api = + new TestProxyApiRegistrar().getPigeonApiCameraPermissionsError(); + + final String description = "desc"; + final CameraPermissionsError instance = new CameraPermissionsError("errorCode", description); + + assertEquals(description, api.description(instance)); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraPermissionsManagerTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraPermissionsManagerTest.java index d90bde953306..3e606a3378e8 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraPermissionsManagerTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraPermissionsManagerTest.java @@ -19,7 +19,7 @@ public class CameraPermissionsManagerTest { public void listener_respondsOnce() { final int[] calledCounter = {0}; CameraRequestPermissionsListener permissionsListener = - new CameraRequestPermissionsListener((String code, String desc) -> calledCounter[0]++); + new CameraRequestPermissionsListener((CameraPermissionsError error) -> calledCounter[0]++); permissionsListener.onRequestPermissionsResult( 9796, null, new int[] {PackageManager.PERMISSION_DENIED}); @@ -39,7 +39,9 @@ public void callback_respondsWithCameraAccessDenied() { 9796, null, new int[] {PackageManager.PERMISSION_DENIED}); verify(fakeResultCallback) - .onResult("CameraAccessDenied", "Camera access permission was denied."); + .onResult( + new CameraPermissionsError( + "CameraAccessDenied", "Camera access permission was denied.")); } @Test @@ -53,7 +55,9 @@ public void callback_respondsWithAudioAccessDenied() { null, new int[] {PackageManager.PERMISSION_GRANTED, PackageManager.PERMISSION_DENIED}); - verify(fakeResultCallback).onResult("AudioAccessDenied", "Audio access permission was denied."); + verify(fakeResultCallback) + .onResult( + new CameraPermissionsError("AudioAccessDenied", "Audio access permission was denied.")); } @Test @@ -68,9 +72,12 @@ public void callback_doesNotRespond() { new int[] {PackageManager.PERMISSION_GRANTED, PackageManager.PERMISSION_GRANTED}); verify(fakeResultCallback, never()) - .onResult("CameraAccessDenied", "Camera access permission was denied."); + .onResult( + new CameraPermissionsError( + "CameraAccessDenied", "Camera access permission was denied.")); verify(fakeResultCallback, never()) - .onResult("AudioAccessDenied", "Audio access permission was denied."); + .onResult( + new CameraPermissionsError("AudioAccessDenied", "Audio access permission was denied.")); } @Test @@ -84,6 +91,8 @@ public void callback_respondsWithCameraAccessDeniedWhenEmptyResult() { permissionsListener.onRequestPermissionsResult(9796, null, new int[] {}); verify(fakeResultCallback) - .onResult("CameraAccessDenied", "Camera access permission was denied."); + .onResult( + new CameraPermissionsError( + "CameraAccessDenied", "Camera access permission was denied.")); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraSelectorTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraSelectorTest.java index 81ae31f74753..93ab0014edda 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraSelectorTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraSelectorTest.java @@ -5,93 +5,38 @@ package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import androidx.camera.core.CameraInfo; import androidx.camera.core.CameraSelector; -import io.flutter.plugin.common.BinaryMessenger; -import java.util.Arrays; +import java.util.Collections; import java.util.List; -import java.util.Objects; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; public class CameraSelectorTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public CameraSelector mockCameraSelector; - @Mock public BinaryMessenger mockBinaryMessenger; - - InstanceManager testInstanceManager; - - @Before - public void setUp() { - testInstanceManager = InstanceManager.create(identifier -> {}); - } - - @After - public void tearDown() { - testInstanceManager.stopFinalizationListener(); - } - @Test - public void createTest() { - final CameraSelectorHostApiImpl cameraSelectorHostApi = - new CameraSelectorHostApiImpl(mockBinaryMessenger, testInstanceManager); - final CameraXProxy mockCameraXProxy = mock(CameraXProxy.class); - final CameraSelector.Builder mockCameraSelectorBuilder = mock(CameraSelector.Builder.class); + public void pigeon_defaultConstructor_createsCameraSelectorInstanceWithLensFacing() { + final PigeonApiCameraSelector api = new TestProxyApiRegistrar().getPigeonApiCameraSelector(); - cameraSelectorHostApi.cameraXProxy = mockCameraXProxy; - when(mockCameraXProxy.createCameraSelectorBuilder()).thenReturn(mockCameraSelectorBuilder); + final CameraSelector selector = + api.pigeon_defaultConstructor(io.flutter.plugins.camerax.LensFacing.FRONT); - when(mockCameraSelectorBuilder.requireLensFacing(1)).thenReturn(mockCameraSelectorBuilder); - when(mockCameraSelectorBuilder.build()).thenReturn(mockCameraSelector); - - cameraSelectorHostApi.create(0L, 1L); - - verify(mockCameraSelectorBuilder).requireLensFacing(CameraSelector.LENS_FACING_BACK); - assertEquals(testInstanceManager.getInstance(0L), mockCameraSelector); + assertEquals(selector.getLensFacing(), (Integer) CameraSelector.LENS_FACING_FRONT); } @Test - public void filterTest() { - final CameraSelectorHostApiImpl cameraSelectorHostApi = - new CameraSelectorHostApiImpl(mockBinaryMessenger, testInstanceManager); - final CameraInfo cameraInfo = mock(CameraInfo.class); - final List cameraInfosForFilter = Arrays.asList(cameraInfo); - final List cameraInfosIds = Arrays.asList(1L); - - testInstanceManager.addDartCreatedInstance(mockCameraSelector, 0); - testInstanceManager.addDartCreatedInstance(cameraInfo, 1); - - when(mockCameraSelector.filter(cameraInfosForFilter)).thenReturn(cameraInfosForFilter); + public void filter_callsFilterWithMethodParameters() { + final PigeonApiCameraSelector api = new TestProxyApiRegistrar().getPigeonApiCameraSelector(); - assertEquals( - cameraSelectorHostApi.filter(0L, cameraInfosIds), - Arrays.asList(testInstanceManager.getIdentifierForStrongReference(cameraInfo))); - verify(mockCameraSelector).filter(cameraInfosForFilter); - } - - @Test - public void flutterApiCreateTest() { - final CameraSelectorFlutterApiImpl spyFlutterApi = - spy(new CameraSelectorFlutterApiImpl(mockBinaryMessenger, testInstanceManager)); + final CameraSelector instance = mock(CameraSelector.class); - spyFlutterApi.create(mockCameraSelector, 0L, reply -> {}); + final List cameraInfos = + Collections.singletonList(mock(CameraInfo.class)); + final List value = + Collections.singletonList(mock(CameraInfo.class)); + when(instance.filter(cameraInfos)).thenReturn(value); - final long identifier = - Objects.requireNonNull( - testInstanceManager.getIdentifierForStrongReference(mockCameraSelector)); - verify(spyFlutterApi).create(eq(identifier), eq(0L), any()); + assertEquals(value, api.filter(instance, cameraInfos)); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraSizeTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraSizeTest.java new file mode 100644 index 000000000000..4a7bf85b4364 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraSizeTest.java @@ -0,0 +1,48 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import android.util.Size; +import org.junit.Test; + +public class CameraSizeTest { + @Test + public void pigeon_defaultConstructor_createsSizeInstanceWithWidthAndHeight() { + final PigeonApiCameraSize api = new TestProxyApiRegistrar().getPigeonApiCameraSize(); + + final int width = 6; + final int height = 7; + final Size instance = api.pigeon_defaultConstructor(width, height); + + assertEquals(instance.getWidth(), width); + assertEquals(instance.getHeight(), height); + } + + @Test + public void width_returnsWidthValueFromInstance() { + final PigeonApiCameraSize api = new TestProxyApiRegistrar().getPigeonApiCameraSize(); + + final Size instance = mock(Size.class); + final int value = 0; + when(instance.getWidth()).thenReturn(value); + + assertEquals(value, api.width(instance)); + } + + @Test + public void height_returnsHeightValueFromInstance() { + final PigeonApiCameraSize api = new TestProxyApiRegistrar().getPigeonApiCameraSize(); + + final Size instance = mock(Size.class); + final int value = 0; + when(instance.getHeight()).thenReturn(value); + + assertEquals(value, api.height(instance)); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraStateErrorTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraStateErrorTest.java deleted file mode 100644 index 0d07c496c8e6..000000000000 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraStateErrorTest.java +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.verify; - -import androidx.camera.core.CameraState; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraStateErrorFlutterApi; -import java.util.Objects; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; - -public class CameraStateErrorTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public CameraState.StateError mockCameraStateError; - @Mock public BinaryMessenger mockBinaryMessenger; - @Mock public CameraStateErrorFlutterApi mockFlutterApi; - - InstanceManager instanceManager; - - @Before - public void setUp() { - instanceManager = InstanceManager.create(identifier -> {}); - } - - @After - public void tearDown() { - instanceManager.stopFinalizationListener(); - } - - @Test - public void flutterApiCreate_makesCallToDartToCreateInstance() { - final CameraStateErrorFlutterApiWrapper flutterApi = - new CameraStateErrorFlutterApiWrapper(mockBinaryMessenger, instanceManager); - flutterApi.setApi(mockFlutterApi); - - final Long code = 0L; - - flutterApi.create(mockCameraStateError, code, reply -> {}); - - final long instanceIdentifier = - Objects.requireNonNull( - instanceManager.getIdentifierForStrongReference(mockCameraStateError)); - verify(mockFlutterApi).create(eq(instanceIdentifier), eq(code), any()); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraStateStateErrorTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraStateStateErrorTest.java new file mode 100644 index 000000000000..fc4a0c5574dd --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraStateStateErrorTest.java @@ -0,0 +1,27 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import androidx.camera.core.CameraState; +import org.junit.Test; + +public class CameraStateStateErrorTest { + @Test + public void code_returnsCodeValueFromInstance() { + final PigeonApiCameraStateStateError api = + new TestProxyApiRegistrar().getPigeonApiCameraStateStateError(); + + final CameraState.StateError instance = mock(CameraState.StateError.class); + final int value = CameraState.ERROR_CAMERA_DISABLED; + when(instance.getCode()).thenReturn(value); + + assertEquals( + io.flutter.plugins.camerax.CameraStateErrorCode.CAMERA_DISABLED, api.code(instance)); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraStateTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraStateTest.java index 726241e612cb..e7820c362ee6 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraStateTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraStateTest.java @@ -5,98 +5,32 @@ package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import androidx.camera.core.CameraState; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraStateFlutterApi; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraStateType; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraStateTypeData; -import java.util.Objects; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; public class CameraStateTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public CameraState mockCameraState; - @Mock public BinaryMessenger mockBinaryMessenger; - @Mock public CameraStateFlutterApi mockFlutterApi; + @Test + public void type_returnsExpectedType() { + final PigeonApiCameraState api = new TestProxyApiRegistrar().getPigeonApiCameraState(); - InstanceManager instanceManager; + final CameraState instance = mock(CameraState.class); + final CameraState.Type value = CameraState.Type.CLOSED; + when(instance.getType()).thenReturn(value); - @Before - public void setUp() { - instanceManager = InstanceManager.create(identifier -> {}); - } - - @After - public void tearDown() { - instanceManager.stopFinalizationListener(); + assertEquals(io.flutter.plugins.camerax.CameraStateType.CLOSED, api.type(instance)); } @Test - public void flutterApiCreate_makesCallToDartToCreateInstance() { - final CameraStateFlutterApiWrapper flutterApi = - new CameraStateFlutterApiWrapper(mockBinaryMessenger, instanceManager); - flutterApi.setApi(mockFlutterApi); - - final CameraStateType type = CameraStateType.OPEN; - final CameraState.StateError mockError = mock(CameraState.StateError.class); + public void error_returnsExpectedError() { + final PigeonApiCameraState api = new TestProxyApiRegistrar().getPigeonApiCameraState(); - flutterApi.create(mockCameraState, type, mockError, reply -> {}); + final CameraState instance = mock(CameraState.class); + final androidx.camera.core.CameraState.StateError value = mock(CameraState.StateError.class); + when(instance.getError()).thenReturn(value); - final long instanceIdentifier = - Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(mockCameraState)); - final ArgumentCaptor cameraStateTypeDataCaptor = - ArgumentCaptor.forClass(CameraStateTypeData.class); - - verify(mockFlutterApi) - .create( - eq(instanceIdentifier), - cameraStateTypeDataCaptor.capture(), - eq(Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(mockError))), - any()); - - assertEquals(cameraStateTypeDataCaptor.getValue().getValue(), type); - } - - @Test - public void getCameraStateType_returnsExpectedType() { - for (CameraState.Type type : CameraState.Type.values()) { - switch (type) { - case CLOSED: - assertEquals( - CameraStateFlutterApiWrapper.getCameraStateType(type), CameraStateType.CLOSED); - break; - case CLOSING: - assertEquals( - CameraStateFlutterApiWrapper.getCameraStateType(type), CameraStateType.CLOSING); - break; - case OPEN: - assertEquals(CameraStateFlutterApiWrapper.getCameraStateType(type), CameraStateType.OPEN); - break; - case OPENING: - assertEquals( - CameraStateFlutterApiWrapper.getCameraStateType(type), CameraStateType.OPENING); - break; - case PENDING_OPEN: - assertEquals( - CameraStateFlutterApiWrapper.getCameraStateType(type), CameraStateType.PENDING_OPEN); - break; - default: - fail("The CameraState.Type " + type.toString() + " is unhandled by this test."); - } - } + assertEquals(value, api.error(instance)); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraTest.java index 590529c93346..85f4fb0d3f11 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CameraTest.java @@ -5,87 +5,34 @@ package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import androidx.camera.core.Camera; import androidx.camera.core.CameraControl; import androidx.camera.core.CameraInfo; -import io.flutter.plugin.common.BinaryMessenger; -import java.util.Objects; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; public class CameraTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public BinaryMessenger mockBinaryMessenger; - @Mock public Camera camera; - - InstanceManager testInstanceManager; - - @Before - public void setUp() { - testInstanceManager = InstanceManager.create(identifier -> {}); - } - - @After - public void tearDown() { - testInstanceManager.stopFinalizationListener(); - } - @Test - public void getCameraInfo_retrievesExpectedCameraInfoInstance() { - final CameraHostApiImpl cameraHostApiImpl = - new CameraHostApiImpl(mockBinaryMessenger, testInstanceManager); - final CameraInfo mockCameraInfo = mock(CameraInfo.class); - final Long cameraIdentifier = 34L; - final Long mockCameraInfoIdentifier = 97L; + public void cameraInfo_retrievesExpectedCameraInfoInstance() { + final PigeonApiCamera api = new TestProxyApiRegistrar().getPigeonApiCamera(); - testInstanceManager.addDartCreatedInstance(camera, cameraIdentifier); - testInstanceManager.addDartCreatedInstance(mockCameraInfo, mockCameraInfoIdentifier); + final Camera instance = mock(Camera.class); + final androidx.camera.core.CameraInfo value = mock(CameraInfo.class); + when(instance.getCameraInfo()).thenReturn(value); - when(camera.getCameraInfo()).thenReturn(mockCameraInfo); - - assertEquals(cameraHostApiImpl.getCameraInfo(cameraIdentifier), mockCameraInfoIdentifier); - verify(camera).getCameraInfo(); + assertEquals(value, api.getCameraInfo(instance)); } @Test public void getCameraControl_retrievesExpectedCameraControlInstance() { - final CameraHostApiImpl cameraHostApiImpl = - new CameraHostApiImpl(mockBinaryMessenger, testInstanceManager); - final CameraControl mockCameraControl = mock(CameraControl.class); - final Long cameraIdentifier = 43L; - final Long mockCameraControlIdentifier = 79L; - - testInstanceManager.addDartCreatedInstance(camera, cameraIdentifier); - testInstanceManager.addDartCreatedInstance(mockCameraControl, mockCameraControlIdentifier); - - when(camera.getCameraControl()).thenReturn(mockCameraControl); - - assertEquals(cameraHostApiImpl.getCameraControl(cameraIdentifier), mockCameraControlIdentifier); - verify(camera).getCameraControl(); - } - - @Test - public void flutterApiCreate_makesCallToCreateInstanceOnDartSide() { - final CameraFlutterApiImpl spyFlutterApi = - spy(new CameraFlutterApiImpl(mockBinaryMessenger, testInstanceManager)); + final PigeonApiCamera api = new TestProxyApiRegistrar().getPigeonApiCamera(); - spyFlutterApi.create(camera, reply -> {}); + final Camera instance = mock(Camera.class); + final androidx.camera.core.CameraControl value = mock(CameraControl.class); + when(instance.getCameraControl()).thenReturn(value); - final long identifier = - Objects.requireNonNull(testInstanceManager.getIdentifierForStrongReference(camera)); - verify(spyFlutterApi).create(eq(identifier), any()); + assertEquals(value, api.cameraControl(instance)); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CaptureRequestOptionsTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CaptureRequestOptionsTest.java index 9c3329978d46..c10550d700fb 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CaptureRequestOptionsTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/CaptureRequestOptionsTest.java @@ -5,105 +5,51 @@ package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.hardware.camera2.CaptureRequest; +import android.hardware.camera2.CaptureRequest.Key; import androidx.camera.camera2.interop.CaptureRequestOptions; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CaptureRequestKeySupportedType; -import java.util.HashMap; import java.util.Map; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; public class CaptureRequestOptionsTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public CaptureRequestOptions mockCaptureRequestOptions; - - InstanceManager testInstanceManager; - - @Before - public void setUp() { - testInstanceManager = InstanceManager.create(identifier -> {}); - } - - @After - public void tearDown() { - testInstanceManager.stopFinalizationListener(); - } - + @SuppressWarnings("unchecked") @Test - public void create_buildsExpectedCaptureKeyRequestOptionsWhenOptionsNonNull() { - final CaptureRequestOptionsHostApiImpl.CaptureRequestOptionsProxy proxySpy = - spy(new CaptureRequestOptionsHostApiImpl.CaptureRequestOptionsProxy()); - final CaptureRequestOptionsHostApiImpl hostApi = - new CaptureRequestOptionsHostApiImpl(testInstanceManager, proxySpy); + public void pigeon_defaultConstructor_buildsExpectedCaptureKeyRequestOptions() { final CaptureRequestOptions.Builder mockBuilder = mock(CaptureRequestOptions.Builder.class); - final long instanceIdentifier = 44; - - // Map between CaptureRequestOptions indices and a test value for that option. - final Map options = - new HashMap() { - { - put(0L, false); + final CaptureRequestOptions mockOptions = mock(CaptureRequestOptions.class); + when(mockBuilder.build()).thenReturn(mockOptions); + final PigeonApiCaptureRequestOptions api = + new CaptureRequestOptionsProxyApi(mock(ProxyApiRegistrar.class)) { + @Override + CaptureRequestOptions.Builder createBuilder() { + return mockBuilder; } }; - when(proxySpy.getCaptureRequestOptionsBuilder()).thenReturn(mockBuilder); - when(mockBuilder.build()).thenReturn(mockCaptureRequestOptions); + final Key mockKey = mock(CaptureRequest.Key.class); + final int value = -1; + final Map, Object> options = Map.of(mockKey, value); + final CaptureRequestOptions instance = api.pigeon_defaultConstructor(options); - hostApi.create(instanceIdentifier, options); - for (CaptureRequestKeySupportedType supportedType : CaptureRequestKeySupportedType.values()) { - final Long supportedTypeIndex = Long.valueOf(supportedType.index); - final Object testValueForSupportedType = options.get(supportedTypeIndex); - switch (supportedType) { - case CONTROL_AE_LOCK: - verify(mockBuilder) - .setCaptureRequestOption( - eq(CaptureRequest.CONTROL_AE_LOCK), eq((Boolean) testValueForSupportedType)); - break; - default: - throw new IllegalArgumentException( - "The capture request key is not currently supported by the plugin."); - } - } - - assertEquals(testInstanceManager.getInstance(instanceIdentifier), mockCaptureRequestOptions); + verify(mockBuilder).setCaptureRequestOption(mockKey, value); + assertEquals(instance, mockOptions); } + @SuppressWarnings("unchecked") @Test - public void create_buildsExpectedCaptureKeyRequestOptionsWhenAnOptionIsNull() { - final CaptureRequestOptionsHostApiImpl.CaptureRequestOptionsProxy proxySpy = - spy(new CaptureRequestOptionsHostApiImpl.CaptureRequestOptionsProxy()); - final CaptureRequestOptionsHostApiImpl hostApi = - new CaptureRequestOptionsHostApiImpl(testInstanceManager, proxySpy); - final CaptureRequestOptions.Builder mockBuilder = mock(CaptureRequestOptions.Builder.class); - final long instanceIdentifier = 44; - - // Map between CaptureRequestOptions.CONTROL_AE_LOCK index and test value. - final Map options = - new HashMap() { - { - put(0L, null); - } - }; - - when(proxySpy.getCaptureRequestOptionsBuilder()).thenReturn(mockBuilder); - when(mockBuilder.build()).thenReturn(mockCaptureRequestOptions); - - hostApi.create(instanceIdentifier, options); + public void getCaptureRequestOption_returnsExpectedCorrespondingRequestOption() { + final PigeonApiCaptureRequestOptions api = + new TestProxyApiRegistrar().getPigeonApiCaptureRequestOptions(); - verify(mockBuilder).clearCaptureRequestOption(CaptureRequest.CONTROL_AE_LOCK); + final CaptureRequestOptions instance = mock(CaptureRequestOptions.class); + final Key key = mock(CaptureRequest.Key.class); + final int value = -1; + when(instance.getCaptureRequestOption(key)).thenReturn(value); - assertEquals(testInstanceManager.getInstance(instanceIdentifier), mockCaptureRequestOptions); + assertEquals(value, api.getCaptureRequestOption(instance, key)); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/DeviceOrientationManagerApiTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/DeviceOrientationManagerApiTest.java new file mode 100644 index 000000000000..f3f7d0d579b5 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/DeviceOrientationManagerApiTest.java @@ -0,0 +1,85 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import androidx.annotation.NonNull; +import io.flutter.embedding.engine.systemchannels.PlatformChannel; +import org.junit.Test; + +public class DeviceOrientationManagerApiTest { + @Test + public void startListeningForDeviceOrientationChange_callsStartOnInstance() { + final PigeonApiDeviceOrientationManager api = + new TestProxyApiRegistrar().getPigeonApiDeviceOrientationManager(); + + final DeviceOrientationManager instance = mock(DeviceOrientationManager.class); + api.startListeningForDeviceOrientationChange(instance); + + verify(instance).start(); + } + + @Test + public void stopListeningForDeviceOrientationChange_callsStopOnInstance() { + final PigeonApiDeviceOrientationManager api = + new TestProxyApiRegistrar().getPigeonApiDeviceOrientationManager(); + + final DeviceOrientationManager instance = mock(DeviceOrientationManager.class); + api.stopListeningForDeviceOrientationChange(instance); + + verify(instance).stop(); + } + + @Test + public void getDefaultDisplayRotation_returnsExpectedRotation() { + final PigeonApiDeviceOrientationManager api = + new TestProxyApiRegistrar().getPigeonApiDeviceOrientationManager(); + + final DeviceOrientationManager instance = mock(DeviceOrientationManager.class); + final Long value = 0L; + when(instance.getDefaultRotation()).thenReturn(value.intValue()); + + assertEquals(value, (Long) api.getDefaultDisplayRotation(instance)); + } + + @Test + public void getUiOrientation_returnsExpectedOrientation() { + final PigeonApiDeviceOrientationManager api = + new TestProxyApiRegistrar().getPigeonApiDeviceOrientationManager(); + + final DeviceOrientationManager instance = mock(DeviceOrientationManager.class); + final PlatformChannel.DeviceOrientation orientation = + PlatformChannel.DeviceOrientation.LANDSCAPE_RIGHT; + when(instance.getUIOrientation()).thenReturn(orientation); + + assertEquals(orientation.toString(), api.getUiOrientation(instance)); + } + + @Test + public void onDeviceOrientationChanged_shouldSendMessageWhenOrientationIsUpdated() { + final DeviceOrientationManagerProxyApi mockApi = mock(DeviceOrientationManagerProxyApi.class); + when(mockApi.getPigeonRegistrar()).thenReturn(new TestProxyApiRegistrar()); + + final PlatformChannel.DeviceOrientation orientation = + PlatformChannel.DeviceOrientation.PORTRAIT_UP; + final DeviceOrientationManager instance = + new DeviceOrientationManager(mockApi) { + @NonNull + @Override + PlatformChannel.DeviceOrientation getUIOrientation() { + return orientation; + } + }; + instance.handleUIOrientationChange(); + + verify(mockApi).onDeviceOrientationChanged(eq(instance), eq(orientation.toString()), any()); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/DeviceOrientationManagerTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/DeviceOrientationManagerTest.java index 1bb4077fb6dc..b75774f5e213 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/DeviceOrientationManagerTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/DeviceOrientationManagerTest.java @@ -21,33 +21,45 @@ import android.provider.Settings; import android.view.Display; import android.view.Surface; -import android.view.WindowManager; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import io.flutter.embedding.engine.systemchannels.PlatformChannel.DeviceOrientation; -import io.flutter.plugins.camerax.DeviceOrientationManager.DeviceOrientationChangeCallback; import org.junit.Before; import org.junit.Test; import org.mockito.MockedStatic; public class DeviceOrientationManagerTest { private Activity mockActivity; - private DeviceOrientationChangeCallback mockDeviceOrientationChangeCallback; - private WindowManager mockWindowManager; private Display mockDisplay; + + private DeviceOrientationManagerProxyApi mockApi; private DeviceOrientationManager deviceOrientationManager; @Before - @SuppressWarnings("deprecation") public void before() { mockActivity = mock(Activity.class); mockDisplay = mock(Display.class); - mockWindowManager = mock(WindowManager.class); - mockDeviceOrientationChangeCallback = mock(DeviceOrientationChangeCallback.class); - when(mockActivity.getSystemService(Context.WINDOW_SERVICE)).thenReturn(mockWindowManager); - when(mockWindowManager.getDefaultDisplay()).thenReturn(mockDisplay); + mockApi = mock(DeviceOrientationManagerProxyApi.class); + + final TestProxyApiRegistrar proxyApiRegistrar = + new TestProxyApiRegistrar() { + @NonNull + @Override + public Context getContext() { + return mockActivity; + } + + @Nullable + @Override + Display getDisplay() { + return mockDisplay; + } + }; + + when(mockApi.getPigeonRegistrar()).thenReturn(proxyApiRegistrar); - deviceOrientationManager = - new DeviceOrientationManager(mockActivity, false, 0, mockDeviceOrientationChangeCallback); + deviceOrientationManager = new DeviceOrientationManager(mockApi); } @Test @@ -63,8 +75,9 @@ public void handleUIOrientationChange_shouldSendMessageWhenSensorAccessIsAllowed deviceOrientationManager.handleUIOrientationChange(); } - verify(mockDeviceOrientationChangeCallback, times(1)) - .onChange(DeviceOrientation.LANDSCAPE_LEFT); + verify(mockApi, times(1)) + .onDeviceOrientationChanged( + eq(deviceOrientationManager), eq(DeviceOrientation.LANDSCAPE_LEFT.toString()), any()); } @Test @@ -73,9 +86,11 @@ public void handleOrientationChange_shouldSendMessageWhenOrientationIsUpdated() DeviceOrientation newOrientation = DeviceOrientation.LANDSCAPE_LEFT; DeviceOrientationManager.handleOrientationChange( - newOrientation, previousOrientation, mockDeviceOrientationChangeCallback); + deviceOrientationManager, newOrientation, previousOrientation, mockApi); - verify(mockDeviceOrientationChangeCallback, times(1)).onChange(newOrientation); + verify(mockApi, times(1)) + .onDeviceOrientationChanged( + eq(deviceOrientationManager), eq(newOrientation.toString()), any()); } @Test @@ -84,9 +99,9 @@ public void handleOrientationChange_shouldNotSendMessageWhenOrientationIsNotUpda DeviceOrientation newOrientation = DeviceOrientation.PORTRAIT_UP; DeviceOrientationManager.handleOrientationChange( - newOrientation, previousOrientation, mockDeviceOrientationChangeCallback); + deviceOrientationManager, newOrientation, previousOrientation, mockApi); - verify(mockDeviceOrientationChangeCallback, never()).onChange(any()); + verify(mockApi, never()).onDeviceOrientationChanged(any(), any(), any()); } @Test diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/DeviceOrientationManagerWrapperTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/DeviceOrientationManagerWrapperTest.java deleted file mode 100644 index ba7335971f1d..000000000000 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/DeviceOrientationManagerWrapperTest.java +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import android.app.Activity; -import io.flutter.embedding.engine.systemchannels.PlatformChannel.DeviceOrientation; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.DeviceOrientationManager.DeviceOrientationChangeCallback; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.DeviceOrientationManagerFlutterApi.Reply; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.ArgumentMatchers; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; - -public class DeviceOrientationManagerWrapperTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock DeviceOrientationManager mockDeviceOrientationManager; - @Mock public BinaryMessenger mockBinaryMessenger; - @Mock public InstanceManager mockInstanceManager; - - @Test - public void deviceOrientationManagerWrapper_handlesDeviceOrientationChangesAsExpected() { - final DeviceOrientationManagerHostApiImpl hostApi = - new DeviceOrientationManagerHostApiImpl(mockBinaryMessenger, mockInstanceManager); - final CameraXProxy mockCameraXProxy = mock(CameraXProxy.class); - final Activity mockActivity = mock(Activity.class); - final Boolean isFrontFacing = true; - final int sensorOrientation = 90; - - DeviceOrientationManagerFlutterApiImpl flutterApi = - mock(DeviceOrientationManagerFlutterApiImpl.class); - hostApi.deviceOrientationManagerFlutterApiImpl = flutterApi; - - hostApi.cameraXProxy = mockCameraXProxy; - hostApi.setActivity(mockActivity); - when(mockCameraXProxy.createDeviceOrientationManager( - eq(mockActivity), - eq(isFrontFacing), - eq(sensorOrientation), - any(DeviceOrientationChangeCallback.class))) - .thenReturn(mockDeviceOrientationManager); - - final ArgumentCaptor deviceOrientationChangeCallbackCaptor = - ArgumentCaptor.forClass(DeviceOrientationChangeCallback.class); - - hostApi.startListeningForDeviceOrientationChange( - isFrontFacing, Long.valueOf(sensorOrientation)); - - // Test callback method defined in Flutter API is called when device orientation changes. - verify(mockCameraXProxy) - .createDeviceOrientationManager( - eq(mockActivity), - eq(isFrontFacing), - eq(sensorOrientation), - deviceOrientationChangeCallbackCaptor.capture()); - DeviceOrientationChangeCallback deviceOrientationChangeCallback = - deviceOrientationChangeCallbackCaptor.getValue(); - - deviceOrientationChangeCallback.onChange(DeviceOrientation.PORTRAIT_DOWN); - verify(flutterApi) - .sendDeviceOrientationChangedEvent( - eq(DeviceOrientation.PORTRAIT_DOWN.toString()), ArgumentMatchers.>any()); - - // Test that the DeviceOrientationManager starts listening for device orientation changes. - verify(mockDeviceOrientationManager).start(); - - // Test that the DeviceOrientationManager can stop listening for device orientation changes. - hostApi.stopListeningForDeviceOrientationChange(); - verify(mockDeviceOrientationManager).stop(); - } - - @Test - public void getDefaultDisplayRotation_returnsExpectedRotation() { - final DeviceOrientationManagerHostApiImpl hostApi = - new DeviceOrientationManagerHostApiImpl(mockBinaryMessenger, mockInstanceManager); - final int defaultRotation = 180; - - hostApi.deviceOrientationManager = mockDeviceOrientationManager; - when(mockDeviceOrientationManager.getDefaultRotation()).thenReturn(defaultRotation); - - assertEquals(hostApi.getDefaultDisplayRotation(), Long.valueOf(defaultRotation)); - } - - @Test - public void getUiOrientation_returnsExpectedOrientation() { - final DeviceOrientationManagerHostApiImpl hostApi = - new DeviceOrientationManagerHostApiImpl(mockBinaryMessenger, mockInstanceManager); - final DeviceOrientation uiOrientation = DeviceOrientation.LANDSCAPE_LEFT; - - hostApi.deviceOrientationManager = mockDeviceOrientationManager; - when(mockDeviceOrientationManager.getUIOrientation()).thenReturn(uiOrientation); - - assertEquals(hostApi.getUiOrientation(), uiOrientation.toString()); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ExposureStateTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ExposureStateTest.java index 7eef68d28d12..d194a4568eb1 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ExposureStateTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ExposureStateTest.java @@ -5,80 +5,35 @@ package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import android.util.Range; import android.util.Rational; import androidx.camera.core.ExposureState; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ExposureCompensationRange; -import java.util.Objects; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.annotation.Config; -@RunWith(RobolectricTestRunner.class) public class ExposureStateTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public BinaryMessenger mockBinaryMessenger; - @Mock public ExposureState mockExposureState; - - InstanceManager testInstanceManager; + @SuppressWarnings("unchecked") + @Test + public void exposureCompensationRange_returnsExpectedRange() { + final PigeonApiExposureState api = new TestProxyApiRegistrar().getPigeonApiExposureState(); - @Before - public void setUp() { - testInstanceManager = InstanceManager.create(identifier -> {}); - } + final ExposureState instance = mock(ExposureState.class); + final android.util.Range value = mock(Range.class); + when(instance.getExposureCompensationRange()).thenReturn(value); - @After - public void tearDown() { - testInstanceManager.stopFinalizationListener(); + assertEquals(value, api.exposureCompensationRange(instance)); } - @Config(sdk = 21) @Test - public void create_makesExpectedCallToCreateInstanceOnDartSide() { - // SDK version configured because ExposureState requires Android 21. - ExposureStateFlutterApiImpl exposureStateFlutterApiImpl = - spy(new ExposureStateFlutterApiImpl(mockBinaryMessenger, testInstanceManager)); - final int minExposureCompensation = 0; - final int maxExposureCompensation = 1; - Range testExposueCompensationRange = - new Range(minExposureCompensation, maxExposureCompensation); - Rational textExposureCompensationStep = new Rational(1, 5); // Makes expected Double value 0.2. - - when(mockExposureState.getExposureCompensationRange()).thenReturn(testExposueCompensationRange); - when(mockExposureState.getExposureCompensationStep()).thenReturn(textExposureCompensationStep); - - final ArgumentCaptor exposureCompensationRangeCaptor = - ArgumentCaptor.forClass(ExposureCompensationRange.class); - - exposureStateFlutterApiImpl.create(mockExposureState, reply -> {}); + public void exposureCompensationStep_returnsExpectedStep() { + final PigeonApiExposureState api = new TestProxyApiRegistrar().getPigeonApiExposureState(); - final long identifier = - Objects.requireNonNull( - testInstanceManager.getIdentifierForStrongReference(mockExposureState)); - verify(exposureStateFlutterApiImpl) - .create(eq(identifier), exposureCompensationRangeCaptor.capture(), eq(0.2), any()); + final ExposureState instance = mock(ExposureState.class); + final double value = (double) 3 / 5; + when(instance.getExposureCompensationStep()).thenReturn(new Rational(3, 5)); - ExposureCompensationRange exposureCompensationRange = - exposureCompensationRangeCaptor.getValue(); - assertEquals( - exposureCompensationRange.getMinCompensation().intValue(), minExposureCompensation); - assertEquals( - exposureCompensationRange.getMaxCompensation().intValue(), maxExposureCompensation); + assertEquals(value, api.exposureCompensationStep(instance), 0.1); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/FallbackStrategyTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/FallbackStrategyTest.java index a68384fc7207..eeb1ed68f570 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/FallbackStrategyTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/FallbackStrategyTest.java @@ -5,114 +5,85 @@ package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockStatic; import androidx.camera.video.FallbackStrategy; import androidx.camera.video.Quality; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.VideoQuality; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.VideoResolutionFallbackRule; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.mockito.Mock; import org.mockito.MockedStatic; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; +import org.mockito.Mockito; import org.mockito.stubbing.Answer; public class FallbackStrategyTest { + @Test + public void higherQualityOrLowerThan_makesExpectedFallbackStrategyWithHigherQualityOrLowerThan() { + final PigeonApiFallbackStrategy api = + new TestProxyApiRegistrar().getPigeonApiFallbackStrategy(); + + final FallbackStrategy mockFallbackStrategy = mock(FallbackStrategy.class); - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock public FallbackStrategy mockFallbackStrategy; + try (MockedStatic mockedFallbackStrategy = + Mockito.mockStatic(FallbackStrategy.class)) { + final Quality quality = Quality.HD; + mockedFallbackStrategy + .when(() -> FallbackStrategy.higherQualityOrLowerThan(quality)) + .thenAnswer((Answer) invocation -> mockFallbackStrategy); + + assertEquals(api.higherQualityOrLowerThan(VideoQuality.HD), mockFallbackStrategy); + } + } + + @Test + public void higherQualityThan_makesExpectedFallbackStrategyWithHigherQualityThan() { + final PigeonApiFallbackStrategy api = + new TestProxyApiRegistrar().getPigeonApiFallbackStrategy(); + + final FallbackStrategy mockFallbackStrategy = mock(FallbackStrategy.class); - InstanceManager instanceManager; + try (MockedStatic mockedFallbackStrategy = + Mockito.mockStatic(FallbackStrategy.class)) { + final Quality quality = Quality.HD; + mockedFallbackStrategy + .when(() -> FallbackStrategy.higherQualityThan(quality)) + .thenAnswer((Answer) invocation -> mockFallbackStrategy); - @Before - public void setUp() { - instanceManager = InstanceManager.create(identifier -> {}); + assertEquals(api.higherQualityThan(VideoQuality.HD), mockFallbackStrategy); + } } - @After - public void tearDown() { - instanceManager.stopFinalizationListener(); + @Test + public void lowerQualityOrHigherThan_makesExpectedFallbackStrategyWithLowerQualityOrHigherThan() { + final PigeonApiFallbackStrategy api = + new TestProxyApiRegistrar().getPigeonApiFallbackStrategy(); + + final FallbackStrategy mockFallbackStrategy = mock(FallbackStrategy.class); + + try (MockedStatic mockedFallbackStrategy = + Mockito.mockStatic(FallbackStrategy.class)) { + final Quality quality = Quality.HD; + mockedFallbackStrategy + .when(() -> FallbackStrategy.lowerQualityOrHigherThan(quality)) + .thenAnswer((Answer) invocation -> mockFallbackStrategy); + + assertEquals(api.lowerQualityOrHigherThan(VideoQuality.HD), mockFallbackStrategy); + } } @Test - public void hostApiCreate_makesCallToCreateExpectedFallbackStrategy() { - final FallbackStrategyHostApiImpl hostApi = new FallbackStrategyHostApiImpl(instanceManager); - final long instanceIdentifier = 45; + public void lowerQualityThan_makesExpectedFallbackStrategyWithLowerQualityThan() { + final PigeonApiFallbackStrategy api = + new TestProxyApiRegistrar().getPigeonApiFallbackStrategy(); + final FallbackStrategy mockFallbackStrategy = mock(FallbackStrategy.class); try (MockedStatic mockedFallbackStrategy = - mockStatic(FallbackStrategy.class)) { - for (VideoQuality videoQuality : VideoQuality.values()) { - for (VideoResolutionFallbackRule fallbackRule : VideoResolutionFallbackRule.values()) { - // Determine expected Quality based on videoQuality being tested. - Quality convertedQuality = null; - switch (videoQuality) { - case SD: - convertedQuality = Quality.SD; - break; - case HD: - convertedQuality = Quality.HD; - break; - case FHD: - convertedQuality = Quality.FHD; - break; - case UHD: - convertedQuality = Quality.UHD; - break; - case LOWEST: - convertedQuality = Quality.LOWEST; - break; - case HIGHEST: - convertedQuality = Quality.HIGHEST; - break; - default: - fail("The VideoQuality " + videoQuality.toString() + "is unhandled by this test."); - } - // Set Quality as final local variable to avoid error about using non-final (or effecitvely final) local variables in lambda expressions. - final Quality expectedQuality = convertedQuality; - - // Mock calls to create FallbackStrategy according to fallbackRule being tested. - switch (fallbackRule) { - case HIGHER_QUALITY_OR_LOWER_THAN: - mockedFallbackStrategy - .when(() -> FallbackStrategy.higherQualityOrLowerThan(expectedQuality)) - .thenAnswer((Answer) invocation -> mockFallbackStrategy); - break; - case HIGHER_QUALITY_THAN: - mockedFallbackStrategy - .when(() -> FallbackStrategy.higherQualityThan(expectedQuality)) - .thenAnswer((Answer) invocation -> mockFallbackStrategy); - break; - case LOWER_QUALITY_OR_HIGHER_THAN: - mockedFallbackStrategy - .when(() -> FallbackStrategy.lowerQualityOrHigherThan(expectedQuality)) - .thenAnswer((Answer) invocation -> mockFallbackStrategy); - break; - case LOWER_QUALITY_THAN: - mockedFallbackStrategy - .when(() -> FallbackStrategy.lowerQualityThan(expectedQuality)) - .thenAnswer((Answer) invocation -> mockFallbackStrategy); - break; - default: - fail( - "The VideoResolutionFallbackRule " - + fallbackRule.toString() - + "is unhandled by this test."); - } - hostApi.create(instanceIdentifier, videoQuality, fallbackRule); - assertEquals(instanceManager.getInstance(instanceIdentifier), mockFallbackStrategy); - - // Clear/reset FallbackStrategy mock and InstanceManager. - mockedFallbackStrategy.reset(); - instanceManager.clear(); - } - } + Mockito.mockStatic(FallbackStrategy.class)) { + final Quality quality = Quality.HD; + mockedFallbackStrategy + .when(() -> FallbackStrategy.lowerQualityThan(quality)) + .thenAnswer((Answer) invocation -> mockFallbackStrategy); + + assertEquals(api.lowerQualityThan(VideoQuality.HD), mockFallbackStrategy); } } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/FocusMeteringActionBuilderTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/FocusMeteringActionBuilderTest.java new file mode 100644 index 000000000000..a0522d2162ae --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/FocusMeteringActionBuilderTest.java @@ -0,0 +1,64 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import androidx.camera.core.FocusMeteringAction; +import androidx.camera.core.MeteringPoint; +import org.junit.Test; + +public class FocusMeteringActionBuilderTest { + @Test + public void addPoint_callsAddPointWithoutModeOnInstance() { + final PigeonApiFocusMeteringActionBuilder api = + new TestProxyApiRegistrar().getPigeonApiFocusMeteringActionBuilder(); + + final FocusMeteringAction.Builder instance = mock(FocusMeteringAction.Builder.class); + final androidx.camera.core.MeteringPoint point = mock(MeteringPoint.class); + api.addPoint(instance, point); + + verify(instance).addPoint(point); + } + + @Test + public void addPointWithMode_callsAddPointWithModeOnInstance() { + final PigeonApiFocusMeteringActionBuilder api = + new TestProxyApiRegistrar().getPigeonApiFocusMeteringActionBuilder(); + + final FocusMeteringAction.Builder instance = mock(FocusMeteringAction.Builder.class); + final androidx.camera.core.MeteringPoint point = mock(MeteringPoint.class); + final MeteringMode mode = io.flutter.plugins.camerax.MeteringMode.AE; + api.addPointWithMode(instance, point, mode); + + verify(instance).addPoint(point, FocusMeteringAction.FLAG_AE); + } + + @Test + public void disableAutoCancel_callsDisableAutoCancelOnInstance() { + final PigeonApiFocusMeteringActionBuilder api = + new TestProxyApiRegistrar().getPigeonApiFocusMeteringActionBuilder(); + + final FocusMeteringAction.Builder instance = mock(FocusMeteringAction.Builder.class); + api.disableAutoCancel(instance); + + verify(instance).disableAutoCancel(); + } + + @Test + public void build_returnExpectedFocusMeteringAction() { + final PigeonApiFocusMeteringActionBuilder api = + new TestProxyApiRegistrar().getPigeonApiFocusMeteringActionBuilder(); + + final FocusMeteringAction.Builder instance = mock(FocusMeteringAction.Builder.class); + final androidx.camera.core.FocusMeteringAction value = mock(FocusMeteringAction.class); + when(instance.build()).thenReturn(value); + + assertEquals(value, api.build(instance)); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/FocusMeteringActionTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/FocusMeteringActionTest.java index 6d96d3036cd7..78e2b27409ef 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/FocusMeteringActionTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/FocusMeteringActionTest.java @@ -6,187 +6,62 @@ import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import androidx.camera.core.FocusMeteringAction; import androidx.camera.core.MeteringPoint; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.MeteringPointInfo; -import java.util.Arrays; +import java.util.Collections; import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; public class FocusMeteringActionTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public BinaryMessenger mockBinaryMessenger; - @Mock public FocusMeteringAction focusMeteringAction; + @Test + public void meteringPointsAe_returnsExpectedAeMeteringPoints() { + final PigeonApiFocusMeteringAction api = + new TestProxyApiRegistrar().getPigeonApiFocusMeteringAction(); - InstanceManager testInstanceManager; + final FocusMeteringAction instance = mock(FocusMeteringAction.class); + final List value = Collections.singletonList(mock(MeteringPoint.class)); + when(instance.getMeteringPointsAe()).thenReturn(value); - @Before - public void setUp() { - testInstanceManager = InstanceManager.create(identifier -> {}); - } - - @After - public void tearDown() { - testInstanceManager.stopFinalizationListener(); + assertEquals(value, api.meteringPointsAe(instance)); } @Test - public void hostApiCreate_createsExpectedFocusMeteringActionWithInitialPointThatHasMode() { - FocusMeteringActionHostApiImpl.FocusMeteringActionProxy proxySpy = - spy(new FocusMeteringActionHostApiImpl.FocusMeteringActionProxy()); - FocusMeteringActionHostApiImpl hostApi = - new FocusMeteringActionHostApiImpl(testInstanceManager, proxySpy); - final Long focusMeteringActionIdentifier = 43L; - - FocusMeteringAction.Builder mockFocusMeteringActionBuilder = - mock(FocusMeteringAction.Builder.class); - final MeteringPoint mockMeteringPoint1 = mock(MeteringPoint.class); - final MeteringPoint mockMeteringPoint2 = mock(MeteringPoint.class); - final MeteringPoint mockMeteringPoint3 = mock(MeteringPoint.class); - final Long mockMeteringPoint1Id = 47L; - final Long mockMeteringPoint2Id = 56L; - final Long mockMeteringPoint3Id = 99L; - final Integer mockMeteringPoint1Mode = FocusMeteringAction.FLAG_AE; - final Integer mockMeteringPoint2Mode = FocusMeteringAction.FLAG_AF; + public void meteringPointsAf_returnsExpectedAfMeteringPoints() { + final PigeonApiFocusMeteringAction api = + new TestProxyApiRegistrar().getPigeonApiFocusMeteringAction(); - MeteringPointInfo fakeMeteringPointInfo1 = - new MeteringPointInfo.Builder() - .setMeteringPointId(mockMeteringPoint1Id) - .setMeteringMode(mockMeteringPoint1Mode.longValue()) - .build(); - MeteringPointInfo fakeMeteringPointInfo2 = - new MeteringPointInfo.Builder() - .setMeteringPointId(mockMeteringPoint2Id) - .setMeteringMode(mockMeteringPoint2Mode.longValue()) - .build(); - MeteringPointInfo fakeMeteringPointInfo3 = - new MeteringPointInfo.Builder() - .setMeteringPointId(mockMeteringPoint3Id) - .setMeteringMode(null) - .build(); + final FocusMeteringAction instance = mock(FocusMeteringAction.class); + final List value = + Collections.singletonList(mock(MeteringPoint.class)); + when(instance.getMeteringPointsAf()).thenReturn(value); - testInstanceManager.addDartCreatedInstance(mockMeteringPoint1, mockMeteringPoint1Id); - testInstanceManager.addDartCreatedInstance(mockMeteringPoint2, mockMeteringPoint2Id); - testInstanceManager.addDartCreatedInstance(mockMeteringPoint3, mockMeteringPoint3Id); - - when(proxySpy.getFocusMeteringActionBuilder( - mockMeteringPoint1, mockMeteringPoint1Mode.intValue())) - .thenReturn(mockFocusMeteringActionBuilder); - when(mockFocusMeteringActionBuilder.build()).thenReturn(focusMeteringAction); - - List mockMeteringPointInfos = - Arrays.asList(fakeMeteringPointInfo1, fakeMeteringPointInfo2, fakeMeteringPointInfo3); - - hostApi.create(focusMeteringActionIdentifier, mockMeteringPointInfos, null); - - verify(mockFocusMeteringActionBuilder).addPoint(mockMeteringPoint2, mockMeteringPoint2Mode); - verify(mockFocusMeteringActionBuilder).addPoint(mockMeteringPoint3); - assertEquals( - testInstanceManager.getInstance(focusMeteringActionIdentifier), focusMeteringAction); + assertEquals(value, api.meteringPointsAf(instance)); } @Test - public void - hostApiCreate_createsExpectedFocusMeteringActionWithInitialPointThatDoesNotHaveMode() { - FocusMeteringActionHostApiImpl.FocusMeteringActionProxy proxySpy = - spy(new FocusMeteringActionHostApiImpl.FocusMeteringActionProxy()); - FocusMeteringActionHostApiImpl hostApi = - new FocusMeteringActionHostApiImpl(testInstanceManager, proxySpy); - final Long focusMeteringActionIdentifier = 43L; - - FocusMeteringAction.Builder mockFocusMeteringActionBuilder = - mock(FocusMeteringAction.Builder.class); - final MeteringPoint mockMeteringPoint1 = mock(MeteringPoint.class); - final MeteringPoint mockMeteringPoint2 = mock(MeteringPoint.class); - final MeteringPoint mockMeteringPoint3 = mock(MeteringPoint.class); - final Long mockMeteringPoint1Id = 47L; - final Long mockMeteringPoint2Id = 56L; - final Long mockMeteringPoint3Id = 99L; - final Integer mockMeteringPoint2Mode = FocusMeteringAction.FLAG_AF; + public void meteringPointsAwb_returnsExpectedAwbMeteringPoints() { + final PigeonApiFocusMeteringAction api = + new TestProxyApiRegistrar().getPigeonApiFocusMeteringAction(); - MeteringPointInfo fakeMeteringPointInfo1 = - new MeteringPointInfo.Builder() - .setMeteringPointId(mockMeteringPoint1Id) - .setMeteringMode(null) - .build(); - MeteringPointInfo fakeMeteringPointInfo2 = - new MeteringPointInfo.Builder() - .setMeteringPointId(mockMeteringPoint2Id) - .setMeteringMode(mockMeteringPoint2Mode.longValue()) - .build(); - MeteringPointInfo fakeMeteringPointInfo3 = - new MeteringPointInfo.Builder() - .setMeteringPointId(mockMeteringPoint3Id) - .setMeteringMode(null) - .build(); + final FocusMeteringAction instance = mock(FocusMeteringAction.class); + final List value = + Collections.singletonList(mock(MeteringPoint.class)); + when(instance.getMeteringPointsAwb()).thenReturn(value); - testInstanceManager.addDartCreatedInstance(mockMeteringPoint1, mockMeteringPoint1Id); - testInstanceManager.addDartCreatedInstance(mockMeteringPoint2, mockMeteringPoint2Id); - testInstanceManager.addDartCreatedInstance(mockMeteringPoint3, mockMeteringPoint3Id); - - when(proxySpy.getFocusMeteringActionBuilder(mockMeteringPoint1)) - .thenReturn(mockFocusMeteringActionBuilder); - when(mockFocusMeteringActionBuilder.build()).thenReturn(focusMeteringAction); - - List mockMeteringPointInfos = - Arrays.asList(fakeMeteringPointInfo1, fakeMeteringPointInfo2, fakeMeteringPointInfo3); - - hostApi.create(focusMeteringActionIdentifier, mockMeteringPointInfos, null); - - verify(mockFocusMeteringActionBuilder).addPoint(mockMeteringPoint2, mockMeteringPoint2Mode); - verify(mockFocusMeteringActionBuilder).addPoint(mockMeteringPoint3); - assertEquals( - testInstanceManager.getInstance(focusMeteringActionIdentifier), focusMeteringAction); + assertEquals(value, api.meteringPointsAwb(instance)); } @Test - public void hostApiCreate_disablesAutoCancelAsExpected() { - FocusMeteringActionHostApiImpl.FocusMeteringActionProxy proxySpy = - spy(new FocusMeteringActionHostApiImpl.FocusMeteringActionProxy()); - FocusMeteringActionHostApiImpl hostApi = - new FocusMeteringActionHostApiImpl(testInstanceManager, proxySpy); - - FocusMeteringAction.Builder mockFocusMeteringActionBuilder = - mock(FocusMeteringAction.Builder.class); - final MeteringPoint mockMeteringPoint = mock(MeteringPoint.class); - final Long mockMeteringPointId = 47L; - - MeteringPointInfo fakeMeteringPointInfo = - new MeteringPointInfo.Builder() - .setMeteringPointId(mockMeteringPointId) - .setMeteringMode(null) - .build(); - - testInstanceManager.addDartCreatedInstance(mockMeteringPoint, mockMeteringPointId); - - when(proxySpy.getFocusMeteringActionBuilder(mockMeteringPoint)) - .thenReturn(mockFocusMeteringActionBuilder); - when(mockFocusMeteringActionBuilder.build()).thenReturn(focusMeteringAction); - - List mockMeteringPointInfos = Arrays.asList(fakeMeteringPointInfo); - - // Test not disabling auto cancel. - hostApi.create(73L, mockMeteringPointInfos, /* disableAutoCancel */ null); - verify(mockFocusMeteringActionBuilder, never()).disableAutoCancel(); + public void isAutoCancelEnabled_callsIsAutoCancelEnabledOnInstance() { + final PigeonApiFocusMeteringAction api = + new TestProxyApiRegistrar().getPigeonApiFocusMeteringAction(); - hostApi.create(74L, mockMeteringPointInfos, /* disableAutoCancel */ false); - verify(mockFocusMeteringActionBuilder, never()).disableAutoCancel(); + final FocusMeteringAction instance = mock(FocusMeteringAction.class); + final Boolean value = true; + when(instance.isAutoCancelEnabled()).thenReturn(value); - // Test disabling auto cancel. - hostApi.create(75L, mockMeteringPointInfos, /* disableAutoCancel */ true); - verify(mockFocusMeteringActionBuilder).disableAutoCancel(); + assertEquals(value, api.isAutoCancelEnabled(instance)); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/FocusMeteringResultTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/FocusMeteringResultTest.java index dae86557b45b..9e3f930d4a47 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/FocusMeteringResultTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/FocusMeteringResultTest.java @@ -4,70 +4,23 @@ package io.flutter.plugins.camerax; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.verify; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import androidx.camera.core.FocusMeteringResult; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.FocusMeteringResultFlutterApi; -import java.util.Objects; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; public class FocusMeteringResultTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public BinaryMessenger mockBinaryMessenger; - @Mock public FocusMeteringResult focusMeteringResult; - @Mock public FocusMeteringResultFlutterApi mockFlutterApi; - - InstanceManager testInstanceManager; - - @Before - public void setUp() { - testInstanceManager = InstanceManager.create(identifier -> {}); - } - - @After - public void tearDown() { - testInstanceManager.stopFinalizationListener(); - } - @Test public void isFocusSuccessful_returnsExpectedResult() { - final FocusMeteringResultHostApiImpl focusMeteringResultHostApiImpl = - new FocusMeteringResultHostApiImpl(testInstanceManager); - final Long focusMeteringResultIdentifier = 98L; - final boolean result = true; - - testInstanceManager.addDartCreatedInstance(focusMeteringResult, focusMeteringResultIdentifier); - - when(focusMeteringResult.isFocusSuccessful()).thenReturn(result); - - assertTrue(focusMeteringResultHostApiImpl.isFocusSuccessful(focusMeteringResultIdentifier)); - verify(focusMeteringResult).isFocusSuccessful(); - } - - @Test - public void flutterApiCreate_makesCallToCreateInstanceOnDartSide() { - final FocusMeteringResultFlutterApiImpl flutterApi = - new FocusMeteringResultFlutterApiImpl(mockBinaryMessenger, testInstanceManager); - - flutterApi.setApi(mockFlutterApi); + final PigeonApiFocusMeteringResult api = + new TestProxyApiRegistrar().getPigeonApiFocusMeteringResult(); - flutterApi.create(focusMeteringResult, reply -> {}); - final long focusMeteringResultIdentifier = - Objects.requireNonNull( - testInstanceManager.getIdentifierForStrongReference(focusMeteringResult)); + final FocusMeteringResult instance = mock(FocusMeteringResult.class); + final Boolean value = true; + when(instance.isFocusSuccessful()).thenReturn(value); - verify(mockFlutterApi).create(eq(focusMeteringResultIdentifier), any()); + assertEquals(value, api.isFocusSuccessful(instance)); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ImageAnalysisTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ImageAnalysisTest.java index 5e4a729dbd23..5b8aa9a9c0c9 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ImageAnalysisTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ImageAnalysisTest.java @@ -5,114 +5,89 @@ package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import android.content.Context; import android.view.Surface; import androidx.camera.core.ImageAnalysis; +import androidx.camera.core.ImageAnalysis.Analyzer; import androidx.camera.core.resolutionselector.ResolutionSelector; -import androidx.test.core.app.ApplicationProvider; -import io.flutter.plugin.common.BinaryMessenger; +import androidx.core.content.ContextCompat; import java.util.concurrent.Executor; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.stubbing.Answer; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class ImageAnalysisTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock public ImageAnalysis mockImageAnalysis; - @Mock public BinaryMessenger mockBinaryMessenger; - - InstanceManager instanceManager; - private Context context; + @Test + public void pigeon_defaultConstructor_createsExpectedImageAnalysisInstance() { + final PigeonApiImageAnalysis api = new TestProxyApiRegistrar().getPigeonApiImageAnalysis(); - @Before - public void setUp() { - instanceManager = InstanceManager.create(identifier -> {}); - context = ApplicationProvider.getApplicationContext(); - } + final ResolutionSelector mockResolutionSelector = new ResolutionSelector.Builder().build(); + final long targetResolution = Surface.ROTATION_0; + final ImageAnalysis imageAnalysis = + api.pigeon_defaultConstructor(mockResolutionSelector, targetResolution); - @After - public void tearDown() { - instanceManager.stopFinalizationListener(); + assertEquals(imageAnalysis.getResolutionSelector(), mockResolutionSelector); + assertEquals(imageAnalysis.getTargetRotation(), Surface.ROTATION_0); } @Test - public void hostApiCreate_createsExpectedImageAnalysisInstanceWithExpectedIdentifier() { - final ImageAnalysisHostApiImpl hostApi = - new ImageAnalysisHostApiImpl(mockBinaryMessenger, instanceManager, context); - final CameraXProxy mockCameraXProxy = mock(CameraXProxy.class); - final ImageAnalysis.Builder mockImageAnalysisBuilder = mock(ImageAnalysis.Builder.class); - final ResolutionSelector mockResolutionSelector = mock(ResolutionSelector.class); - final long instanceIdentifier = 0; - final long mockResolutionSelectorId = 25; - final int targetRotation = Surface.ROTATION_90; - - hostApi.cameraXProxy = mockCameraXProxy; - instanceManager.addDartCreatedInstance(mockResolutionSelector, mockResolutionSelectorId); - - when(mockCameraXProxy.createImageAnalysisBuilder()).thenReturn(mockImageAnalysisBuilder); - when(mockImageAnalysisBuilder.build()).thenReturn(mockImageAnalysis); - - hostApi.create(instanceIdentifier, Long.valueOf(targetRotation), mockResolutionSelectorId); - - verify(mockImageAnalysisBuilder).setTargetRotation(targetRotation); - verify(mockImageAnalysisBuilder).setResolutionSelector(mockResolutionSelector); - assertEquals(instanceManager.getInstance(instanceIdentifier), mockImageAnalysis); + public void resolutionSelector_returnsExpectedResolutionSelector() { + final PigeonApiImageAnalysis api = new TestProxyApiRegistrar().getPigeonApiImageAnalysis(); + + final ImageAnalysis instance = mock(ImageAnalysis.class); + final androidx.camera.core.resolutionselector.ResolutionSelector value = + mock(ResolutionSelector.class); + when(instance.getResolutionSelector()).thenReturn(value); + + assertEquals(value, api.resolutionSelector(instance)); } @Test public void setAnalyzer_makesCallToSetAnalyzerOnExpectedImageAnalysisInstance() { - final ImageAnalysisHostApiImpl hostApi = - new ImageAnalysisHostApiImpl(mockBinaryMessenger, instanceManager, context); + final PigeonApiImageAnalysis api = new TestProxyApiRegistrar().getPigeonApiImageAnalysis(); - final ImageAnalysis.Analyzer mockAnalyzer = mock(ImageAnalysis.Analyzer.class); - final long analyzerIdentifier = 10; - final long instanceIdentifier = 94; + final ImageAnalysis instance = mock(ImageAnalysis.class); + final androidx.camera.core.ImageAnalysis.Analyzer analyzer = mock(Analyzer.class); - instanceManager.addDartCreatedInstance(mockAnalyzer, analyzerIdentifier); - instanceManager.addDartCreatedInstance(mockImageAnalysis, instanceIdentifier); + try (MockedStatic mockedContextCompat = + Mockito.mockStatic(ContextCompat.class)) { + mockedContextCompat + .when(() -> ContextCompat.getMainExecutor(any())) + .thenAnswer((Answer) invocation -> mock(Executor.class)); - hostApi.setAnalyzer(instanceIdentifier, analyzerIdentifier); + api.setAnalyzer(instance, analyzer); - verify(mockImageAnalysis).setAnalyzer(any(Executor.class), eq(mockAnalyzer)); + verify(instance).setAnalyzer(any(), eq(analyzer)); + } } @Test public void clearAnalyzer_makesCallToClearAnalyzerOnExpectedImageAnalysisInstance() { - final ImageAnalysisHostApiImpl hostApi = - new ImageAnalysisHostApiImpl(mockBinaryMessenger, instanceManager, context); - final long instanceIdentifier = 22; - - instanceManager.addDartCreatedInstance(mockImageAnalysis, instanceIdentifier); + final PigeonApiImageAnalysis api = new TestProxyApiRegistrar().getPigeonApiImageAnalysis(); - hostApi.clearAnalyzer(instanceIdentifier); + final ImageAnalysis instance = mock(ImageAnalysis.class); + api.clearAnalyzer(instance); - verify(mockImageAnalysis).clearAnalyzer(); + verify(instance).clearAnalyzer(); } @Test public void setTargetRotation_makesCallToSetTargetRotation() { - final ImageAnalysisHostApiImpl hostApi = - new ImageAnalysisHostApiImpl(mockBinaryMessenger, instanceManager, context); - final long instanceIdentifier = 32; - final int targetRotation = Surface.ROTATION_180; - - instanceManager.addDartCreatedInstance(mockImageAnalysis, instanceIdentifier); + final PigeonApiImageAnalysis api = new TestProxyApiRegistrar().getPigeonApiImageAnalysis(); - hostApi.setTargetRotation(instanceIdentifier, Long.valueOf(targetRotation)); + final ImageAnalysis instance = mock(ImageAnalysis.class); + final long rotation = Surface.ROTATION_180; + api.setTargetRotation(instance, rotation); - verify(mockImageAnalysis).setTargetRotation(targetRotation); + verify(instance).setTargetRotation(Surface.ROTATION_180); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ImageCaptureTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ImageCaptureTest.java index 591037fd97cb..02151111f96c 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ImageCaptureTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ImageCaptureTest.java @@ -4,218 +4,234 @@ package io.flutter.plugins.camerax; +import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import android.content.Context; import android.view.Surface; +import androidx.annotation.NonNull; import androidx.camera.core.ImageCapture; import androidx.camera.core.ImageCaptureException; import androidx.camera.core.resolutionselector.ResolutionSelector; -import io.flutter.plugin.common.BinaryMessenger; import java.io.File; import java.io.IOException; import java.util.concurrent.Executor; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; +import kotlin.Result; +import kotlin.Unit; +import kotlin.jvm.functions.Function1; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Mock; import org.mockito.MockedStatic; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class ImageCaptureTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public ImageCapture mockImageCapture; - @Mock public BinaryMessenger mockBinaryMessenger; - @Mock public CameraXProxy mockCameraXProxy; - - InstanceManager testInstanceManager; - private Context context; - private MockedStatic mockedStaticFile; - - @Before - public void setUp() throws Exception { - testInstanceManager = spy(InstanceManager.create(identifier -> {})); - context = mock(Context.class); - mockedStaticFile = mockStatic(File.class); - } - - @After - public void tearDown() { - testInstanceManager.stopFinalizationListener(); - mockedStaticFile.close(); + @Test + public void pigeon_defaultConstructor_createsImageCaptureWithCorrectConfiguration() { + final PigeonApiImageCapture api = new TestProxyApiRegistrar().getPigeonApiImageCapture(); + + final ResolutionSelector mockResolutionSelector = new ResolutionSelector.Builder().build(); + final long targetResolution = Surface.ROTATION_0; + final ImageCapture imageCapture = + api.pigeon_defaultConstructor( + mockResolutionSelector, targetResolution, CameraXFlashMode.OFF); + + assertEquals(imageCapture.getResolutionSelector(), mockResolutionSelector); + assertEquals(imageCapture.getTargetRotation(), Surface.ROTATION_0); + assertEquals(imageCapture.getFlashMode(), ImageCapture.FLASH_MODE_OFF); } @Test - public void create_createsImageCaptureWithCorrectConfiguration() { - final ImageCaptureHostApiImpl imageCaptureHostApiImpl = - new ImageCaptureHostApiImpl(mockBinaryMessenger, testInstanceManager, context); - final ImageCapture.Builder mockImageCaptureBuilder = mock(ImageCapture.Builder.class); - final Long imageCaptureIdentifier = 74L; - final int flashMode = ImageCapture.FLASH_MODE_ON; - final ResolutionSelector mockResolutionSelector = mock(ResolutionSelector.class); - final long mockResolutionSelectorId = 77; - final int targetRotation = Surface.ROTATION_270; - - imageCaptureHostApiImpl.cameraXProxy = mockCameraXProxy; - testInstanceManager.addDartCreatedInstance(mockResolutionSelector, mockResolutionSelectorId); - when(mockCameraXProxy.createImageCaptureBuilder()).thenReturn(mockImageCaptureBuilder); - when(mockImageCaptureBuilder.build()).thenReturn(mockImageCapture); - - imageCaptureHostApiImpl.create( - imageCaptureIdentifier, - Long.valueOf(targetRotation), - Long.valueOf(flashMode), - mockResolutionSelectorId); - - verify(mockImageCaptureBuilder).setTargetRotation(targetRotation); - verify(mockImageCaptureBuilder).setFlashMode(flashMode); - verify(mockImageCaptureBuilder).setResolutionSelector(mockResolutionSelector); - verify(mockImageCaptureBuilder).build(); - verify(testInstanceManager).addDartCreatedInstance(mockImageCapture, imageCaptureIdentifier); + public void resolutionSelector_returnsExpectedResolutionSelector() { + final PigeonApiImageCapture api = new TestProxyApiRegistrar().getPigeonApiImageCapture(); + + final ImageCapture instance = mock(ImageCapture.class); + final ResolutionSelector value = mock(ResolutionSelector.class); + when(instance.getResolutionSelector()).thenReturn(value); + + assertEquals(value, api.resolutionSelector(instance)); } @Test public void setFlashMode_setsFlashModeOfImageCaptureInstance() { - final ImageCaptureHostApiImpl imageCaptureHostApiImpl = - new ImageCaptureHostApiImpl(mockBinaryMessenger, testInstanceManager, context); - final Long imageCaptureIdentifier = 85L; - final Long flashMode = Long.valueOf(ImageCapture.FLASH_MODE_AUTO); - - testInstanceManager.addDartCreatedInstance(mockImageCapture, imageCaptureIdentifier); + final PigeonApiImageCapture api = new TestProxyApiRegistrar().getPigeonApiImageCapture(); - imageCaptureHostApiImpl.setFlashMode(imageCaptureIdentifier, flashMode); + final ImageCapture instance = mock(ImageCapture.class); + final CameraXFlashMode flashMode = io.flutter.plugins.camerax.CameraXFlashMode.AUTO; + api.setFlashMode(instance, flashMode); - verify(mockImageCapture).setFlashMode(flashMode.intValue()); + verify(instance).setFlashMode(ImageCapture.FLASH_MODE_AUTO); } @Test public void takePicture_sendsRequestToTakePictureWithExpectedConfigurationWhenTemporaryFileCanBeCreated() { - final ImageCaptureHostApiImpl imageCaptureHostApiImpl = - spy(new ImageCaptureHostApiImpl(mockBinaryMessenger, testInstanceManager, context)); - final Long imageCaptureIdentifier = 6L; + final ProxyApiRegistrar mockApiRegistrar = mock(ProxyApiRegistrar.class); + final Context mockContext = mock(Context.class); final File mockOutputDir = mock(File.class); - final File mockFile = mock(File.class); - final ImageCapture.OutputFileOptions mockOutputFileOptions = - mock(ImageCapture.OutputFileOptions.class); - final ImageCapture.OnImageSavedCallback mockOnImageSavedCallback = - mock(ImageCapture.OnImageSavedCallback.class); - @SuppressWarnings("unchecked") - final GeneratedCameraXLibrary.Result mockResult = - mock(GeneratedCameraXLibrary.Result.class); - - testInstanceManager.addDartCreatedInstance(mockImageCapture, imageCaptureIdentifier); - when(context.getCacheDir()).thenReturn(mockOutputDir); - imageCaptureHostApiImpl.cameraXProxy = mockCameraXProxy; - mockedStaticFile - .when( - () -> - File.createTempFile( - ImageCaptureHostApiImpl.TEMPORARY_FILE_NAME, - ImageCaptureHostApiImpl.JPG_FILE_TYPE, - mockOutputDir)) - .thenReturn(mockFile); - when(mockCameraXProxy.createImageCaptureOutputFileOptions(mockFile)) - .thenReturn(mockOutputFileOptions); - when(imageCaptureHostApiImpl.createOnImageSavedCallback(mockFile, mockResult)) - .thenReturn(mockOnImageSavedCallback); - - imageCaptureHostApiImpl.takePicture(imageCaptureIdentifier, mockResult); - - verify(mockImageCapture) - .takePicture(eq(mockOutputFileOptions), any(Executor.class), eq(mockOnImageSavedCallback)); + when(mockContext.getCacheDir()).thenReturn(mockOutputDir); + when(mockApiRegistrar.getContext()).thenReturn(mockContext); + + final String filename = "myFile.jpg"; + final ImageCaptureProxyApi api = + new ImageCaptureProxyApi(mockApiRegistrar) { + @Override + ImageCapture.OutputFileOptions createImageCaptureOutputFileOptions(@NonNull File file) { + return super.createImageCaptureOutputFileOptions(file); + } + + @NonNull + @Override + ImageCapture.OnImageSavedCallback createOnImageSavedCallback( + @NonNull File file, @NonNull Function1, Unit> callback) { + final File mockFile = mock(File.class); + when(mockFile.getAbsolutePath()).thenReturn(filename); + final ImageCapture.OnImageSavedCallback imageSavedCallback = + super.createOnImageSavedCallback(mockFile, callback); + imageSavedCallback.onImageSaved(mock(ImageCapture.OutputFileResults.class)); + return imageSavedCallback; + } + }; + + final ImageCapture instance = mock(ImageCapture.class); + + try (MockedStatic mockedStaticFile = mockStatic(File.class)) { + final File mockFile = mock(File.class); + mockedStaticFile + .when( + () -> + File.createTempFile( + ImageCaptureProxyApi.TEMPORARY_FILE_NAME, + ImageCaptureProxyApi.JPG_FILE_TYPE, + mockOutputDir)) + .thenReturn(mockFile); + + final String[] result = {null}; + api.takePicture( + instance, + ResultCompat.asCompatCallback( + reply -> { + result[0] = reply.getOrNull(); + return null; + })); + + verify(instance) + .takePicture( + any(ImageCapture.OutputFileOptions.class), + any(Executor.class), + any(ImageCapture.OnImageSavedCallback.class)); + assertEquals(result[0], filename); + } } @Test public void takePicture_sendsErrorWhenTemporaryFileCannotBeCreated() { - final ImageCaptureHostApiImpl imageCaptureHostApiImpl = - new ImageCaptureHostApiImpl(mockBinaryMessenger, testInstanceManager, context); - final Long imageCaptureIdentifier = 6L; + final ProxyApiRegistrar mockApiRegistrar = mock(ProxyApiRegistrar.class); + final Context mockContext = mock(Context.class); final File mockOutputDir = mock(File.class); - final File mockTemporaryCaptureFile = mock(File.class); - @SuppressWarnings("unchecked") - final GeneratedCameraXLibrary.Result mockResult = - mock(GeneratedCameraXLibrary.Result.class); - final IOException fileCreationException = new IOException(); - - testInstanceManager.addDartCreatedInstance(mockImageCapture, imageCaptureIdentifier); - imageCaptureHostApiImpl.cameraXProxy = mockCameraXProxy; - when(context.getCacheDir()).thenReturn(mockOutputDir); - mockedStaticFile - .when( - () -> - File.createTempFile( - ImageCaptureHostApiImpl.TEMPORARY_FILE_NAME, - ImageCaptureHostApiImpl.JPG_FILE_TYPE, - mockOutputDir)) - .thenThrow(fileCreationException); - - imageCaptureHostApiImpl.takePicture(imageCaptureIdentifier, mockResult); - - verify(mockResult).error(fileCreationException); - verify(mockImageCapture, times(0)) - .takePicture( - any(ImageCapture.OutputFileOptions.class), - any(Executor.class), - any(ImageCapture.OnImageSavedCallback.class)); + when(mockContext.getCacheDir()).thenReturn(mockOutputDir); + when(mockApiRegistrar.getContext()).thenReturn(mockContext); + + final PigeonApiImageCapture api = new ImageCaptureProxyApi(mockApiRegistrar); + + final ImageCapture instance = mock(ImageCapture.class); + + try (MockedStatic mockedStaticFile = mockStatic(File.class)) { + final IOException fileCreationException = new IOException(); + mockedStaticFile + .when( + () -> + File.createTempFile( + ImageCaptureProxyApi.TEMPORARY_FILE_NAME, + ImageCaptureProxyApi.JPG_FILE_TYPE, + mockOutputDir)) + .thenThrow(fileCreationException); + + final Throwable[] result = {null}; + api.takePicture( + instance, + ResultCompat.asCompatCallback( + reply -> { + result[0] = reply.exceptionOrNull(); + return null; + })); + + verifyNoInteractions(instance); + assertEquals(result[0], fileCreationException); + } } @Test - public void takePicture_usesExpectedOnImageSavedCallback() { - final ImageCaptureHostApiImpl imageCaptureHostApiImpl = - new ImageCaptureHostApiImpl(mockBinaryMessenger, testInstanceManager, context); - final SystemServicesFlutterApiImpl mockSystemServicesFlutterApiImpl = - mock(SystemServicesFlutterApiImpl.class); - final File mockFile = mock(File.class); - @SuppressWarnings("unchecked") - final GeneratedCameraXLibrary.Result mockResult = - mock(GeneratedCameraXLibrary.Result.class); - final ImageCapture.OutputFileResults mockOutputFileResults = - mock(ImageCapture.OutputFileResults.class); - final String mockFileAbsolutePath = "absolute/path/to/captured/image"; - final ImageCaptureException mockException = mock(ImageCaptureException.class); - - imageCaptureHostApiImpl.cameraXProxy = mockCameraXProxy; - when(mockFile.getAbsolutePath()).thenReturn(mockFileAbsolutePath); - - ImageCapture.OnImageSavedCallback onImageSavedCallback = - imageCaptureHostApiImpl.createOnImageSavedCallback(mockFile, mockResult); - - // Test success case. - onImageSavedCallback.onImageSaved(mockOutputFileResults); - - verify(mockResult).success(mockFileAbsolutePath); - - // Test error case. - onImageSavedCallback.onError(mockException); - - verify(mockResult).error(mockException); + public void takePicture_onImageSavedCallbackCanSendsError() { + final ProxyApiRegistrar mockApiRegistrar = mock(ProxyApiRegistrar.class); + final Context mockContext = mock(Context.class); + final File mockOutputDir = mock(File.class); + when(mockContext.getCacheDir()).thenReturn(mockOutputDir); + when(mockApiRegistrar.getContext()).thenReturn(mockContext); + + final ImageCaptureException captureException = mock(ImageCaptureException.class); + final ImageCaptureProxyApi api = + new ImageCaptureProxyApi(mockApiRegistrar) { + @Override + ImageCapture.OutputFileOptions createImageCaptureOutputFileOptions(@NonNull File file) { + return super.createImageCaptureOutputFileOptions(file); + } + + @NonNull + @Override + ImageCapture.OnImageSavedCallback createOnImageSavedCallback( + @NonNull File file, @NonNull Function1, Unit> callback) { + final ImageCapture.OnImageSavedCallback imageSavedCallback = + super.createOnImageSavedCallback(mock(File.class), callback); + imageSavedCallback.onError(captureException); + return imageSavedCallback; + } + }; + + final ImageCapture instance = mock(ImageCapture.class); + + try (MockedStatic mockedStaticFile = mockStatic(File.class)) { + final File mockFile = mock(File.class); + mockedStaticFile + .when( + () -> + File.createTempFile( + ImageCaptureProxyApi.TEMPORARY_FILE_NAME, + ImageCaptureProxyApi.JPG_FILE_TYPE, + mockOutputDir)) + .thenReturn(mockFile); + + final Throwable[] result = {null}; + api.takePicture( + instance, + ResultCompat.asCompatCallback( + reply -> { + result[0] = reply.exceptionOrNull(); + return null; + })); + + verify(instance) + .takePicture( + any(ImageCapture.OutputFileOptions.class), + any(Executor.class), + any(ImageCapture.OnImageSavedCallback.class)); + assertEquals(result[0], captureException); + } } @Test public void setTargetRotation_makesCallToSetTargetRotation() { - final ImageCaptureHostApiImpl hostApi = - new ImageCaptureHostApiImpl(mockBinaryMessenger, testInstanceManager, context); - final long instanceIdentifier = 42; - final int targetRotation = Surface.ROTATION_90; - - testInstanceManager.addDartCreatedInstance(mockImageCapture, instanceIdentifier); + final PigeonApiImageCapture api = new TestProxyApiRegistrar().getPigeonApiImageCapture(); - hostApi.setTargetRotation(instanceIdentifier, Long.valueOf(targetRotation)); + final ImageCapture instance = mock(ImageCapture.class); + final long rotation = 0; + api.setTargetRotation(instance, rotation); - verify(mockImageCapture).setTargetRotation(targetRotation); + verify(instance).setTargetRotation((int) rotation); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ImageProxyTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ImageProxyTest.java index 99cd06a7beae..50f7782ef61f 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ImageProxyTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ImageProxyTest.java @@ -5,115 +5,68 @@ package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import androidx.camera.core.ImageProxy; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ImageProxyFlutterApi; -import java.nio.ByteBuffer; +import androidx.camera.core.ImageProxy.PlaneProxy; +import java.util.Collections; import java.util.List; -import java.util.Objects; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.robolectric.annotation.Config; public class ImageProxyTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock public ImageProxy mockImageProxy; - @Mock public BinaryMessenger mockBinaryMessenger; - @Mock public ImageProxyFlutterApi mockFlutterApi; + @Test + public void format_returnsExpectedFormat() { + final PigeonApiImageProxy api = new TestProxyApiRegistrar().getPigeonApiImageProxy(); - InstanceManager instanceManager; + final ImageProxy instance = mock(ImageProxy.class); + final long value = 0; + when(instance.getFormat()).thenReturn((int) value); - @Before - public void setUp() { - instanceManager = InstanceManager.create(identifier -> {}); + assertEquals(value, api.format(instance)); } - @After - public void tearDown() { - instanceManager.stopFinalizationListener(); + @Test + public void width_returnsExpectedWidth() { + final PigeonApiImageProxy api = new TestProxyApiRegistrar().getPigeonApiImageProxy(); + + final ImageProxy instance = mock(ImageProxy.class); + final long value = 0; + when(instance.getWidth()).thenReturn((int) value); + + assertEquals(value, api.width(instance)); } - @Config(sdk = 21) @Test - public void getPlanes_returnsExpectedPlanesFromExpectedImageProxyInstance() { - final ImageProxyHostApiImpl hostApi = - new ImageProxyHostApiImpl(mockBinaryMessenger, instanceManager); - final CameraXProxy mockCameraXProxy = mock(CameraXProxy.class); - final PlaneProxyFlutterApiImpl mockPlaneProxyFlutterApiImpl = - mock(PlaneProxyFlutterApiImpl.class); - final long instanceIdentifier = 24; - final long mockPlaneProxyIdentifier = 45; - final ImageProxy.PlaneProxy mockPlaneProxy = mock(ImageProxy.PlaneProxy.class); - final ImageProxy.PlaneProxy[] returnValue = new ImageProxy.PlaneProxy[] {mockPlaneProxy}; - final ByteBuffer mockByteBuffer = mock(ByteBuffer.class); - final int bufferRemaining = 23; - final byte[] buffer = new byte[bufferRemaining]; - final int pixelStride = 2; - final int rowStride = 65; - - instanceManager.addDartCreatedInstance(mockImageProxy, instanceIdentifier); - - hostApi.cameraXProxy = mockCameraXProxy; - hostApi.planeProxyFlutterApiImpl = mockPlaneProxyFlutterApiImpl; - - when(mockImageProxy.getPlanes()).thenReturn(returnValue); - when(mockPlaneProxy.getBuffer()).thenReturn(mockByteBuffer); - when(mockByteBuffer.remaining()).thenReturn(bufferRemaining); - when(mockCameraXProxy.getBytesFromBuffer(bufferRemaining)).thenReturn(buffer); - when(mockPlaneProxy.getPixelStride()).thenReturn(pixelStride); - when(mockPlaneProxy.getRowStride()).thenReturn(rowStride); - - final List result = hostApi.getPlanes(instanceIdentifier); - - verify(mockImageProxy).getPlanes(); - verify(mockPlaneProxyFlutterApiImpl) - .create( - eq(mockPlaneProxy), - eq(buffer), - eq(Long.valueOf(pixelStride)), - eq(Long.valueOf(rowStride)), - any()); - assertEquals(result.size(), 1); + public void height_returnsExpectedHeight() { + final PigeonApiImageProxy api = new TestProxyApiRegistrar().getPigeonApiImageProxy(); + + final ImageProxy instance = mock(ImageProxy.class); + final long value = 0; + when(instance.getHeight()).thenReturn((int) value); + + assertEquals(value, api.height(instance)); } @Test - public void close_makesCallToCloseExpectedImageProxyInstance() { - final ImageProxyHostApiImpl hostApi = - new ImageProxyHostApiImpl(mockBinaryMessenger, instanceManager); - final long instanceIdentifier = 9; + public void getPlanes_returnsExpectedPlanes() { + final PigeonApiImageProxy api = new TestProxyApiRegistrar().getPigeonApiImageProxy(); - instanceManager.addDartCreatedInstance(mockImageProxy, instanceIdentifier); + final ImageProxy instance = mock(ImageProxy.class); + final List value = Collections.singletonList(mock(PlaneProxy.class)); + when(instance.getPlanes()).thenReturn(value.toArray(new PlaneProxy[] {})); - hostApi.close(instanceIdentifier); - - verify(mockImageProxy).close(); + assertEquals(value, api.getPlanes(instance)); } @Test - public void flutterApiCreate_makesCallToDartCreate() { - final ImageProxyFlutterApiImpl flutterApi = - new ImageProxyFlutterApiImpl(mockBinaryMessenger, instanceManager); - final long format = 3; - final long height = 2; - final long width = 1; - - flutterApi.setApi(mockFlutterApi); + public void close_callsCloseOnInstance() { + final PigeonApiImageProxy api = new TestProxyApiRegistrar().getPigeonApiImageProxy(); - flutterApi.create(mockImageProxy, format, height, width, reply -> {}); - final long instanceIdentifier = - Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(mockImageProxy)); + final ImageProxy instance = mock(ImageProxy.class); + api.close(instance); - verify(mockFlutterApi).create(eq(instanceIdentifier), eq(format), eq(height), eq(width), any()); + verify(instance).close(); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/InstanceManagerTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/InstanceManagerTest.java deleted file mode 100644 index 7dd5e62acabb..000000000000 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/InstanceManagerTest.java +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -public class InstanceManagerTest { - @Test - public void addDartCreatedInstance() { - final InstanceManager instanceManager = InstanceManager.create(identifier -> {}); - - final Object object = new Object(); - instanceManager.addDartCreatedInstance(object, 0); - - assertEquals(object, instanceManager.getInstance(0)); - assertEquals((Long) 0L, instanceManager.getIdentifierForStrongReference(object)); - assertTrue(instanceManager.containsInstance(object)); - - instanceManager.stopFinalizationListener(); - } - - @Test - public void addHostCreatedInstance() { - final InstanceManager instanceManager = InstanceManager.create(identifier -> {}); - - final Object object = new Object(); - long identifier = instanceManager.addHostCreatedInstance(object); - - assertNotNull(instanceManager.getInstance(identifier)); - assertEquals(object, instanceManager.getInstance(identifier)); - assertTrue(instanceManager.containsInstance(object)); - - instanceManager.stopFinalizationListener(); - } - - @Test - public void removeReturnsRemovedObjectAndClearsIdentifier() { - final InstanceManager instanceManager = InstanceManager.create(identifier -> {}); - - Object object = new Object(); - instanceManager.addDartCreatedInstance(object, 0); - - assertEquals(object, instanceManager.remove(0)); - - // To allow for object to be garbage collected. - //noinspection UnusedAssignment - object = null; - - Runtime.getRuntime().gc(); - - assertNull(instanceManager.getInstance(0)); - - instanceManager.stopFinalizationListener(); - } - - @Test - public void clear() { - final InstanceManager instanceManager = InstanceManager.create(identifier -> {}); - - final Object instance = new Object(); - - instanceManager.addDartCreatedInstance(instance, 0); - assertTrue(instanceManager.containsInstance(instance)); - - instanceManager.clear(); - assertFalse(instanceManager.containsInstance(instance)); - - instanceManager.stopFinalizationListener(); - } - - @Test - public void canAddSameObjectWithAddDartCreatedInstance() { - final InstanceManager instanceManager = InstanceManager.create(identifier -> {}); - - final Object instance = new Object(); - - instanceManager.addDartCreatedInstance(instance, 0); - instanceManager.addDartCreatedInstance(instance, 1); - - assertTrue(instanceManager.containsInstance(instance)); - - assertEquals(instanceManager.getInstance(0), instance); - assertEquals(instanceManager.getInstance(1), instance); - - instanceManager.stopFinalizationListener(); - } - - @Test(expected = IllegalArgumentException.class) - public void cannotAddSameObjectsWithAddHostCreatedInstance() { - final InstanceManager instanceManager = InstanceManager.create(identifier -> {}); - - final Object instance = new Object(); - - instanceManager.addHostCreatedInstance(instance); - instanceManager.addHostCreatedInstance(instance); - - instanceManager.stopFinalizationListener(); - } - - @Test(expected = IllegalArgumentException.class) - public void cannotUseIdentifierLessThanZero() { - final InstanceManager instanceManager = InstanceManager.create(identifier -> {}); - - instanceManager.addDartCreatedInstance(new Object(), -1); - - instanceManager.stopFinalizationListener(); - } - - @Test(expected = IllegalArgumentException.class) - public void identifiersMustBeUnique() { - final InstanceManager instanceManager = InstanceManager.create(identifier -> {}); - - instanceManager.addDartCreatedInstance(new Object(), 0); - instanceManager.addDartCreatedInstance(new Object(), 0); - - instanceManager.stopFinalizationListener(); - } - - @Test - public void managerIsUsableWhileListenerHasStopped() { - final InstanceManager instanceManager = InstanceManager.create(identifier -> {}); - instanceManager.stopFinalizationListener(); - - final Object instance = new Object(); - final long identifier = 0; - - instanceManager.addDartCreatedInstance(instance, identifier); - assertEquals(instanceManager.getInstance(identifier), instance); - assertEquals(instanceManager.getIdentifierForStrongReference(instance), (Long) identifier); - assertTrue(instanceManager.containsInstance(instance)); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/JavaObjectHostApiTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/JavaObjectHostApiTest.java deleted file mode 100644 index d05bf5bc46b5..000000000000 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/JavaObjectHostApiTest.java +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.camerax; - -import static org.junit.Assert.assertNull; - -import org.junit.Test; - -public class JavaObjectHostApiTest { - @Test - public void dispose() { - final InstanceManager instanceManager = InstanceManager.create(identifier -> {}); - - final JavaObjectHostApiImpl hostApi = new JavaObjectHostApiImpl(instanceManager); - - Object object = new Object(); - instanceManager.addDartCreatedInstance(object, 0); - - // To free object for garbage collection. - //noinspection UnusedAssignment - object = null; - - hostApi.dispose(0L); - Runtime.getRuntime().gc(); - - assertNull(instanceManager.getInstance(0)); - - instanceManager.stopFinalizationListener(); - } -} diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/LiveDataTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/LiveDataTest.java index 8002ff94de95..c0cf221e22fc 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/LiveDataTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/LiveDataTest.java @@ -5,150 +5,85 @@ package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import androidx.camera.core.CameraState; -import androidx.camera.core.ZoomState; +import androidx.annotation.Nullable; import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.LiveData; import androidx.lifecycle.Observer; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.LiveDataFlutterApi; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.LiveDataSupportedType; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.LiveDataSupportedTypeData; -import java.util.Objects; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; +import io.flutter.plugins.camerax.LiveDataProxyApi.LiveDataWrapper; import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; public class LiveDataTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public LiveData mockLiveData; - - @Mock public BinaryMessenger mockBinaryMessenger; - @Mock public LiveDataFlutterApi mockFlutterApi; - - InstanceManager instanceManager; + @Test + public void type_returnsExpectedType() { + final PigeonApiLiveData api = new TestProxyApiRegistrar().getPigeonApiLiveData(); - @Before - public void setUp() { - instanceManager = InstanceManager.create(identifier -> {}); - } + final LiveDataSupportedType value = + io.flutter.plugins.camerax.LiveDataSupportedType.CAMERA_STATE; + final LiveDataWrapper instance = new LiveDataWrapper(mock(LiveData.class), value); - @After - public void tearDown() { - instanceManager.stopFinalizationListener(); + assertEquals(value, api.type(instance)); } + @SuppressWarnings("unchecked") @Test - @SuppressWarnings({"unchecked", "rawtypes"}) - public void observe_addsExpectedObserverToLiveDataInstance() { - final LiveDataHostApiImpl hostApi = - new LiveDataHostApiImpl(mockBinaryMessenger, instanceManager); - final Observer mockObserver = mock(Observer.class); - final long observerIdentifier = 20; - final long instanceIdentifier = 29; - final LifecycleOwner mockLifecycleOwner = mock(LifecycleOwner.class); - - instanceManager.addDartCreatedInstance(mockObserver, observerIdentifier); - instanceManager.addDartCreatedInstance(mockLiveData, instanceIdentifier); - - hostApi.setLifecycleOwner(mockLifecycleOwner); - hostApi.observe(instanceIdentifier, observerIdentifier); - - verify(mockLiveData).observe(mockLifecycleOwner, mockObserver); + public void observe_callsObserveOnInstanceWithLifeCycleOwner() { + final PigeonApiLiveData api = + new TestProxyApiRegistrar() { + @Nullable + @Override + public LifecycleOwner getLifecycleOwner() { + return mock(LifecycleOwner.class); + } + }.getPigeonApiLiveData(); + + final LiveData liveData = mock(LiveData.class); + final LiveDataWrapper instance = + new LiveDataWrapper(liveData, LiveDataSupportedType.CAMERA_STATE); + + final Observer observer = mock(Observer.class); + api.observe(instance, observer); + + verify(liveData).observe(any(LifecycleOwner.class), eq(observer)); } + @SuppressWarnings("unchecked") @Test - public void removeObservers_makesCallToRemoveObserversFromLiveDataInstance() { - final LiveDataHostApiImpl hostApi = - new LiveDataHostApiImpl(mockBinaryMessenger, instanceManager); - final long instanceIdentifier = 10; - final LifecycleOwner mockLifecycleOwner = mock(LifecycleOwner.class); - - instanceManager.addDartCreatedInstance(mockLiveData, instanceIdentifier); - - hostApi.setLifecycleOwner(mockLifecycleOwner); - hostApi.removeObservers(instanceIdentifier); - - verify(mockLiveData).removeObservers(mockLifecycleOwner); + public void removeObservers_callsRemoveObserversOnInstance() { + final PigeonApiLiveData api = + new TestProxyApiRegistrar() { + @Nullable + @Override + public LifecycleOwner getLifecycleOwner() { + return mock(LifecycleOwner.class); + } + }.getPigeonApiLiveData(); + + final LiveData liveData = mock(LiveData.class); + final LiveDataWrapper instance = + new LiveDataWrapper(liveData, LiveDataSupportedType.CAMERA_STATE); + + api.removeObservers(instance); + + verify(liveData).removeObservers(any(LifecycleOwner.class)); } - @Test @SuppressWarnings("unchecked") - public void getValue_returnsExpectedValue() { - final LiveDataHostApiImpl hostApi = - new LiveDataHostApiImpl(mockBinaryMessenger, instanceManager); - - for (LiveDataSupportedType supportedType : LiveDataSupportedType.values()) { - LiveDataSupportedTypeData typeData = - new LiveDataSupportedTypeData.Builder().setValue(supportedType).build(); - - switch (supportedType) { - case CAMERA_STATE: - CameraState mockCameraState = mock(CameraState.class); - final Long mockCameraStateIdentifier = 56L; - final long instanceIdentifier = 33; - - instanceManager.addDartCreatedInstance(mockLiveData, instanceIdentifier); - instanceManager.addDartCreatedInstance(mockCameraState, mockCameraStateIdentifier); - - when(mockLiveData.getValue()).thenReturn(mockCameraState); - when(mockCameraState.getType()).thenReturn(CameraState.Type.CLOSED); - when(mockCameraState.getError()).thenReturn(null); - - assertEquals(hostApi.getValue(instanceIdentifier, typeData), mockCameraStateIdentifier); - break; - case ZOOM_STATE: - final LiveData mockLiveZoomState = (LiveData) mock(LiveData.class); - ZoomState mockZoomState = mock(ZoomState.class); - final Long mockLiveZoomStateIdentifier = 22L; - final Long mockZoomStateIdentifier = 8L; - - when(mockLiveZoomState.getValue()).thenReturn(mockZoomState); - instanceManager.addDartCreatedInstance(mockLiveZoomState, mockLiveZoomStateIdentifier); - instanceManager.addDartCreatedInstance(mockZoomState, mockZoomStateIdentifier); - - assertEquals( - hostApi.getValue(mockLiveZoomStateIdentifier, typeData), mockZoomStateIdentifier); - break; - default: - fail( - "The LiveDataSupportedType " - + supportedType.toString() - + "is unhandled by this test."); - } - } - } - @Test - public void flutterApiCreate_makesCallToDartToCreateInstance() { - final LiveDataFlutterApiWrapper flutterApi = - new LiveDataFlutterApiWrapper(mockBinaryMessenger, instanceManager); - final LiveDataSupportedType liveDataType = LiveDataSupportedType.CAMERA_STATE; - - flutterApi.setApi(mockFlutterApi); - - final ArgumentCaptor liveDataSupportedTypeDataCaptor = - ArgumentCaptor.forClass(LiveDataSupportedTypeData.class); + public void getValue_returnsExpectedResult() { + final PigeonApiLiveData api = new TestProxyApiRegistrar().getPigeonApiLiveData(); - flutterApi.create(mockLiveData, liveDataType, reply -> {}); + final LiveData liveData = mock(LiveData.class); + final String result = "result"; + when(liveData.getValue()).thenReturn(result); + final LiveDataWrapper instance = + new LiveDataWrapper(liveData, LiveDataSupportedType.CAMERA_STATE); - final long instanceIdentifier = - Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(mockLiveData)); - verify(mockFlutterApi) - .create(eq(instanceIdentifier), liveDataSupportedTypeDataCaptor.capture(), any()); - assertEquals(liveDataSupportedTypeDataCaptor.getValue().getValue(), liveDataType); + assertEquals(result, api.getValue(instance)); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/MeteringPointFactoryTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/MeteringPointFactoryTest.java new file mode 100644 index 000000000000..2a30ea6f0e16 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/MeteringPointFactoryTest.java @@ -0,0 +1,44 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import androidx.camera.core.MeteringPoint; +import androidx.camera.core.MeteringPointFactory; +import org.junit.Test; + +public class MeteringPointFactoryTest { + @Test + public void createPoint_createsExpectedMeteringPointWithoutSizeSpecified() { + final PigeonApiMeteringPointFactory api = + new TestProxyApiRegistrar().getPigeonApiMeteringPointFactory(); + + final MeteringPointFactory instance = mock(MeteringPointFactory.class); + final double x = 1.0; + final double y = 2.0; + final androidx.camera.core.MeteringPoint value = mock(MeteringPoint.class); + when(instance.createPoint((float) x, (float) y)).thenReturn(value); + + assertEquals(value, api.createPoint(instance, x, y)); + } + + @Test + public void createPointWithSize_createsExpectedMeteringPointWithSizeSpecified() { + final PigeonApiMeteringPointFactory api = + new TestProxyApiRegistrar().getPigeonApiMeteringPointFactory(); + + final MeteringPointFactory instance = mock(MeteringPointFactory.class); + final double x = 1.0; + final double y = 2.0; + final double size = 3.0; + final androidx.camera.core.MeteringPoint value = mock(MeteringPoint.class); + when(instance.createPoint((float) x, (float) y, (float) size)).thenReturn(value); + + assertEquals(value, api.createPointWithSize(instance, x, y, size)); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/MeteringPointTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/MeteringPointTest.java index 0734f6ba6a9d..24f31641788a 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/MeteringPointTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/MeteringPointTest.java @@ -6,226 +6,20 @@ import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import android.app.Activity; -import android.content.Context; -import android.view.Display; -import android.view.WindowManager; -import androidx.camera.core.CameraInfo; -import androidx.camera.core.DisplayOrientedMeteringPointFactory; import androidx.camera.core.MeteringPoint; -import androidx.camera.core.MeteringPointFactory; -import io.flutter.plugin.common.BinaryMessenger; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.MockedStatic; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.mockito.stubbing.Answer; -import org.robolectric.RobolectricTestRunner; -import org.robolectric.annotation.Config; -@RunWith(RobolectricTestRunner.class) public class MeteringPointTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public BinaryMessenger mockBinaryMessenger; - @Mock public MeteringPoint meteringPoint; - - InstanceManager testInstanceManager; - - @Before - public void setUp() { - testInstanceManager = InstanceManager.create(identifier -> {}); - } - - @After - public void tearDown() { - testInstanceManager.stopFinalizationListener(); - } - - @Test - @Config(sdk = 30) - public void hostApiCreate_createsExpectedMeteringPointWithSizeSpecified_AboveAndroid30() { - final MeteringPointHostApiImpl.MeteringPointProxy proxySpy = - spy(new MeteringPointHostApiImpl.MeteringPointProxy()); - final MeteringPointHostApiImpl hostApi = - new MeteringPointHostApiImpl(testInstanceManager, proxySpy); - final Long meteringPointIdentifier = 78L; - final Float x = 0.25f; - final Float y = 0.18f; - final Float size = 0.6f; - final Float surfaceWidth = 1f; - final Float surfaceHeight = 1f; - final DisplayOrientedMeteringPointFactory mockDisplayOrientedMeteringPointFactory = - mock(DisplayOrientedMeteringPointFactory.class); - final Activity mockActivity = mock(Activity.class); - final Display mockDisplay = mock(Display.class); - final CameraInfo mockCameraInfo = mock(CameraInfo.class); - final long mockCameraInfoId = 55L; - - hostApi.setActivity(mockActivity); - testInstanceManager.addDartCreatedInstance(mockCameraInfo, mockCameraInfoId); - - when(mockActivity.getDisplay()).thenReturn(mockDisplay); - when(proxySpy.getDisplayOrientedMeteringPointFactory( - mockDisplay, mockCameraInfo, surfaceWidth, surfaceHeight)) - .thenReturn(mockDisplayOrientedMeteringPointFactory); - when(mockDisplayOrientedMeteringPointFactory.createPoint(x, y, size)).thenReturn(meteringPoint); - - hostApi.create( - meteringPointIdentifier, - x.doubleValue(), - y.doubleValue(), - size.doubleValue(), - mockCameraInfoId); - - verify(mockDisplayOrientedMeteringPointFactory).createPoint(x, y, size); - assertEquals(testInstanceManager.getInstance(meteringPointIdentifier), meteringPoint); - } - - @Test - @Config(sdk = 29) - @SuppressWarnings("deprecation") - public void hostApiCreate_createsExpectedMeteringPointWithSizeSpecified_BelowAndroid30() { - final MeteringPointHostApiImpl.MeteringPointProxy proxySpy = - spy(new MeteringPointHostApiImpl.MeteringPointProxy()); - final MeteringPointHostApiImpl hostApi = - new MeteringPointHostApiImpl(testInstanceManager, proxySpy); - final Long meteringPointIdentifier = 78L; - final Float x = 0.3f; - final Float y = 0.2f; - final Float size = 6f; - final Float surfaceWidth = 1f; - final Float surfaceHeight = 1f; - final DisplayOrientedMeteringPointFactory mockDisplayOrientedMeteringPointFactory = - mock(DisplayOrientedMeteringPointFactory.class); - final Activity mockActivity = mock(Activity.class); - final WindowManager mockWindowManager = mock(WindowManager.class); - final Display mockDisplay = mock(Display.class); - final CameraInfo mockCameraInfo = mock(CameraInfo.class); - final long mockCameraInfoId = 5L; - - hostApi.setActivity(mockActivity); - testInstanceManager.addDartCreatedInstance(mockCameraInfo, mockCameraInfoId); - - when(mockActivity.getSystemService(Context.WINDOW_SERVICE)).thenReturn(mockWindowManager); - when(mockWindowManager.getDefaultDisplay()).thenReturn(mockDisplay); - when(proxySpy.getDisplayOrientedMeteringPointFactory( - mockDisplay, mockCameraInfo, surfaceWidth, surfaceHeight)) - .thenReturn(mockDisplayOrientedMeteringPointFactory); - when(mockDisplayOrientedMeteringPointFactory.createPoint(x, y, size)).thenReturn(meteringPoint); - - hostApi.create( - meteringPointIdentifier, - x.doubleValue(), - y.doubleValue(), - size.doubleValue(), - mockCameraInfoId); - - verify(mockDisplayOrientedMeteringPointFactory).createPoint(x, y, size); - assertEquals(testInstanceManager.getInstance(meteringPointIdentifier), meteringPoint); - } - - @Test - @Config(sdk = 30) - public void hostApiCreate_createsExpectedMeteringPointWithoutSizeSpecified_AboveAndroid30() { - final MeteringPointHostApiImpl.MeteringPointProxy proxySpy = - spy(new MeteringPointHostApiImpl.MeteringPointProxy()); - final MeteringPointHostApiImpl hostApi = - new MeteringPointHostApiImpl(testInstanceManager, proxySpy); - final Long meteringPointIdentifier = 78L; - final Float x = 0.23f; - final Float y = 0.32f; - final Float surfaceWidth = 1f; - final Float surfaceHeight = 1f; - final DisplayOrientedMeteringPointFactory mockDisplayOrientedMeteringPointFactory = - mock(DisplayOrientedMeteringPointFactory.class); - final Activity mockActivity = mock(Activity.class); - final Display mockDisplay = mock(Display.class); - final CameraInfo mockCameraInfo = mock(CameraInfo.class); - final long mockCameraInfoId = 6L; - - hostApi.setActivity(mockActivity); - testInstanceManager.addDartCreatedInstance(mockCameraInfo, mockCameraInfoId); - - when(mockActivity.getDisplay()).thenReturn(mockDisplay); - when(proxySpy.getDisplayOrientedMeteringPointFactory( - mockDisplay, mockCameraInfo, surfaceWidth, surfaceHeight)) - .thenReturn(mockDisplayOrientedMeteringPointFactory); - when(mockDisplayOrientedMeteringPointFactory.createPoint(x, y)).thenReturn(meteringPoint); - - hostApi.create( - meteringPointIdentifier, x.doubleValue(), y.doubleValue(), null, mockCameraInfoId); - - verify(mockDisplayOrientedMeteringPointFactory).createPoint(x, y); - assertEquals(testInstanceManager.getInstance(meteringPointIdentifier), meteringPoint); - } - @Test - @Config(sdk = 29) - @SuppressWarnings("deprecation") - public void hostApiCreate_createsExpectedMeteringPointWithoutSizeSpecified_BelowAndroid30() { - final MeteringPointHostApiImpl.MeteringPointProxy proxySpy = - spy(new MeteringPointHostApiImpl.MeteringPointProxy()); - final MeteringPointHostApiImpl hostApi = - new MeteringPointHostApiImpl(testInstanceManager, proxySpy); - final Long meteringPointIdentifier = 78L; - final Float x = 0.1f; - final Float y = 0.8f; - final Float surfaceWidth = 1f; - final Float surfaceHeight = 1f; - final DisplayOrientedMeteringPointFactory mockDisplayOrientedMeteringPointFactory = - mock(DisplayOrientedMeteringPointFactory.class); - final Activity mockActivity = mock(Activity.class); - final WindowManager mockWindowManager = mock(WindowManager.class); - final Display mockDisplay = mock(Display.class); - final CameraInfo mockCameraInfo = mock(CameraInfo.class); - final long mockCameraInfoId = 7L; - - hostApi.setActivity(mockActivity); - testInstanceManager.addDartCreatedInstance(mockCameraInfo, mockCameraInfoId); - - when(mockActivity.getSystemService(Context.WINDOW_SERVICE)).thenReturn(mockWindowManager); - when(mockWindowManager.getDefaultDisplay()).thenReturn(mockDisplay); - when(proxySpy.getDisplayOrientedMeteringPointFactory( - mockDisplay, mockCameraInfo, surfaceWidth, surfaceHeight)) - .thenReturn(mockDisplayOrientedMeteringPointFactory); - when(mockDisplayOrientedMeteringPointFactory.createPoint(x, y)).thenReturn(meteringPoint); - - hostApi.create( - meteringPointIdentifier, x.doubleValue(), y.doubleValue(), null, mockCameraInfoId); - - verify(mockDisplayOrientedMeteringPointFactory).createPoint(x, y); - assertEquals(testInstanceManager.getInstance(meteringPointIdentifier), meteringPoint); - } - - @Test - public void getDefaultPointSize_returnsExpectedSize() { - try (MockedStatic mockedMeteringPointFactory = - Mockito.mockStatic(MeteringPointFactory.class)) { - final MeteringPointHostApiImpl meteringPointHostApiImpl = - new MeteringPointHostApiImpl(testInstanceManager); - final Long meteringPointIdentifier = 93L; - final Long index = 2L; - final Double defaultPointSize = 4D; - - testInstanceManager.addDartCreatedInstance(meteringPoint, meteringPointIdentifier); + public void getSize_returnsExpectedSize() { + final PigeonApiMeteringPoint api = new TestProxyApiRegistrar().getPigeonApiMeteringPoint(); - mockedMeteringPointFactory - .when(() -> MeteringPointFactory.getDefaultPointSize()) - .thenAnswer((Answer) invocation -> defaultPointSize.floatValue()); + final MeteringPoint instance = mock(MeteringPoint.class); + final double value = 1.0; + when(instance.getSize()).thenReturn((float) value); - assertEquals(meteringPointHostApiImpl.getDefaultPointSize(), defaultPointSize); - mockedMeteringPointFactory.verify(() -> MeteringPointFactory.getDefaultPointSize()); - } + assertEquals(value, api.getSize(instance), 0.1); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ObserverTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ObserverTest.java index dc45c8903ecb..b2140cf9e889 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ObserverTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ObserverTest.java @@ -4,129 +4,25 @@ package io.flutter.plugins.camerax; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import androidx.camera.core.CameraState; -import androidx.camera.core.ZoomState; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraStateType; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ObserverFlutterApi; -import java.util.Objects; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; public class ObserverTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public ObserverHostApiImpl.ObserverImpl mockObserver; - - @Mock public BinaryMessenger mockBinaryMessenger; - @Mock public ObserverFlutterApi mockFlutterApi; - @Mock public ObserverHostApiImpl.ObserverProxy mockProxy; - - InstanceManager instanceManager; - - @Before - public void setUp() { - instanceManager = InstanceManager.create(identifier -> {}); - } - - @After - public void tearDown() { - instanceManager.stopFinalizationListener(); - } - @Test - public void create_createsObserverInstance() { - final ObserverHostApiImpl hostApi = - new ObserverHostApiImpl(mockBinaryMessenger, instanceManager, mockProxy); - final long instanceIdentifier = 0; - - when(mockProxy.create(mockBinaryMessenger, instanceManager)) - .thenReturn(mockObserver); - - hostApi.create(instanceIdentifier); - - assertEquals(instanceManager.getInstance(instanceIdentifier), mockObserver); - } - - @Test - public void onChanged_makesExpectedCallToDartCallbackForCameraState() { - final ObserverFlutterApiWrapper flutterApi = - new ObserverFlutterApiWrapper(mockBinaryMessenger, instanceManager); - final ObserverHostApiImpl.ObserverImpl instance = - new ObserverHostApiImpl.ObserverImpl(mockBinaryMessenger, instanceManager); - final CameraStateFlutterApiWrapper mockCameraStateFlutterApiWrapper = - mock(CameraStateFlutterApiWrapper.class); - final long instanceIdentifier = 60; - final CameraState.StateError testCameraStateError = - CameraState.StateError.create(CameraState.ERROR_CAMERA_IN_USE); - final CameraState testCameraState = - CameraState.create(CameraState.Type.CLOSED, testCameraStateError); - final Long mockCameraStateIdentifier = instanceManager.addHostCreatedInstance(testCameraState); - - flutterApi.setApi(mockFlutterApi); - instance.setApi(flutterApi); - flutterApi.cameraStateFlutterApiWrapper = mockCameraStateFlutterApiWrapper; - - instanceManager.addDartCreatedInstance(instance, instanceIdentifier); - - instance.onChanged(testCameraState); - - verify(mockFlutterApi) - .onChanged( - eq(instanceIdentifier), eq(Objects.requireNonNull(mockCameraStateIdentifier)), any()); - verify(mockCameraStateFlutterApiWrapper) - .create(eq(testCameraState), eq(CameraStateType.CLOSED), eq(testCameraStateError), any()); - } - - @Test - public void onChanged_makesExpectedCallToDartCallbackForZoomState() { - final ObserverFlutterApiWrapper flutterApi = - new ObserverFlutterApiWrapper(mockBinaryMessenger, instanceManager); - final ObserverHostApiImpl.ObserverImpl instance = - new ObserverHostApiImpl.ObserverImpl(mockBinaryMessenger, instanceManager); - final long instanceIdentifier = 2; - final ZoomStateFlutterApiImpl mockZoomStateFlutterApiImpl = mock(ZoomStateFlutterApiImpl.class); - final ZoomState mockZoomState = mock(ZoomState.class); - final Long mockZoomStateIdentifier = instanceManager.addHostCreatedInstance(mockZoomState); - - flutterApi.setApi(mockFlutterApi); - instance.setApi(flutterApi); - flutterApi.zoomStateFlutterApiImpl = mockZoomStateFlutterApiImpl; - - instanceManager.addDartCreatedInstance(instance, instanceIdentifier); - - instance.onChanged(mockZoomState); - - verify(mockFlutterApi).onChanged(eq(instanceIdentifier), eq(mockZoomStateIdentifier), any()); - verify(mockZoomStateFlutterApiImpl).create(eq(mockZoomState), any()); - } - - @Test - public void onChanged_throwsExceptionForUnsupportedLiveDataType() { - final ObserverFlutterApiWrapper flutterApi = - new ObserverFlutterApiWrapper(mockBinaryMessenger, instanceManager); - final ObserverHostApiImpl.ObserverImpl instance = - new ObserverHostApiImpl.ObserverImpl(mockBinaryMessenger, instanceManager); - final long instanceIdentifier = 2; - - flutterApi.setApi(mockFlutterApi); - instance.setApi(flutterApi); + public void onChanged_makesExpectedCallToDartCallback() { + final ObserverProxyApi mockApi = mock(ObserverProxyApi.class); + when(mockApi.getPigeonRegistrar()).thenReturn(new TestProxyApiRegistrar()); - instanceManager.addDartCreatedInstance(instance, instanceIdentifier); + final ObserverProxyApi.ObserverImpl instance = + new ObserverProxyApi.ObserverImpl<>(mockApi); + final String value = "result"; + instance.onChanged(value); - assertThrows(UnsupportedOperationException.class, () -> instance.onChanged(mock(Object.class))); + verify(mockApi).onChanged(eq(instance), eq(value), any()); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/PendingRecordingTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/PendingRecordingTest.java index f25a17ed5d91..23e8279a7a4b 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/PendingRecordingTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/PendingRecordingTest.java @@ -5,131 +5,38 @@ package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import android.content.Context; import androidx.camera.video.PendingRecording; import androidx.camera.video.Recording; -import androidx.camera.video.VideoRecordEvent; -import io.flutter.plugin.common.BinaryMessenger; -import java.util.Objects; +import androidx.core.content.ContextCompat; import java.util.concurrent.Executor; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.robolectric.RobolectricTestRunner; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.stubbing.Answer; -@RunWith(RobolectricTestRunner.class) public class PendingRecordingTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public BinaryMessenger mockBinaryMessenger; - @Mock public PendingRecording mockPendingRecording; - @Mock public Recording mockRecording; - @Mock public RecordingFlutterApiImpl mockRecordingFlutterApi; - @Mock public Context mockContext; - @Mock public SystemServicesFlutterApiImpl mockSystemServicesFlutterApi; - @Mock public PendingRecordingFlutterApiImpl mockPendingRecordingFlutterApi; - @Mock public VideoRecordEvent.Finalize event; - @Mock public Throwable throwable; - - InstanceManager testInstanceManager; - - @Before - public void setUp() { - testInstanceManager = spy(InstanceManager.create(identifier -> {})); - } - - @After - public void tearDown() { - testInstanceManager.stopFinalizationListener(); - } - @Test - public void testStart() { - final Long mockPendingRecordingId = 3L; - final Long mockRecordingId = testInstanceManager.addHostCreatedInstance(mockRecording); - testInstanceManager.addDartCreatedInstance(mockPendingRecording, mockPendingRecordingId); + public void start_callsStartOnInstance() { + final PigeonApiPendingRecording api = + new TestProxyApiRegistrar().getPigeonApiPendingRecording(); - doReturn(mockRecording).when(mockPendingRecording).start(any(), any()); - doNothing().when(mockRecordingFlutterApi).create(any(Recording.class), any()); - PendingRecordingHostApiImpl spy = - spy(new PendingRecordingHostApiImpl(mockBinaryMessenger, testInstanceManager, mockContext)); - doReturn(mock(Executor.class)).when(spy).getExecutor(); - spy.recordingFlutterApi = mockRecordingFlutterApi; - assertEquals(spy.start(mockPendingRecordingId), mockRecordingId); - verify(mockRecordingFlutterApi).create(eq(mockRecording), any()); + final PendingRecording instance = mock(PendingRecording.class); + final VideoRecordEventListener listener = event -> {}; + final Recording value = mock(Recording.class); - testInstanceManager.remove(mockPendingRecordingId); - testInstanceManager.remove(mockRecordingId); - } - - @Test - public void testHandleVideoRecordEventSendsError() { - PendingRecordingHostApiImpl pendingRecordingHostApi = - new PendingRecordingHostApiImpl(mockBinaryMessenger, testInstanceManager, mockContext); - pendingRecordingHostApi.systemServicesFlutterApi = mockSystemServicesFlutterApi; - pendingRecordingHostApi.pendingRecordingFlutterApi = mockPendingRecordingFlutterApi; - final String eventMessage = "example failure message"; - - when(event.hasError()).thenReturn(true); - when(event.getCause()).thenReturn(throwable); - when(throwable.toString()).thenReturn(eventMessage); - doNothing().when(mockSystemServicesFlutterApi).sendCameraError(any(), any()); - - pendingRecordingHostApi.handleVideoRecordEvent(event); - - verify(mockPendingRecordingFlutterApi).sendVideoRecordingFinalizedEvent(any()); - verify(mockSystemServicesFlutterApi).sendCameraError(eq(eventMessage), any()); - } - - @Test - public void handleVideoRecordEvent_SendsVideoRecordingFinalizedEvent() { - PendingRecordingHostApiImpl pendingRecordingHostApi = - new PendingRecordingHostApiImpl(mockBinaryMessenger, testInstanceManager, mockContext); - pendingRecordingHostApi.pendingRecordingFlutterApi = mockPendingRecordingFlutterApi; - - when(event.hasError()).thenReturn(false); - - pendingRecordingHostApi.handleVideoRecordEvent(event); - - verify(mockPendingRecordingFlutterApi).sendVideoRecordingFinalizedEvent(any()); - } - - @Test - public void handleVideoRecordEvent_SendsVideoRecordingStartedEvent() { - PendingRecordingHostApiImpl pendingRecordingHostApi = - new PendingRecordingHostApiImpl(mockBinaryMessenger, testInstanceManager, mockContext); - pendingRecordingHostApi.pendingRecordingFlutterApi = mockPendingRecordingFlutterApi; - VideoRecordEvent.Start mockStartEvent = mock(VideoRecordEvent.Start.class); - - pendingRecordingHostApi.handleVideoRecordEvent(mockStartEvent); - - verify(mockPendingRecordingFlutterApi).sendVideoRecordingStartedEvent(any()); - } - - @Test - public void flutterApiCreateTest() { - final PendingRecordingFlutterApiImpl spyPendingRecordingFlutterApi = - spy(new PendingRecordingFlutterApiImpl(mockBinaryMessenger, testInstanceManager)); + try (MockedStatic mockedContextCompat = + Mockito.mockStatic(ContextCompat.class)) { + mockedContextCompat + .when(() -> ContextCompat.getMainExecutor(any())) + .thenAnswer((Answer) invocation -> mock(Executor.class)); - spyPendingRecordingFlutterApi.create(mockPendingRecording, reply -> {}); + when(instance.start(any(), any())).thenReturn(value); - final long identifier = - Objects.requireNonNull( - testInstanceManager.getIdentifierForStrongReference(mockPendingRecording)); - verify(spyPendingRecordingFlutterApi).create(eq(identifier), any()); + assertEquals(value, api.start(instance, listener)); + } } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/PlaneProxyTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/PlaneProxyTest.java index 643b63e3f93f..2abc3d7695b6 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/PlaneProxyTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/PlaneProxyTest.java @@ -4,55 +4,33 @@ package io.flutter.plugins.camerax; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.verify; - -import androidx.camera.core.ImageProxy; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.PlaneProxyFlutterApi; -import java.util.Objects; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import androidx.camera.core.ImageProxy.PlaneProxy; import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; public class PlaneProxyTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock public ImageProxy.PlaneProxy mockPlaneProxy; - @Mock public BinaryMessenger mockBinaryMessenger; - @Mock public PlaneProxyFlutterApi mockFlutterApi; + @Test + public void pixelStride_returnsExpectedPixelStride() { + final PigeonApiPlaneProxy api = new TestProxyApiRegistrar().getPigeonApiPlaneProxy(); - InstanceManager instanceManager; + final PlaneProxy instance = mock(PlaneProxy.class); + final long value = 0; + when(instance.getPixelStride()).thenReturn((int) value); - @Before - public void setUp() { - instanceManager = InstanceManager.create(identifier -> {}); - } - - @After - public void tearDown() { - instanceManager.stopFinalizationListener(); + assertEquals(value, api.pixelStride(instance)); } @Test - public void flutterApiCreate_makesCallToCreateInstanceWithExpectedIdentifier() { - final PlaneProxyFlutterApiImpl flutterApi = - new PlaneProxyFlutterApiImpl(mockBinaryMessenger, instanceManager); - final byte[] buffer = new byte[23]; - final long pixelStride = 20; - final long rowStride = 2; - - flutterApi.setApi(mockFlutterApi); + public void rowStride_returnsExpectedRowStride() { + final PigeonApiPlaneProxy api = new TestProxyApiRegistrar().getPigeonApiPlaneProxy(); - flutterApi.create(mockPlaneProxy, buffer, pixelStride, rowStride, reply -> {}); - final long instanceIdentifier = - Objects.requireNonNull(instanceManager.getIdentifierForStrongReference(mockPlaneProxy)); + final PlaneProxy instance = mock(PlaneProxy.class); + final long value = 0; + when(instance.getRowStride()).thenReturn((int) value); - verify(mockFlutterApi) - .create(eq(instanceIdentifier), eq(buffer), eq(pixelStride), eq(rowStride), any()); + assertEquals(value, api.rowStride(instance)); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/PreviewTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/PreviewTest.java index bc2577bc0072..a94f6f288adc 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/PreviewTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/PreviewTest.java @@ -5,113 +5,99 @@ package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.anyString; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import android.util.Size; import android.view.Surface; +import androidx.annotation.NonNull; import androidx.camera.core.Preview; +import androidx.camera.core.ResolutionInfo; import androidx.camera.core.SurfaceRequest; import androidx.camera.core.resolutionselector.ResolutionSelector; import androidx.core.util.Consumer; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ResolutionInfo; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.SystemServicesFlutterApi.Reply; import io.flutter.view.TextureRegistry; import java.util.concurrent.Executor; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; -import org.mockito.ArgumentMatchers; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class PreviewTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public Preview mockPreview; - @Mock public BinaryMessenger mockBinaryMessenger; - @Mock public TextureRegistry mockTextureRegistry; - @Mock public CameraXProxy mockCameraXProxy; - - InstanceManager testInstanceManager; + @Test + public void pigeon_defaultConstructor_createsPreviewWithCorrectConfiguration() { + final PigeonApiPreview api = new TestProxyApiRegistrar().getPigeonApiPreview(); - @Before - public void setUp() { - testInstanceManager = spy(InstanceManager.create(identifier -> {})); - } + final ResolutionSelector mockResolutionSelector = new ResolutionSelector.Builder().build(); + final long targetResolution = Surface.ROTATION_0; + final Preview instance = + api.pigeon_defaultConstructor(mockResolutionSelector, targetResolution); - @After - public void tearDown() { - testInstanceManager.stopFinalizationListener(); + assertEquals(instance.getResolutionSelector(), mockResolutionSelector); + assertEquals(instance.getTargetRotation(), Surface.ROTATION_0); } @Test - public void create_createsPreviewWithCorrectConfiguration() { - final PreviewHostApiImpl previewHostApi = - new PreviewHostApiImpl(mockBinaryMessenger, testInstanceManager, mockTextureRegistry); - final Preview.Builder mockPreviewBuilder = mock(Preview.Builder.class); - final int targetRotation = 90; - final Long previewIdentifier = 3L; - final ResolutionSelector mockResolutionSelector = mock(ResolutionSelector.class); - final long mockResolutionSelectorId = 90; - - previewHostApi.cameraXProxy = mockCameraXProxy; - testInstanceManager.addDartCreatedInstance(mockResolutionSelector, mockResolutionSelectorId); - when(mockCameraXProxy.createPreviewBuilder()).thenReturn(mockPreviewBuilder); - when(mockPreviewBuilder.build()).thenReturn(mockPreview); - - previewHostApi.create( - previewIdentifier, Long.valueOf(targetRotation), mockResolutionSelectorId); - - verify(mockPreviewBuilder).setTargetRotation(targetRotation); - verify(mockPreviewBuilder).setResolutionSelector(mockResolutionSelector); - verify(mockPreviewBuilder).build(); - verify(testInstanceManager).addDartCreatedInstance(mockPreview, previewIdentifier); + public void resolutionSelector_returnsExpectedResolutionSelector() { + final PigeonApiPreview api = new TestProxyApiRegistrar().getPigeonApiPreview(); + + final Preview instance = mock(Preview.class); + final androidx.camera.core.resolutionselector.ResolutionSelector value = + mock(ResolutionSelector.class); + when(instance.getResolutionSelector()).thenReturn(value); + + assertEquals(value, api.resolutionSelector(instance)); } @Test public void setSurfaceProvider_createsSurfaceProviderAndReturnsTextureEntryId() { - final PreviewHostApiImpl previewHostApi = - spy(new PreviewHostApiImpl(mockBinaryMessenger, testInstanceManager, mockTextureRegistry)); + final TextureRegistry mockTextureRegistry = mock(TextureRegistry.class); final TextureRegistry.SurfaceProducer mockSurfaceProducer = mock(TextureRegistry.SurfaceProducer.class); - final Long previewIdentifier = 5L; - final Long surfaceProducerEntryId = 120L; - - previewHostApi.cameraXProxy = mockCameraXProxy; - testInstanceManager.addDartCreatedInstance(mockPreview, previewIdentifier); - + final long textureId = 0; + when(mockSurfaceProducer.id()).thenReturn(textureId); when(mockTextureRegistry.createSurfaceProducer()).thenReturn(mockSurfaceProducer); - when(mockSurfaceProducer.id()).thenReturn(surfaceProducerEntryId); - - final ArgumentCaptor surfaceProviderCaptor = - ArgumentCaptor.forClass(Preview.SurfaceProvider.class); - - // Test that surface provider was set and the surface texture ID was returned. - assertEquals(previewHostApi.setSurfaceProvider(previewIdentifier), surfaceProducerEntryId); - verify(mockPreview).setSurfaceProvider(surfaceProviderCaptor.capture()); - verify(previewHostApi).createSurfaceProvider(mockSurfaceProducer); + final PigeonApiPreview api = + new TestProxyApiRegistrar() { + @NonNull + @Override + TextureRegistry getTextureRegistry() { + return mockTextureRegistry; + } + }.getPigeonApiPreview(); + + final Preview instance = mock(Preview.class); + final SystemServicesManager systemServicesManager = mock(SystemServicesManager.class); + + assertEquals(textureId, api.setSurfaceProvider(instance, systemServicesManager)); + verify(instance).setSurfaceProvider(any(Preview.SurfaceProvider.class)); } @Test public void createSurfaceProducer_setsExpectedSurfaceProducerCallback() { - final PreviewHostApiImpl previewHostApi = - new PreviewHostApiImpl(mockBinaryMessenger, testInstanceManager, mockTextureRegistry); + final TextureRegistry mockTextureRegistry = mock(TextureRegistry.class); final TextureRegistry.SurfaceProducer mockSurfaceProducer = mock(TextureRegistry.SurfaceProducer.class); + final long textureId = 0; + when(mockSurfaceProducer.id()).thenReturn(textureId); + when(mockTextureRegistry.createSurfaceProducer()).thenReturn(mockSurfaceProducer); + final PreviewProxyApi api = + (PreviewProxyApi) + new TestProxyApiRegistrar() { + @NonNull + @Override + TextureRegistry getTextureRegistry() { + return mockTextureRegistry; + } + }.getPigeonApiPreview(); + + final SystemServicesManager mockSystemServicesManager = mock(SystemServicesManager.class); final SurfaceRequest mockSurfaceRequest = mock(SurfaceRequest.class); final ArgumentCaptor callbackCaptor = ArgumentCaptor.forClass(TextureRegistry.SurfaceProducer.Callback.class); @@ -119,13 +105,13 @@ public void createSurfaceProducer_setsExpectedSurfaceProducerCallback() { when(mockSurfaceRequest.getResolution()).thenReturn(new Size(5, 6)); when(mockSurfaceProducer.getSurface()).thenReturn(mock(Surface.class)); - Preview.SurfaceProvider previewSurfaceProvider = - previewHostApi.createSurfaceProvider(mockSurfaceProducer); + final Preview.SurfaceProvider previewSurfaceProvider = + api.createSurfaceProvider(mockSurfaceProducer, mockSystemServicesManager); previewSurfaceProvider.onSurfaceRequested(mockSurfaceRequest); verify(mockSurfaceProducer).setCallback(callbackCaptor.capture()); - TextureRegistry.SurfaceProducer.Callback callback = callbackCaptor.getValue(); + final TextureRegistry.SurfaceProducer.Callback callback = callbackCaptor.getValue(); // Verify callback's onSurfaceDestroyed invalidates SurfaceRequest. simulateSurfaceDestruction(callback); @@ -138,35 +124,45 @@ public void createSurfaceProducer_setsExpectedSurfaceProducerCallback() { verifyNoMoreInteractions(mockSurfaceRequest); } + @SuppressWarnings("unchecked") @Test public void createSurfaceProvider_createsExpectedPreviewSurfaceProvider() { - final PreviewHostApiImpl previewHostApi = - new PreviewHostApiImpl(mockBinaryMessenger, testInstanceManager, mockTextureRegistry); + final TextureRegistry mockTextureRegistry = mock(TextureRegistry.class); final TextureRegistry.SurfaceProducer mockSurfaceProducer = mock(TextureRegistry.SurfaceProducer.class); + final long textureId = 0; + when(mockSurfaceProducer.id()).thenReturn(textureId); + when(mockTextureRegistry.createSurfaceProducer()).thenReturn(mockSurfaceProducer); + final PreviewProxyApi api = + (PreviewProxyApi) + new TestProxyApiRegistrar() { + @NonNull + @Override + TextureRegistry getTextureRegistry() { + return mockTextureRegistry; + } + }.getPigeonApiPreview(); + + final SystemServicesManager mockSystemServicesManager = mock(SystemServicesManager.class); + final Surface mockSurface = mock(Surface.class); final SurfaceRequest mockSurfaceRequest = mock(SurfaceRequest.class); final SurfaceRequest.Result mockSurfaceRequestResult = mock(SurfaceRequest.Result.class); - final SystemServicesFlutterApiImpl mockSystemServicesFlutterApi = - mock(SystemServicesFlutterApiImpl.class); + final int resolutionWidth = 200; final int resolutionHeight = 500; final Long surfaceProducerEntryId = 120L; - previewHostApi.cameraXProxy = mockCameraXProxy; when(mockSurfaceRequest.getResolution()) .thenReturn(new Size(resolutionWidth, resolutionHeight)); - when(mockCameraXProxy.createSystemServicesFlutterApiImpl(mockBinaryMessenger)) - .thenReturn(mockSystemServicesFlutterApi); when(mockSurfaceProducer.getSurface()).thenReturn(mockSurface); final ArgumentCaptor surfaceCaptor = ArgumentCaptor.forClass(Surface.class); - @SuppressWarnings("unchecked") final ArgumentCaptor> consumerCaptor = ArgumentCaptor.forClass(Consumer.class); - Preview.SurfaceProvider previewSurfaceProvider = - previewHostApi.createSurfaceProvider(mockSurfaceProducer); + final Preview.SurfaceProvider previewSurfaceProvider = + api.createSurfaceProvider(mockSurfaceProducer, mockSystemServicesManager); previewSurfaceProvider.onSurfaceRequested(mockSurfaceRequest); verify(mockSurfaceProducer).setSize(resolutionWidth, resolutionHeight); @@ -212,69 +208,78 @@ public void createSurfaceProvider_createsExpectedPreviewSurfaceProvider() { .thenReturn(SurfaceRequest.Result.RESULT_INVALID_SURFACE); capturedConsumer.accept(mockSurfaceRequestResult); verify(mockSurface).release(); - verify(mockSystemServicesFlutterApi) - .sendCameraError(anyString(), ArgumentMatchers.>any()); + verify(mockSystemServicesManager).onCameraError(anyString()); } @Test - public void releaseFlutterSurfaceTexture_makesCallToReleaseFlutterSurfaceTexture() { - final PreviewHostApiImpl previewHostApi = - new PreviewHostApiImpl(mockBinaryMessenger, testInstanceManager, mockTextureRegistry); + public void releaseSurfaceProvider_makesCallToReleaseFlutterSurfaceTexture() { + final TextureRegistry mockTextureRegistry = mock(TextureRegistry.class); final TextureRegistry.SurfaceProducer mockSurfaceProducer = mock(TextureRegistry.SurfaceProducer.class); + when(mockSurfaceProducer.id()).thenReturn(0L); + when(mockTextureRegistry.createSurfaceProducer()).thenReturn(mockSurfaceProducer); + final PigeonApiPreview api = + new TestProxyApiRegistrar() { + @NonNull + @Override + TextureRegistry getTextureRegistry() { + return mockTextureRegistry; + } + }.getPigeonApiPreview(); + + final Preview instance = mock(Preview.class); + final SystemServicesManager systemServicesManager = mock(SystemServicesManager.class); + api.setSurfaceProvider(instance, systemServicesManager); + api.releaseSurfaceProvider(instance); - previewHostApi.flutterSurfaceProducer = mockSurfaceProducer; - - previewHostApi.releaseFlutterSurfaceTexture(); verify(mockSurfaceProducer).release(); } @Test - public void getResolutionInfo_makesCallToRetrievePreviewResolutionInfo() { - final PreviewHostApiImpl previewHostApi = - new PreviewHostApiImpl(mockBinaryMessenger, testInstanceManager, mockTextureRegistry); - final androidx.camera.core.ResolutionInfo mockResolutionInfo = - mock(androidx.camera.core.ResolutionInfo.class); - final Long previewIdentifier = 23L; - final int resolutionWidth = 500; - final int resolutionHeight = 200; - - testInstanceManager.addDartCreatedInstance(mockPreview, previewIdentifier); - when(mockPreview.getResolutionInfo()).thenReturn(mockResolutionInfo); - when(mockResolutionInfo.getResolution()) - .thenReturn(new Size(resolutionWidth, resolutionHeight)); + public void getResolutionInfo_returnsExpectedResolutionInfo() { + final PigeonApiPreview api = new TestProxyApiRegistrar().getPigeonApiPreview(); - ResolutionInfo resolutionInfo = previewHostApi.getResolutionInfo(previewIdentifier); - assertEquals(resolutionInfo.getWidth(), Long.valueOf(resolutionWidth)); - assertEquals(resolutionInfo.getHeight(), Long.valueOf(resolutionHeight)); + final Preview instance = mock(Preview.class); + final androidx.camera.core.ResolutionInfo value = mock(ResolutionInfo.class); + when(instance.getResolutionInfo()).thenReturn(value); + + assertEquals(value, api.getResolutionInfo(instance)); } @Test - public void setTargetRotation_makesCallToSetTargetRotation() { - final PreviewHostApiImpl hostApi = - new PreviewHostApiImpl(mockBinaryMessenger, testInstanceManager, mockTextureRegistry); - final long instanceIdentifier = 52; - final int targetRotation = Surface.ROTATION_180; - - testInstanceManager.addDartCreatedInstance(mockPreview, instanceIdentifier); + public void setTargetRotation_returnsExpectedTargetRotation() { + final PigeonApiPreview api = new TestProxyApiRegistrar().getPigeonApiPreview(); - hostApi.setTargetRotation(instanceIdentifier, Long.valueOf(targetRotation)); + final Preview instance = mock(Preview.class); + final long rotation = 0; + api.setTargetRotation(instance, rotation); - verify(mockPreview).setTargetRotation(targetRotation); + verify(instance).setTargetRotation((int) rotation); } @Test public void surfaceProducerHandlesCropAndRotation_returnsIfSurfaceProducerHandlesCropAndRotation() { - final PreviewHostApiImpl hostApi = - new PreviewHostApiImpl(mockBinaryMessenger, testInstanceManager, mockTextureRegistry); + final TextureRegistry mockTextureRegistry = mock(TextureRegistry.class); final TextureRegistry.SurfaceProducer mockSurfaceProducer = mock(TextureRegistry.SurfaceProducer.class); - - hostApi.flutterSurfaceProducer = mockSurfaceProducer; - when(mockSurfaceProducer.handlesCropAndRotation()).thenReturn(true); - - assertEquals(hostApi.surfaceProducerHandlesCropAndRotation(), true); + when(mockSurfaceProducer.id()).thenReturn(0L); + when(mockTextureRegistry.createSurfaceProducer()).thenReturn(mockSurfaceProducer); + final PigeonApiPreview api = + new TestProxyApiRegistrar() { + @NonNull + @Override + TextureRegistry getTextureRegistry() { + return mockTextureRegistry; + } + }.getPigeonApiPreview(); + + final Preview instance = mock(Preview.class); + final SystemServicesManager systemServicesManager = mock(SystemServicesManager.class); + api.setSurfaceProvider(instance, systemServicesManager); + api.surfaceProducerHandlesCropAndRotation(instance); + + verify(mockSurfaceProducer).handlesCropAndRotation(); } // TODO(bparrishMines): Replace with inline calls to onSurfaceCleanup once available on stable; diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ProcessCameraProviderTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ProcessCameraProviderTest.java index f7987143b98e..0ae47bcdf3bb 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ProcessCameraProviderTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ProcessCameraProviderTest.java @@ -5,183 +5,143 @@ package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import android.content.Context; +import androidx.annotation.Nullable; import androidx.camera.core.Camera; import androidx.camera.core.CameraInfo; import androidx.camera.core.CameraSelector; import androidx.camera.core.UseCase; import androidx.camera.lifecycle.ProcessCameraProvider; +import androidx.core.content.ContextCompat; import androidx.lifecycle.LifecycleOwner; -import androidx.test.core.app.ApplicationProvider; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; -import io.flutter.plugin.common.BinaryMessenger; -import java.util.Arrays; -import java.util.Objects; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Executor; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; -import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; import org.mockito.stubbing.Answer; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class ProcessCameraProviderTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public ProcessCameraProvider processCameraProvider; - @Mock public BinaryMessenger mockBinaryMessenger; - - InstanceManager testInstanceManager; - private Context context; - - @Before - public void setUp() { - testInstanceManager = InstanceManager.create(identifier -> {}); - context = ApplicationProvider.getApplicationContext(); - } - - @After - public void tearDown() { - testInstanceManager.stopFinalizationListener(); - } - @Test - public void getInstanceTest() { - final ProcessCameraProviderHostApiImpl processCameraProviderHostApi = - new ProcessCameraProviderHostApiImpl(mockBinaryMessenger, testInstanceManager, context); - final ListenableFuture processCameraProviderFuture = - spy(Futures.immediateFuture(processCameraProvider)); - @SuppressWarnings("unchecked") - final GeneratedCameraXLibrary.Result mockResult = - mock(GeneratedCameraXLibrary.Result.class); + public void getInstance_returnsExpectedProcessCameraProviderInFutureCallback() { + final PigeonApiProcessCameraProvider api = + new TestProxyApiRegistrar().getPigeonApiProcessCameraProvider(); - testInstanceManager.addDartCreatedInstance(processCameraProvider, 0); + final ProcessCameraProvider instance = mock(ProcessCameraProvider.class); + final ListenableFuture processCameraProviderFuture = + spy(Futures.immediateFuture(instance)); try (MockedStatic mockedProcessCameraProvider = - Mockito.mockStatic(ProcessCameraProvider.class)) { + Mockito.mockStatic(ProcessCameraProvider.class); + MockedStatic mockedContextCompat = Mockito.mockStatic(ContextCompat.class)) { mockedProcessCameraProvider - .when(() -> ProcessCameraProvider.getInstance(context)) + .when(() -> ProcessCameraProvider.getInstance(any())) .thenAnswer( (Answer>) invocation -> processCameraProviderFuture); + mockedContextCompat + .when(() -> ContextCompat.getMainExecutor(any())) + .thenAnswer((Answer) invocation -> mock(Executor.class)); + final ArgumentCaptor runnableCaptor = ArgumentCaptor.forClass(Runnable.class); - processCameraProviderHostApi.getInstance(mockResult); + final ProcessCameraProvider[] resultArray = {null}; + api.getInstance( + ResultCompat.asCompatCallback( + reply -> { + resultArray[0] = reply.getOrNull(); + return null; + })); + verify(processCameraProviderFuture).addListener(runnableCaptor.capture(), any()); runnableCaptor.getValue().run(); - verify(mockResult).success(0L); + assertEquals(resultArray[0], instance); } } @Test - public void getAvailableCameraInfosTest() { - final ProcessCameraProviderHostApiImpl processCameraProviderHostApi = - new ProcessCameraProviderHostApiImpl(mockBinaryMessenger, testInstanceManager, context); - final CameraInfo mockCameraInfo = mock(CameraInfo.class); - - testInstanceManager.addDartCreatedInstance(processCameraProvider, 0); - testInstanceManager.addDartCreatedInstance(mockCameraInfo, 1); + public void getAvailableCameraInfos_returnsExpectedCameraInfos() { + final PigeonApiProcessCameraProvider api = + new TestProxyApiRegistrar().getPigeonApiProcessCameraProvider(); - when(processCameraProvider.getAvailableCameraInfos()).thenReturn(Arrays.asList(mockCameraInfo)); + final ProcessCameraProvider instance = mock(ProcessCameraProvider.class); + final List value = Collections.singletonList(mock(CameraInfo.class)); + when(instance.getAvailableCameraInfos()).thenReturn(value); - assertEquals(processCameraProviderHostApi.getAvailableCameraInfos(0L), Arrays.asList(1L)); - verify(processCameraProvider).getAvailableCameraInfos(); + assertEquals(value, api.getAvailableCameraInfos(instance)); } @Test - public void bindToLifecycleTest() { - final ProcessCameraProviderHostApiImpl processCameraProviderHostApi = - new ProcessCameraProviderHostApiImpl(mockBinaryMessenger, testInstanceManager, context); - final Camera mockCamera = mock(Camera.class); - final CameraSelector mockCameraSelector = mock(CameraSelector.class); - final UseCase mockUseCase = mock(UseCase.class); - UseCase[] mockUseCases = new UseCase[] {mockUseCase}; - - LifecycleOwner mockLifecycleOwner = mock(LifecycleOwner.class); - processCameraProviderHostApi.setLifecycleOwner(mockLifecycleOwner); - - testInstanceManager.addDartCreatedInstance(processCameraProvider, 0); - testInstanceManager.addDartCreatedInstance(mockCameraSelector, 1); - testInstanceManager.addDartCreatedInstance(mockUseCase, 2); - testInstanceManager.addDartCreatedInstance(mockCamera, 3); - - when(processCameraProvider.bindToLifecycle( - mockLifecycleOwner, mockCameraSelector, mockUseCases)) - .thenReturn(mockCamera); - - assertEquals( - processCameraProviderHostApi.bindToLifecycle(0L, 1L, Arrays.asList(2L)), Long.valueOf(3)); - verify(processCameraProvider) - .bindToLifecycle(mockLifecycleOwner, mockCameraSelector, mockUseCases); - } - - @Test - public void isBoundTest() { - final ProcessCameraProviderHostApiImpl processCameraProviderHostApiImpl = - new ProcessCameraProviderHostApiImpl(mockBinaryMessenger, testInstanceManager, context); - final UseCase mockUseCase = mock(UseCase.class); - - testInstanceManager.addDartCreatedInstance(processCameraProvider, 0); - testInstanceManager.addDartCreatedInstance(mockUseCase, 27); - - when(processCameraProvider.isBound(mockUseCase)).thenReturn(true); - - assertTrue(processCameraProviderHostApiImpl.isBound(0L, 27L)); - verify(processCameraProvider).isBound(mockUseCase); + public void bindToLifecycle_callsBindToLifecycleWithSelectorsAndUseCases() { + final PigeonApiProcessCameraProvider api = + new TestProxyApiRegistrar() { + @Nullable + @Override + public LifecycleOwner getLifecycleOwner() { + return mock(LifecycleOwner.class); + } + }.getPigeonApiProcessCameraProvider(); + + final ProcessCameraProvider instance = mock(ProcessCameraProvider.class); + final androidx.camera.core.CameraSelector cameraSelector = mock(CameraSelector.class); + final List useCases = + Collections.singletonList(mock(UseCase.class)); + final androidx.camera.core.Camera value = mock(Camera.class); + when(instance.bindToLifecycle( + any(), eq(cameraSelector), eq(useCases.toArray(new UseCase[] {})))) + .thenReturn(value); + + assertEquals(value, api.bindToLifecycle(instance, cameraSelector, useCases)); } @Test - public void unbindTest() { - final ProcessCameraProviderHostApiImpl processCameraProviderHostApi = - new ProcessCameraProviderHostApiImpl(mockBinaryMessenger, testInstanceManager, context); - final UseCase mockUseCase = mock(UseCase.class); - UseCase[] mockUseCases = new UseCase[] {mockUseCase}; + public void isBound_returnsExpectedIsBound() { + final PigeonApiProcessCameraProvider api = + new TestProxyApiRegistrar().getPigeonApiProcessCameraProvider(); - testInstanceManager.addDartCreatedInstance(processCameraProvider, 0); - testInstanceManager.addDartCreatedInstance(mockUseCase, 1); + final ProcessCameraProvider instance = mock(ProcessCameraProvider.class); + final androidx.camera.core.UseCase useCase = mock(UseCase.class); + final Boolean value = true; + when(instance.isBound(useCase)).thenReturn(value); - processCameraProviderHostApi.unbind(0L, Arrays.asList(1L)); - verify(processCameraProvider).unbind(mockUseCases); + assertEquals(value, api.isBound(instance, useCase)); } @Test - public void unbindAllTest() { - final ProcessCameraProviderHostApiImpl processCameraProviderHostApi = - new ProcessCameraProviderHostApiImpl(mockBinaryMessenger, testInstanceManager, context); + public void unbind_callsUnBindOnInstance() { + final PigeonApiProcessCameraProvider api = + new TestProxyApiRegistrar().getPigeonApiProcessCameraProvider(); - testInstanceManager.addDartCreatedInstance(processCameraProvider, 0); + final ProcessCameraProvider instance = mock(ProcessCameraProvider.class); + final List useCases = + Collections.singletonList(mock(UseCase.class)); + api.unbind(instance, useCases); - processCameraProviderHostApi.unbindAll(0L); - verify(processCameraProvider).unbindAll(); + verify(instance).unbind(useCases.toArray(new UseCase[] {})); } @Test - public void flutterApiCreateTest() { - final ProcessCameraProviderFlutterApiImpl spyFlutterApi = - spy(new ProcessCameraProviderFlutterApiImpl(mockBinaryMessenger, testInstanceManager)); + public void unbindAll() { + final PigeonApiProcessCameraProvider api = + new TestProxyApiRegistrar().getPigeonApiProcessCameraProvider(); - spyFlutterApi.create(processCameraProvider, reply -> {}); + final ProcessCameraProvider instance = mock(ProcessCameraProvider.class); + api.unbindAll(instance); - final long identifier = - Objects.requireNonNull( - testInstanceManager.getIdentifierForStrongReference(processCameraProvider)); - verify(spyFlutterApi).create(eq(identifier), any()); + verify(instance).unbindAll(); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/QualitySelectorTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/QualitySelectorTest.java index 83617a713d89..1c05fbe6304b 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/QualitySelectorTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/QualitySelectorTest.java @@ -6,144 +6,72 @@ import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockStatic; import android.util.Size; import androidx.camera.core.CameraInfo; import androidx.camera.video.FallbackStrategy; import androidx.camera.video.Quality; import androidx.camera.video.QualitySelector; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ResolutionInfo; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.VideoQuality; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.VideoQualityData; -import java.util.Arrays; -import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; +import java.util.Collections; import org.junit.Test; -import org.mockito.Mock; import org.mockito.MockedStatic; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; +import org.mockito.Mockito; import org.mockito.stubbing.Answer; public class QualitySelectorTest { - - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock public QualitySelector mockQualitySelectorWithoutFallbackStrategy; - @Mock public QualitySelector mockQualitySelectorWithFallbackStrategy; - - InstanceManager instanceManager; - - @Before - public void setUp() { - instanceManager = InstanceManager.create(identifier -> {}); - } - - @After - public void tearDown() { - instanceManager.stopFinalizationListener(); - } - @Test - public void hostApiCreate_createsExpectedQualitySelectorWhenOneQualitySpecified() { - final VideoQualityData expectedVideoQualityData = - new VideoQualityData.Builder().setQuality(VideoQuality.UHD).build(); - final List videoQualityDataList = Arrays.asList(expectedVideoQualityData); - final FallbackStrategy mockFallbackStrategy = mock(FallbackStrategy.class); - final long fallbackStrategyIdentifier = 9; - final QualitySelectorHostApiImpl hostApi = new QualitySelectorHostApiImpl(instanceManager); + public void from_createsExpectedQualitySelectorWhenOneQualitySpecified() { + final PigeonApiQualitySelector api = new TestProxyApiRegistrar().getPigeonApiQualitySelector(); - instanceManager.addDartCreatedInstance(mockFallbackStrategy, fallbackStrategyIdentifier); + final QualitySelector mockQualitySelector = mock(QualitySelector.class); + final FallbackStrategy fallbackStrategy = mock(FallbackStrategy.class); - try (MockedStatic mockedQualitySelector = mockStatic(QualitySelector.class)) { - mockedQualitySelector - .when(() -> QualitySelector.from(Quality.UHD)) - .thenAnswer( - (Answer) invocation -> mockQualitySelectorWithoutFallbackStrategy); + try (MockedStatic mockedQualitySelector = + Mockito.mockStatic(QualitySelector.class)) { mockedQualitySelector - .when(() -> QualitySelector.from(Quality.UHD, mockFallbackStrategy)) - .thenAnswer( - (Answer) invocation -> mockQualitySelectorWithFallbackStrategy); + .when(() -> QualitySelector.from(Quality.HD, fallbackStrategy)) + .thenAnswer((Answer) invocation -> mockQualitySelector); - // Test with no fallback strategy. - long instanceIdentifier = 0; - hostApi.create(instanceIdentifier, videoQualityDataList, null); - - assertEquals( - instanceManager.getInstance(instanceIdentifier), - mockQualitySelectorWithoutFallbackStrategy); - - // Test with fallback strategy. - instanceIdentifier = 1; - hostApi.create(instanceIdentifier, videoQualityDataList, fallbackStrategyIdentifier); - - assertEquals( - instanceManager.getInstance(instanceIdentifier), mockQualitySelectorWithFallbackStrategy); + assertEquals(api.from(VideoQuality.HD, fallbackStrategy), mockQualitySelector); } } @Test - public void hostApiCreate_createsExpectedQualitySelectorWhenOrderedListOfQualitiesSpecified() { - final List videoQualityDataList = - Arrays.asList( - new VideoQualityData.Builder().setQuality(VideoQuality.UHD).build(), - new VideoQualityData.Builder().setQuality(VideoQuality.HIGHEST).build()); - final List expectedVideoQualityList = Arrays.asList(Quality.UHD, Quality.HIGHEST); - final FallbackStrategy mockFallbackStrategy = mock(FallbackStrategy.class); - final long fallbackStrategyIdentifier = 9; - final QualitySelectorHostApiImpl hostApi = new QualitySelectorHostApiImpl(instanceManager); + public void fromOrderedList_createsExpectedQualitySelectorWhenOrderedListOfQualitiesSpecified() { + final PigeonApiQualitySelector api = new TestProxyApiRegistrar().getPigeonApiQualitySelector(); - instanceManager.addDartCreatedInstance(mockFallbackStrategy, fallbackStrategyIdentifier); + final QualitySelector mockQualitySelector = mock(QualitySelector.class); + final FallbackStrategy fallbackStrategy = mock(FallbackStrategy.class); - try (MockedStatic mockedQualitySelector = mockStatic(QualitySelector.class)) { - mockedQualitySelector - .when(() -> QualitySelector.fromOrderedList(expectedVideoQualityList)) - .thenAnswer( - (Answer) invocation -> mockQualitySelectorWithoutFallbackStrategy); + try (MockedStatic mockedQualitySelector = + Mockito.mockStatic(QualitySelector.class)) { mockedQualitySelector .when( - () -> QualitySelector.fromOrderedList(expectedVideoQualityList, mockFallbackStrategy)) - .thenAnswer( - (Answer) invocation -> mockQualitySelectorWithFallbackStrategy); - - // Test with no fallback strategy. - long instanceIdentifier = 0; - hostApi.create(instanceIdentifier, videoQualityDataList, null); + () -> + QualitySelector.fromOrderedList( + Collections.singletonList(Quality.SD), fallbackStrategy)) + .thenAnswer((Answer) invocation -> mockQualitySelector); assertEquals( - instanceManager.getInstance(instanceIdentifier), - mockQualitySelectorWithoutFallbackStrategy); - - // Test with fallback strategy. - instanceIdentifier = 1; - hostApi.create(instanceIdentifier, videoQualityDataList, fallbackStrategyIdentifier); - - assertEquals( - instanceManager.getInstance(instanceIdentifier), mockQualitySelectorWithFallbackStrategy); + api.fromOrderedList(Collections.singletonList(VideoQuality.SD), fallbackStrategy), + mockQualitySelector); } } @Test public void getResolution_returnsExpectedResolutionInfo() { - final CameraInfo mockCameraInfo = mock(CameraInfo.class); - final long cameraInfoIdentifier = 6; - final VideoQuality videoQuality = VideoQuality.FHD; - final Size sizeResult = new Size(30, 40); - final QualitySelectorHostApiImpl hostApi = new QualitySelectorHostApiImpl(instanceManager); + final PigeonApiQualitySelector api = new TestProxyApiRegistrar().getPigeonApiQualitySelector(); - instanceManager.addDartCreatedInstance(mockCameraInfo, cameraInfoIdentifier); + final CameraInfo cameraInfo = mock(CameraInfo.class); - try (MockedStatic mockedQualitySelector = mockStatic(QualitySelector.class)) { + try (MockedStatic mockedQualitySelector = + Mockito.mockStatic(QualitySelector.class)) { + final Size value = new Size(1, 2); mockedQualitySelector - .when(() -> QualitySelector.getResolution(mockCameraInfo, Quality.FHD)) - .thenAnswer((Answer) invocation -> sizeResult); - - final ResolutionInfo result = hostApi.getResolution(cameraInfoIdentifier, videoQuality); + .when(() -> QualitySelector.getResolution(cameraInfo, Quality.UHD)) + .thenAnswer((Answer) invocation -> value); - assertEquals(result.getWidth(), Long.valueOf(sizeResult.getWidth())); - assertEquals(result.getHeight(), Long.valueOf(sizeResult.getHeight())); + assertEquals(api.getResolution(cameraInfo, VideoQuality.UHD), value); } } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/RecorderTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/RecorderTest.java index a859e9d513ee..fad2c4257549 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/RecorderTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/RecorderTest.java @@ -5,174 +5,79 @@ package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.content.Context; import androidx.camera.video.FileOutputOptions; import androidx.camera.video.PendingRecording; +import androidx.camera.video.Quality; import androidx.camera.video.QualitySelector; import androidx.camera.video.Recorder; -import androidx.test.core.app.ApplicationProvider; -import io.flutter.plugin.common.BinaryMessenger; -import java.io.File; -import java.util.Objects; -import java.util.concurrent.Executor; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class RecorderTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public BinaryMessenger mockBinaryMessenger; - @Mock public Recorder mockRecorder; - private Context context; - - InstanceManager testInstanceManager; - - @Before - public void setUp() { - testInstanceManager = spy(InstanceManager.create(identifier -> {})); - context = ApplicationProvider.getApplicationContext(); - } - - @After - public void tearDown() { - testInstanceManager.stopFinalizationListener(); - } - @Test - public void create_createsExpectedRecorderInstance() { - final int recorderId = 0; - final int aspectRatio = 1; - final int bitRate = 2; - final int qualitySelectorId = 3; - - final RecorderHostApiImpl recorderHostApi = - new RecorderHostApiImpl(mockBinaryMessenger, testInstanceManager, context); - - final CameraXProxy mockCameraXProxy = mock(CameraXProxy.class); - final Recorder.Builder mockRecorderBuilder = mock(Recorder.Builder.class); - final QualitySelector mockQualitySelector = mock(QualitySelector.class); - recorderHostApi.cameraXProxy = mockCameraXProxy; - when(mockCameraXProxy.createRecorderBuilder()).thenReturn(mockRecorderBuilder); - when(mockRecorderBuilder.setAspectRatio(aspectRatio)).thenReturn(mockRecorderBuilder); - when(mockRecorderBuilder.setTargetVideoEncodingBitRate(bitRate)) - .thenReturn(mockRecorderBuilder); - when(mockRecorderBuilder.setExecutor(any(Executor.class))).thenReturn(mockRecorderBuilder); - when(mockRecorderBuilder.build()).thenReturn(mockRecorder); - testInstanceManager.addDartCreatedInstance( - mockQualitySelector, Long.valueOf(qualitySelectorId)); - - recorderHostApi.create( - Long.valueOf(recorderId), - Long.valueOf(aspectRatio), - Long.valueOf(bitRate), - Long.valueOf(qualitySelectorId)); - verify(mockCameraXProxy).createRecorderBuilder(); - verify(mockRecorderBuilder).setAspectRatio(aspectRatio); - verify(mockRecorderBuilder).setTargetVideoEncodingBitRate(bitRate); - verify(mockRecorderBuilder).setQualitySelector(mockQualitySelector); - verify(mockRecorderBuilder).build(); - assertEquals(testInstanceManager.getInstance(Long.valueOf(recorderId)), mockRecorder); - testInstanceManager.remove(Long.valueOf(recorderId)); + public void pigeon_defaultConstructor_createsExpectedRecorderInstance() { + final PigeonApiRecorder api = new TestProxyApiRegistrar().getPigeonApiRecorder(); + + final long aspectRatio = 5; + final long targetVideoEncodingBitRate = 7; + final QualitySelector qualitySelector = QualitySelector.from(Quality.HD); + final Recorder recorder = + api.pigeon_defaultConstructor(aspectRatio, targetVideoEncodingBitRate, qualitySelector); + + assertEquals(recorder.getAspectRatio(), aspectRatio); + assertEquals(recorder.getTargetVideoEncodingBitRate(), targetVideoEncodingBitRate); + assertEquals(recorder.getQualitySelector(), qualitySelector); } @Test - public void getAspectRatioTest() { - final int recorderId = 3; - final int aspectRatio = 6; - - when(mockRecorder.getAspectRatio()).thenReturn(aspectRatio); - testInstanceManager.addDartCreatedInstance(mockRecorder, Long.valueOf(recorderId)); - final RecorderHostApiImpl recorderHostApi = - new RecorderHostApiImpl(mockBinaryMessenger, testInstanceManager, context); - assertEquals( - recorderHostApi.getAspectRatio(Long.valueOf(recorderId)), Long.valueOf(aspectRatio)); - verify(mockRecorder).getAspectRatio(); - testInstanceManager.remove(Long.valueOf(recorderId)); - } + public void getAspectRatio_returnsExpectedAspectRatio() { + final PigeonApiRecorder api = new TestProxyApiRegistrar().getPigeonApiRecorder(); - @Test - public void getTargetVideoEncodingBitRateTest() { - final int bitRate = 7; - final int recorderId = 3; - - when(mockRecorder.getTargetVideoEncodingBitRate()).thenReturn(bitRate); - testInstanceManager.addDartCreatedInstance(mockRecorder, Long.valueOf(recorderId)); - final RecorderHostApiImpl recorderHostApi = - new RecorderHostApiImpl(mockBinaryMessenger, testInstanceManager, context); - assertEquals( - recorderHostApi.getTargetVideoEncodingBitRate(Long.valueOf(recorderId)), - Long.valueOf(bitRate)); - verify(mockRecorder).getTargetVideoEncodingBitRate(); - testInstanceManager.remove(Long.valueOf(recorderId)); + final Recorder instance = mock(Recorder.class); + final long value = 0; + when(instance.getAspectRatio()).thenReturn((int) value); + + assertEquals(value, api.getAspectRatio(instance)); } @Test - @SuppressWarnings("unchecked") - public void prepareRecording_returnsExpectedPendingRecording() { - final int recorderId = 3; + public void getTargetVideoEncodingBitRate_returnsExpectedBitRate() { + final PigeonApiRecorder api = new TestProxyApiRegistrar().getPigeonApiRecorder(); - PendingRecordingFlutterApiImpl mockPendingRecordingFlutterApi = - mock(PendingRecordingFlutterApiImpl.class); - PendingRecording mockPendingRecording = mock(PendingRecording.class); - testInstanceManager.addDartCreatedInstance(mockRecorder, Long.valueOf(recorderId)); - when(mockRecorder.prepareRecording(any(Context.class), any(FileOutputOptions.class))) - .thenReturn(mockPendingRecording); - doNothing().when(mockPendingRecordingFlutterApi).create(any(PendingRecording.class), any()); - Long mockPendingRecordingId = testInstanceManager.addHostCreatedInstance(mockPendingRecording); + final Recorder instance = mock(Recorder.class); + final long value = 0; + when(instance.getTargetVideoEncodingBitRate()).thenReturn((int) value); - RecorderHostApiImpl spy = - spy(new RecorderHostApiImpl(mockBinaryMessenger, testInstanceManager, context)); - spy.pendingRecordingFlutterApi = mockPendingRecordingFlutterApi; - doReturn(mock(File.class)).when(spy).openTempFile(any()); - spy.prepareRecording(Long.valueOf(recorderId), ""); - - testInstanceManager.remove(Long.valueOf(recorderId)); - testInstanceManager.remove(mockPendingRecordingId); + assertEquals(value, api.getTargetVideoEncodingBitRate(instance)); } @Test - @SuppressWarnings("unchecked") - public void prepareRecording_errorsWhenPassedNullPath() { - final int recorderId = 3; - - testInstanceManager.addDartCreatedInstance(mockRecorder, Long.valueOf(recorderId)); - RecorderHostApiImpl recorderHostApi = - new RecorderHostApiImpl(mockBinaryMessenger, testInstanceManager, context); - assertThrows( - RuntimeException.class, - () -> { - recorderHostApi.prepareRecording(Long.valueOf(recorderId), null); - }); - testInstanceManager.remove(Long.valueOf(recorderId)); + public void getQualitySelector_returnsExpectedQualitySelector() { + final PigeonApiRecorder api = new TestProxyApiRegistrar().getPigeonApiRecorder(); + + final Recorder instance = mock(Recorder.class); + final androidx.camera.video.QualitySelector value = mock(QualitySelector.class); + when(instance.getQualitySelector()).thenReturn(value); + + assertEquals(value, api.getQualitySelector(instance)); } @Test - public void flutterApiCreateTest() { - final RecorderFlutterApiImpl spyRecorderFlutterApi = - spy(new RecorderFlutterApiImpl(mockBinaryMessenger, testInstanceManager)); + public void prepareRecording_returnsExpectedPendingRecording() { + final PigeonApiRecorder api = new TestProxyApiRegistrar().getPigeonApiRecorder(); - spyRecorderFlutterApi.create(mockRecorder, null, null, reply -> {}); + final Recorder mockRecorder = mock(Recorder.class); + final PendingRecording mockPendingRecording = mock(PendingRecording.class); + when(mockRecorder.prepareRecording(any(Context.class), any(FileOutputOptions.class))) + .thenReturn(mockPendingRecording); - final long identifier = - Objects.requireNonNull(testInstanceManager.getIdentifierForStrongReference(mockRecorder)); - verify(spyRecorderFlutterApi).create(eq(identifier), eq(null), eq(null), any()); + assertEquals(mockPendingRecording, api.prepareRecording(mockRecorder, "myFile.mp4")); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/RecordingTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/RecordingTest.java index ca0c99649561..f143d8e1b9c6 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/RecordingTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/RecordingTest.java @@ -4,108 +4,50 @@ package io.flutter.plugins.camerax; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import androidx.camera.video.Recording; -import io.flutter.plugin.common.BinaryMessenger; -import java.util.Objects; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.robolectric.RobolectricTestRunner; -@RunWith(RobolectricTestRunner.class) public class RecordingTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public BinaryMessenger mockBinaryMessenger; - @Mock public Recording mockRecording; - - InstanceManager testInstanceManager; - - @Before - public void setUp() { - testInstanceManager = spy(InstanceManager.create(identifier -> {})); - } - - @After - public void tearDown() { - testInstanceManager.stopFinalizationListener(); - } - - @Test - public void close_getsRecordingFromInstanceManagerAndCloses() { - final RecordingHostApiImpl recordingHostApi = - new RecordingHostApiImpl(mockBinaryMessenger, testInstanceManager); - final Long recordingId = 5L; - - testInstanceManager.addDartCreatedInstance(mockRecording, recordingId); - - recordingHostApi.close(recordingId); - - verify(mockRecording).close(); - testInstanceManager.remove(recordingId); - } - @Test - public void stop_getsRecordingFromInstanceManagerAndStops() { - final RecordingHostApiImpl recordingHostApi = - new RecordingHostApiImpl(mockBinaryMessenger, testInstanceManager); - final Long recordingId = 5L; - - testInstanceManager.addDartCreatedInstance(mockRecording, recordingId); + public void close_callsCloseOnInstance() { + final PigeonApiRecording api = new TestProxyApiRegistrar().getPigeonApiRecording(); - recordingHostApi.stop(recordingId); + final Recording instance = mock(Recording.class); + api.close(instance); - verify(mockRecording).stop(); - testInstanceManager.remove(recordingId); + verify(instance).close(); } @Test - public void resume_getsRecordingFromInstanceManagerAndResumes() { - final RecordingHostApiImpl recordingHostApi = - new RecordingHostApiImpl(mockBinaryMessenger, testInstanceManager); - final Long recordingId = 5L; + public void pause_callsPauseOnInstance() { + final PigeonApiRecording api = new TestProxyApiRegistrar().getPigeonApiRecording(); - testInstanceManager.addDartCreatedInstance(mockRecording, recordingId); + final Recording instance = mock(Recording.class); + api.pause(instance); - recordingHostApi.resume(recordingId); - - verify(mockRecording).resume(); - testInstanceManager.remove(recordingId); + verify(instance).pause(); } @Test - public void pause_getsRecordingFromInstanceManagerAndPauses() { - final RecordingHostApiImpl recordingHostApi = - new RecordingHostApiImpl(mockBinaryMessenger, testInstanceManager); - final Long recordingId = 5L; - - testInstanceManager.addDartCreatedInstance(mockRecording, recordingId); + public void resume_callsResumeOnInstance() { + final PigeonApiRecording api = new TestProxyApiRegistrar().getPigeonApiRecording(); - recordingHostApi.pause(recordingId); + final Recording instance = mock(Recording.class); + api.resume(instance); - verify(mockRecording).pause(); - testInstanceManager.remove(recordingId); + verify(instance).resume(); } @Test - public void flutterApiCreateTest() { - final RecordingFlutterApiImpl spyRecordingFlutterApi = - spy(new RecordingFlutterApiImpl(mockBinaryMessenger, testInstanceManager)); + public void stop_callsStopOnInstance() { + final PigeonApiRecording api = new TestProxyApiRegistrar().getPigeonApiRecording(); - spyRecordingFlutterApi.create(mockRecording, reply -> {}); + final Recording instance = mock(Recording.class); + api.stop(instance); - final long identifier = - Objects.requireNonNull(testInstanceManager.getIdentifierForStrongReference(mockRecording)); - verify(spyRecordingFlutterApi).create(eq(identifier), any()); + verify(instance).stop(); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ResolutionFilterTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ResolutionFilterTest.java index 150f5676739a..d3440eec64ba 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ResolutionFilterTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ResolutionFilterTest.java @@ -8,57 +8,29 @@ import android.util.Size; import androidx.camera.core.resolutionselector.ResolutionFilter; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.ResolutionInfo; import java.util.ArrayList; import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; -import org.robolectric.RobolectricTestRunner; -@RunWith(RobolectricTestRunner.class) public class ResolutionFilterTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - InstanceManager instanceManager; - - @Before - public void setUp() { - instanceManager = InstanceManager.create(identifier -> {}); - } - - @After - public void tearDown() { - instanceManager.stopFinalizationListener(); - } - @Test - public void hostApiCreateWithOnePreferredSize_createsExpectedResolutionFilterInstance() { - final ResolutionFilterHostApiImpl hostApi = new ResolutionFilterHostApiImpl(instanceManager); - final long instanceIdentifier = 50; - final long preferredResolutionWidth = 20; - final long preferredResolutionHeight = 80; - final ResolutionInfo preferredResolution = - new ResolutionInfo.Builder() - .setWidth(preferredResolutionWidth) - .setHeight(preferredResolutionHeight) - .build(); + public void createWithOnePreferredSize_createsExpectedResolutionFilterInstance() { + final PigeonApiResolutionFilter api = + new TestProxyApiRegistrar().getPigeonApiResolutionFilter(); - hostApi.createWithOnePreferredSize(instanceIdentifier, preferredResolution); + final int preferredResolutionWidth = 20; + final int preferredResolutionHeight = 80; + final ResolutionFilter resolutionFilter = + api.createWithOnePreferredSize( + new Size(preferredResolutionWidth, preferredResolutionHeight)); // Test that instance filters supported resolutions as expected. - final ResolutionFilter resolutionFilter = instanceManager.getInstance(instanceIdentifier); final Size fakeSupportedSize1 = new Size(720, 480); final Size fakeSupportedSize2 = new Size(20, 80); final Size fakeSupportedSize3 = new Size(2, 8); - final Size preferredSize = - new Size((int) preferredResolutionWidth, (int) preferredResolutionHeight); + final Size preferredSize = new Size(preferredResolutionWidth, preferredResolutionHeight); - final ArrayList fakeSupportedSizes = new ArrayList(); + final ArrayList fakeSupportedSizes = new ArrayList<>(); fakeSupportedSizes.add(fakeSupportedSize1); fakeSupportedSizes.add(fakeSupportedSize2); fakeSupportedSizes.add(preferredSize); diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ResolutionInfoTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ResolutionInfoTest.java new file mode 100644 index 000000000000..4dba9b3486ea --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ResolutionInfoTest.java @@ -0,0 +1,26 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import android.util.Size; +import androidx.camera.core.ResolutionInfo; +import org.junit.Test; + +public class ResolutionInfoTest { + @Test + public void resolution_returnsExpectedResolution() { + final PigeonApiResolutionInfo api = new TestProxyApiRegistrar().getPigeonApiResolutionInfo(); + + final ResolutionInfo instance = mock(ResolutionInfo.class); + final Size value = mock(Size.class); + when(instance.getResolution()).thenReturn(value); + + assertEquals(value, api.resolution(instance)); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ResolutionSelectorTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ResolutionSelectorTest.java index 0f45f07b4f7a..725d9d28e1f2 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ResolutionSelectorTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ResolutionSelectorTest.java @@ -12,57 +12,65 @@ import androidx.camera.core.resolutionselector.ResolutionFilter; import androidx.camera.core.resolutionselector.ResolutionSelector; import androidx.camera.core.resolutionselector.ResolutionStrategy; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; +@RunWith(RobolectricTestRunner.class) public class ResolutionSelectorTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock public ResolutionSelector mockResolutionSelector; - @Mock public ResolutionSelectorHostApiImpl.ResolutionSelectorProxy mockProxy; + @Test + public void pigeon_defaultConstructor_createsExpectedResolutionSelectorInstance() { + final PigeonApiResolutionSelector api = + new TestProxyApiRegistrar().getPigeonApiResolutionSelector(); + + final ResolutionFilter resolutionFilter = mock(ResolutionFilter.class); + final ResolutionStrategy resolutionStrategy = mock(ResolutionStrategy.class); + final AspectRatioStrategy aspectRatioStrategy = mock(AspectRatioStrategy.class); + + final ResolutionSelector instance = + api.pigeon_defaultConstructor(resolutionFilter, resolutionStrategy, aspectRatioStrategy); + + assertEquals(instance.getResolutionFilter(), resolutionFilter); + assertEquals(instance.getResolutionStrategy(), resolutionStrategy); + assertEquals(instance.getAspectRatioStrategy(), aspectRatioStrategy); + } + + @Test + public void resolutionFilter_returnsExpectedResolutionFilter() { + final PigeonApiResolutionSelector api = + new TestProxyApiRegistrar().getPigeonApiResolutionSelector(); - InstanceManager instanceManager; + final ResolutionSelector instance = mock(ResolutionSelector.class); + final androidx.camera.core.resolutionselector.ResolutionFilter value = + mock(ResolutionFilter.class); + when(instance.getResolutionFilter()).thenReturn(value); - @Before - public void setUp() { - instanceManager = InstanceManager.create(identifier -> {}); + assertEquals(value, api.resolutionFilter(instance)); } - @After - public void tearDown() { - instanceManager.stopFinalizationListener(); + @Test + public void resolutionStrategy_returnsExpectedResolutionStrategy() { + final PigeonApiResolutionSelector api = + new TestProxyApiRegistrar().getPigeonApiResolutionSelector(); + + final ResolutionSelector instance = mock(ResolutionSelector.class); + final androidx.camera.core.resolutionselector.ResolutionStrategy value = + mock(ResolutionStrategy.class); + when(instance.getResolutionStrategy()).thenReturn(value); + + assertEquals(value, api.resolutionStrategy(instance)); } @Test - public void hostApiCreate_createsExpectedResolutionSelectorInstance() { - final ResolutionStrategy mockResolutionStrategy = mock(ResolutionStrategy.class); - final long resolutionStrategyIdentifier = 14; - instanceManager.addDartCreatedInstance(mockResolutionStrategy, resolutionStrategyIdentifier); - - final AspectRatioStrategy mockAspectRatioStrategy = mock(AspectRatioStrategy.class); - final long aspectRatioStrategyIdentifier = 15; - instanceManager.addDartCreatedInstance(mockAspectRatioStrategy, aspectRatioStrategyIdentifier); - - final ResolutionFilter mockResolutionFilter = mock(ResolutionFilter.class); - final long resolutionFilterIdentifier = 33; - instanceManager.addDartCreatedInstance(mockResolutionFilter, resolutionFilterIdentifier); - - when(mockProxy.create(mockResolutionStrategy, mockAspectRatioStrategy, mockResolutionFilter)) - .thenReturn(mockResolutionSelector); - final ResolutionSelectorHostApiImpl hostApi = - new ResolutionSelectorHostApiImpl(instanceManager, mockProxy); - - final long instanceIdentifier = 0; - hostApi.create( - instanceIdentifier, - resolutionStrategyIdentifier, - resolutionFilterIdentifier, - aspectRatioStrategyIdentifier); - - assertEquals(instanceManager.getInstance(instanceIdentifier), mockResolutionSelector); + public void getAspectRatioStrategy() { + final PigeonApiResolutionSelector api = + new TestProxyApiRegistrar().getPigeonApiResolutionSelector(); + + final ResolutionSelector instance = mock(ResolutionSelector.class); + final androidx.camera.core.resolutionselector.AspectRatioStrategy value = + mock(AspectRatioStrategy.class); + when(instance.getAspectRatioStrategy()).thenReturn(value); + + assertEquals(value, api.getAspectRatioStrategy(instance)); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ResolutionStrategyTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ResolutionStrategyTest.java index 7bbc6152da0c..650744c17232 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ResolutionStrategyTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ResolutionStrategyTest.java @@ -5,67 +5,55 @@ package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import android.util.Size; import androidx.camera.core.resolutionselector.ResolutionStrategy; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; +@RunWith(RobolectricTestRunner.class) public class ResolutionStrategyTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Mock public ResolutionStrategy mockResolutionStrategy; - @Mock public ResolutionStrategyHostApiImpl.ResolutionStrategyProxy mockProxy; - - InstanceManager instanceManager; - - @Before - public void setUp() { - instanceManager = InstanceManager.create(identifier -> {}); - } - - @After - public void tearDown() { - instanceManager.stopFinalizationListener(); + @Test + public void + pigeon_defaultConstructor_createsExpectedResolutionStrategyInstanceWhenArgumentsValid() { + final PigeonApiResolutionStrategy api = + new TestProxyApiRegistrar().getPigeonApiResolutionStrategy(); + + final Size size = new Size(1, 2); + final ResolutionStrategy resolutionStrategy = + api.pigeon_defaultConstructor(size, ResolutionStrategyFallbackRule.CLOSEST_HIGHER); + + assertEquals(resolutionStrategy.getBoundSize(), size); + assertEquals( + resolutionStrategy.getFallbackRule(), ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER); } @Test - public void hostApiCreate_createsExpectedResolutionStrategyInstanceWhenArgumentsValid() { - final GeneratedCameraXLibrary.ResolutionInfo boundSize = - new GeneratedCameraXLibrary.ResolutionInfo.Builder().setWidth(50L).setHeight(30L).build(); - - final Long fallbackRule = 0L; - - when(mockProxy.create(any(Size.class), eq(fallbackRule))).thenReturn(mockResolutionStrategy); - - final ResolutionStrategyHostApiImpl hostApi = - new ResolutionStrategyHostApiImpl(instanceManager, mockProxy); + public void getBoundSize_returnsExpectedSize() { + final PigeonApiResolutionStrategy api = + new TestProxyApiRegistrar().getPigeonApiResolutionStrategy(); - final long instanceIdentifier = 0; - hostApi.create(instanceIdentifier, boundSize, fallbackRule); + final ResolutionStrategy instance = mock(ResolutionStrategy.class); + final Size value = mock(Size.class); + when(instance.getBoundSize()).thenReturn(value); - assertEquals(instanceManager.getInstance(instanceIdentifier), mockResolutionStrategy); + assertEquals(value, api.getBoundSize(instance)); } @Test - public void hostApiCreate_throwsAssertionErrorWhenArgumentsInvalid() { - final Long fallbackRule = 8L; - final long instanceIdentifier = 0; + public void getFallbackRule_returnsExpectedFallbackRule() { + final PigeonApiResolutionStrategy api = + new TestProxyApiRegistrar().getPigeonApiResolutionStrategy(); - final ResolutionStrategyHostApiImpl hostApi = - new ResolutionStrategyHostApiImpl(instanceManager, mockProxy); + final ResolutionStrategy instance = mock(ResolutionStrategy.class); + ; + when(instance.getFallbackRule()) + .thenReturn(ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER); - // We expect an exception to be thrown if fallback rule is specified but bound size is not. - assertThrows( - IllegalArgumentException.class, - () -> hostApi.create(instanceIdentifier, null, fallbackRule)); + assertEquals( + ResolutionStrategyFallbackRule.CLOSEST_HIGHER_THEN_LOWER, api.getFallbackRule(instance)); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/SystemServicesTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/SystemServicesTest.java index fdfc1b224ffa..3a1b39675971 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/SystemServicesTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/SystemServicesTest.java @@ -5,64 +5,75 @@ package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThrows; -import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; -import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.app.Activity; import android.content.Context; -import io.flutter.plugin.common.BinaryMessenger; -import io.flutter.plugins.camerax.CameraPermissionsManager.PermissionsRegistry; -import io.flutter.plugins.camerax.CameraPermissionsManager.ResultCallback; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.CameraPermissionsErrorData; -import io.flutter.plugins.camerax.GeneratedCameraXLibrary.Result; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import java.io.File; import java.io.IOException; -import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; -import org.mockito.Mock; import org.mockito.MockedStatic; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class SystemServicesTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public BinaryMessenger mockBinaryMessenger; - @Mock public InstanceManager mockInstanceManager; - @Mock public Context mockContext; - @Test public void requestCameraPermissionsTest() { - final SystemServicesHostApiImpl systemServicesHostApi = - new SystemServicesHostApiImpl(mockBinaryMessenger, mockInstanceManager, mockContext); - final CameraXProxy mockCameraXProxy = mock(CameraXProxy.class); + final Activity mockActivity = mock(Activity.class); + final CameraPermissionsManager.PermissionsRegistry mockPermissionsRegistry = + mock(CameraPermissionsManager.PermissionsRegistry.class); final CameraPermissionsManager mockCameraPermissionsManager = mock(CameraPermissionsManager.class); - final Activity mockActivity = mock(Activity.class); - final PermissionsRegistry mockPermissionsRegistry = mock(PermissionsRegistry.class); - @SuppressWarnings("unchecked") - final Result mockResult = mock(Result.class); + final TestProxyApiRegistrar proxyApiRegistrar = + new TestProxyApiRegistrar() { + @NonNull + @Override + public Context getContext() { + return mockActivity; + } + + @Nullable + @Override + CameraPermissionsManager.PermissionsRegistry getPermissionsRegistry() { + return mockPermissionsRegistry; + } + + @NonNull + @Override + public CameraPermissionsManager getCameraPermissionsManager() { + return mockCameraPermissionsManager; + } + }; + final SystemServicesManagerProxyApi api = proxyApiRegistrar.getPigeonApiSystemServicesManager(); + + final SystemServicesManager instance = + new SystemServicesManagerProxyApi.SystemServicesManagerImpl( + proxyApiRegistrar.getPigeonApiSystemServicesManager()); final Boolean enableAudio = false; - systemServicesHostApi.cameraXProxy = mockCameraXProxy; - systemServicesHostApi.setActivity(mockActivity); - systemServicesHostApi.setPermissionsRegistry(mockPermissionsRegistry); - when(mockCameraXProxy.createCameraPermissionsManager()) - .thenReturn(mockCameraPermissionsManager); + final CameraPermissionsError[] result = {null}; + api.requestCameraPermissions( + instance, + enableAudio, + ResultCompat.asCompatCallback( + reply -> { + result[0] = reply.getOrNull(); + return null; + })); - final ArgumentCaptor resultCallbackCaptor = - ArgumentCaptor.forClass(ResultCallback.class); - - systemServicesHostApi.requestCameraPermissions(enableAudio, mockResult); + final ArgumentCaptor resultCallbackCaptor = + ArgumentCaptor.forClass(CameraPermissionsManager.ResultCallback.class); // Test camera permissions are requested. verify(mockCameraPermissionsManager) @@ -72,33 +83,39 @@ public void requestCameraPermissionsTest() { eq(enableAudio), resultCallbackCaptor.capture()); - ResultCallback resultCallback = resultCallbackCaptor.getValue(); + CameraPermissionsManager.ResultCallback resultCallback = resultCallbackCaptor.getValue(); // Test no error data is sent upon permissions request success. - resultCallback.onResult(null, null); - verify(mockResult).success(null); + resultCallback.onResult(null); + assertNull(result[0]); // Test expected error data is sent upon permissions request failure. final String testErrorCode = "TestErrorCode"; final String testErrorDescription = "Test error description."; - final ArgumentCaptor cameraPermissionsErrorDataCaptor = - ArgumentCaptor.forClass(CameraPermissionsErrorData.class); - - resultCallback.onResult(testErrorCode, testErrorDescription); - verify(mockResult, times(2)).success(cameraPermissionsErrorDataCaptor.capture()); + final ArgumentCaptor + cameraPermissionsErrorDataCaptor = + ArgumentCaptor.forClass(GeneratedCameraXLibrary.CameraPermissionsErrorData.class); - CameraPermissionsErrorData cameraPermissionsErrorData = - cameraPermissionsErrorDataCaptor.getValue(); - assertEquals(cameraPermissionsErrorData.getErrorCode(), testErrorCode); - assertEquals(cameraPermissionsErrorData.getDescription(), testErrorDescription); + resultCallback.onResult(new CameraPermissionsError(testErrorCode, testErrorDescription)); + assertEquals(result[0], new CameraPermissionsError(testErrorCode, testErrorDescription)); } @Test public void getTempFilePath_returnsCorrectPath() { - final SystemServicesHostApiImpl systemServicesHostApi = - new SystemServicesHostApiImpl(mockBinaryMessenger, mockInstanceManager, mockContext); - + final Context mockContext = mock(Context.class); + final TestProxyApiRegistrar proxyApiRegistrar = + new TestProxyApiRegistrar() { + @NonNull + @Override + public Context getContext() { + return mockContext; + } + }; + final SystemServicesManagerProxyApi api = proxyApiRegistrar.getPigeonApiSystemServicesManager(); + + final SystemServicesManager instance = + new SystemServicesManagerProxyApi.SystemServicesManagerImpl(api); final String prefix = "prefix"; final String suffix = ".suffix"; final MockedStatic mockedStaticFile = mockStatic(File.class); @@ -108,16 +125,28 @@ public void getTempFilePath_returnsCorrectPath() { mockedStaticFile .when(() -> File.createTempFile(prefix, suffix, mockOutputDir)) .thenReturn(mockFile); + when(mockFile.toString()).thenReturn(prefix + suffix); - assertEquals(systemServicesHostApi.getTempFilePath(prefix, suffix), prefix + suffix); + assertEquals(api.getTempFilePath(instance, prefix, suffix), prefix + suffix); mockedStaticFile.close(); } @Test public void getTempFilePath_throwsRuntimeExceptionOnIOException() { - final SystemServicesHostApiImpl systemServicesHostApi = - new SystemServicesHostApiImpl(mockBinaryMessenger, mockInstanceManager, mockContext); + final Context mockContext = mock(Context.class); + final TestProxyApiRegistrar proxyApiRegistrar = + new TestProxyApiRegistrar() { + @NonNull + @Override + public Context getContext() { + return mockContext; + } + }; + final SystemServicesManagerProxyApi api = proxyApiRegistrar.getPigeonApiSystemServicesManager(); + + final SystemServicesManager instance = + new SystemServicesManagerProxyApi.SystemServicesManagerImpl(api); final String prefix = "prefix"; final String suffix = ".suffix"; @@ -127,10 +156,21 @@ public void getTempFilePath_throwsRuntimeExceptionOnIOException() { mockedStaticFile .when(() -> File.createTempFile(prefix, suffix, mockOutputDir)) .thenThrow(IOException.class); - assertThrows( - GeneratedCameraXLibrary.FlutterError.class, - () -> systemServicesHostApi.getTempFilePath(prefix, suffix)); + assertThrows(RuntimeException.class, () -> api.getTempFilePath(instance, prefix, suffix)); mockedStaticFile.close(); } + + @Test + public void onCameraError() { + final SystemServicesManagerProxyApi mockApi = mock(SystemServicesManagerProxyApi.class); + when(mockApi.getPigeonRegistrar()).thenReturn(new TestProxyApiRegistrar()); + + final SystemServicesManager instance = + new SystemServicesManagerProxyApi.SystemServicesManagerImpl(mockApi); + final String errorDescription = "myString"; + instance.onCameraError(errorDescription); + + verify(mockApi).onCameraError(eq(instance), eq(errorDescription), any()); + } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/TestProxyApiRegistrar.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/TestProxyApiRegistrar.java new file mode 100644 index 000000000000..956d4bcf72c2 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/TestProxyApiRegistrar.java @@ -0,0 +1,32 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import static org.mockito.Mockito.mock; + +import android.content.Context; +import io.flutter.plugin.common.BinaryMessenger; +import io.flutter.view.TextureRegistry; +import org.checkerframework.checker.nullness.qual.NonNull; + +/** + * Test implementation of `ProxyApiRegistrar` that provides mocks, instantly runs callbacks instead + * of posting them, and makes all SDK checks pass by default. + */ +public class TestProxyApiRegistrar extends ProxyApiRegistrar { + public TestProxyApiRegistrar() { + super(mock(BinaryMessenger.class), mock(Context.class), mock(TextureRegistry.class)); + } + + @Override + void runOnMainThread(@NonNull FlutterMethodRunnable runnable) { + runnable.run(); + } + + @Override + boolean sdkIsAtLeast(int version) { + return true; + } +} diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/VideoCaptureTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/VideoCaptureTest.java index 32627fbd6245..960ad4dc83fa 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/VideoCaptureTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/VideoCaptureTest.java @@ -5,103 +5,60 @@ package io.flutter.plugins.camerax; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; -import android.view.Surface; -import androidx.camera.video.Recorder; import androidx.camera.video.VideoCapture; -import io.flutter.plugin.common.BinaryMessenger; -import java.util.Objects; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; +import androidx.camera.video.VideoOutput; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.stubbing.Answer; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class VideoCaptureTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public BinaryMessenger mockBinaryMessenger; - @Mock public Recorder mockRecorder; - @Mock public VideoCaptureFlutterApiImpl mockVideoCaptureFlutterApi; - @Mock public VideoCapture mockVideoCapture; + @SuppressWarnings({"unchecked", "rawtypes"}) + @Test + public void withOutput_createsVideoCaptureWithVideoOutput() { + final PigeonApiVideoCapture api = new TestProxyApiRegistrar().getPigeonApiVideoCapture(); - InstanceManager testInstanceManager; + final VideoCapture instance = mock(VideoCapture.class); + final VideoOutput videoOutput = mock(VideoOutput.class); - @Before - public void setUp() { - testInstanceManager = spy(InstanceManager.create(identifier -> {})); - } + try (MockedStatic mockedCamera2CameraInfo = + Mockito.mockStatic(VideoCapture.class)) { + mockedCamera2CameraInfo + .when(() -> VideoCapture.withOutput(videoOutput)) + .thenAnswer((Answer) invocation -> instance); - @After - public void tearDown() { - testInstanceManager.stopFinalizationListener(); + assertEquals(api.withOutput(videoOutput), instance); + } } + @SuppressWarnings("unchecked") @Test public void getOutput_returnsAssociatedRecorder() { - final Long recorderId = 5L; - final Long videoCaptureId = 6L; - VideoCapture videoCapture = VideoCapture.withOutput(mockRecorder); + final PigeonApiVideoCapture api = new TestProxyApiRegistrar().getPigeonApiVideoCapture(); - testInstanceManager.addDartCreatedInstance(mockRecorder, recorderId); - testInstanceManager.addDartCreatedInstance(videoCapture, videoCaptureId); + final VideoCapture instance = mock(VideoCapture.class); + final VideoOutput value = mock(VideoOutput.class); + when(instance.getOutput()).thenReturn(value); - VideoCaptureHostApiImpl videoCaptureHostApi = - new VideoCaptureHostApiImpl(mockBinaryMessenger, testInstanceManager); - assertEquals(videoCaptureHostApi.getOutput(videoCaptureId), recorderId); - testInstanceManager.remove(recorderId); - testInstanceManager.remove(videoCaptureId); + assertEquals(value, api.getOutput(instance)); } - @Test @SuppressWarnings("unchecked") - public void withOutput_returnsNewVideoCaptureWithAssociatedRecorder() { - final Long recorderId = 5L; - testInstanceManager.addDartCreatedInstance(mockRecorder, recorderId); - - VideoCaptureHostApiImpl videoCaptureHostApi = - new VideoCaptureHostApiImpl(mockBinaryMessenger, testInstanceManager); - VideoCaptureHostApiImpl spyVideoCaptureApi = spy(videoCaptureHostApi); - final Long videoCaptureId = videoCaptureHostApi.withOutput(recorderId); - VideoCapture videoCapture = testInstanceManager.getInstance(videoCaptureId); - assertEquals(videoCapture.getOutput(), mockRecorder); - - testInstanceManager.remove(recorderId); - testInstanceManager.remove(videoCaptureId); - } - @Test public void setTargetRotation_makesCallToSetTargetRotation() { - final VideoCaptureHostApiImpl hostApi = - new VideoCaptureHostApiImpl(mockBinaryMessenger, testInstanceManager); - final long instanceIdentifier = 62; - final int targetRotation = Surface.ROTATION_270; - - testInstanceManager.addDartCreatedInstance(mockVideoCapture, instanceIdentifier); - - hostApi.setTargetRotation(instanceIdentifier, Long.valueOf(targetRotation)); + final PigeonApiVideoCapture api = new TestProxyApiRegistrar().getPigeonApiVideoCapture(); - verify(mockVideoCapture).setTargetRotation(targetRotation); - } - - @Test - public void flutterApiCreateTest() { - final VideoCaptureFlutterApiImpl spyVideoCaptureFlutterApi = - spy(new VideoCaptureFlutterApiImpl(mockBinaryMessenger, testInstanceManager)); - spyVideoCaptureFlutterApi.create(mockVideoCapture, reply -> {}); + final VideoCapture instance = mock(VideoCapture.class); + final long rotation = 0; + api.setTargetRotation(instance, rotation); - final long identifier = - Objects.requireNonNull( - testInstanceManager.getIdentifierForStrongReference(mockVideoCapture)); - verify(spyVideoCaptureFlutterApi).create(eq(identifier), any()); + verify(instance).setTargetRotation((int) rotation); } } diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/VideoRecordEventListenerTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/VideoRecordEventListenerTest.java new file mode 100644 index 000000000000..525ea796e718 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/VideoRecordEventListenerTest.java @@ -0,0 +1,40 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package io.flutter.plugins.camerax; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import androidx.camera.video.VideoRecordEvent; +import org.junit.Test; + +public class VideoRecordEventListenerTest { + @Test + public void pigeon_defaultConstructor_createsExpectedVideoRecordEvent() { + final PigeonApiVideoRecordEventListener api = + new TestProxyApiRegistrar().getPigeonApiVideoRecordEventListener(); + + assertTrue( + api.pigeon_defaultConstructor() + instanceof VideoRecordEventListenerProxyApi.VideoRecordEventListenerImpl); + } + + @Test + public void onEvent_makesCallToDartCallback() { + final VideoRecordEventListenerProxyApi mockApi = mock(VideoRecordEventListenerProxyApi.class); + when(mockApi.getPigeonRegistrar()).thenReturn(new TestProxyApiRegistrar()); + + final VideoRecordEventListenerProxyApi.VideoRecordEventListenerImpl instance = + new VideoRecordEventListenerProxyApi.VideoRecordEventListenerImpl(mockApi); + final androidx.camera.video.VideoRecordEvent event = mock(VideoRecordEvent.class); + instance.onEvent(event); + + verify(mockApi).onEvent(eq(instance), eq(event), any()); + } +} diff --git a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ZoomStateTest.java b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ZoomStateTest.java index a4f53ad80c5d..2338759edd6c 100644 --- a/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ZoomStateTest.java +++ b/packages/camera/camera_android_camerax/android/src/test/java/io/flutter/plugins/camerax/ZoomStateTest.java @@ -4,60 +4,33 @@ package io.flutter.plugins.camerax; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import androidx.camera.core.ZoomState; -import io.flutter.plugin.common.BinaryMessenger; -import java.util.Objects; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnit; -import org.mockito.junit.MockitoRule; public class ZoomStateTest { - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - - @Mock public BinaryMessenger mockBinaryMessenger; - @Mock public ZoomState mockZoomState; - - InstanceManager testInstanceManager; + @Test + public void minZoomRatio_returnsExpectedMinZoomRatio() { + final PigeonApiZoomState api = new TestProxyApiRegistrar().getPigeonApiZoomState(); - @Before - public void setUp() { - testInstanceManager = InstanceManager.create(identifier -> {}); - } + final ZoomState instance = mock(ZoomState.class); + final double value = 1.0; + when(instance.getMinZoomRatio()).thenReturn((float) value); - @After - public void tearDown() { - testInstanceManager.stopFinalizationListener(); + assertEquals(value, api.minZoomRatio(instance), 0.1); } @Test - public void create_makesExpectedCallToCreateInstanceOnDartSide() { - ZoomStateFlutterApiImpl zoomStateFlutterApiImpl = - spy(new ZoomStateFlutterApiImpl(mockBinaryMessenger, testInstanceManager)); - final Float testMinZoomRatio = 0F; - final Float testMaxZoomRatio = 1F; - - when(mockZoomState.getMinZoomRatio()).thenReturn(testMinZoomRatio); - when(mockZoomState.getMaxZoomRatio()).thenReturn(testMaxZoomRatio); - - zoomStateFlutterApiImpl.create(mockZoomState, reply -> {}); - - final long identifier = - Objects.requireNonNull(testInstanceManager.getIdentifierForStrongReference(mockZoomState)); - verify(zoomStateFlutterApiImpl) - .create( - eq(identifier), - eq(testMinZoomRatio.doubleValue()), - eq(testMaxZoomRatio.doubleValue()), - any()); + public void maxZoomRatio_returnsExpectedMaxZoomRatio() { + final PigeonApiZoomState api = new TestProxyApiRegistrar().getPigeonApiZoomState(); + + final ZoomState instance = mock(ZoomState.class); + final double value = 1.0; + when(instance.getMaxZoomRatio()).thenReturn((float) value); + + assertEquals(value, api.maxZoomRatio(instance), 0.1); } } diff --git a/packages/camera/camera_android_camerax/example/android/app/build.gradle b/packages/camera/camera_android_camerax/example/android/app/build.gradle index a5331be7303b..ff29b2f9982a 100644 --- a/packages/camera/camera_android_camerax/example/android/app/build.gradle +++ b/packages/camera/camera_android_camerax/example/android/app/build.gradle @@ -32,6 +32,11 @@ android { targetCompatibility JavaVersion.VERSION_11 } + kotlinOptions { + // This must match the Java version provided in compileOptions. + jvmTarget = '11' + } + defaultConfig { applicationId "io.flutter.plugins.cameraxexample" minSdkVersion flutter.minSdkVersion diff --git a/packages/camera/camera_android_camerax/example/android/app/src/androidTest/java/io/flutter/plugins/cameraxexample/InstanceManagerTest.java b/packages/camera/camera_android_camerax/example/android/app/src/androidTest/java/io/flutter/plugins/cameraxexample/InstanceManagerTest.java deleted file mode 100644 index fe15629b6d72..000000000000 --- a/packages/camera/camera_android_camerax/example/android/app/src/androidTest/java/io/flutter/plugins/cameraxexample/InstanceManagerTest.java +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.cameraxexample; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; - -import androidx.test.ext.junit.runners.AndroidJUnit4; -import io.flutter.plugins.camerax.InstanceManager; -import org.junit.Test; -import org.junit.runner.RunWith; - -@RunWith(AndroidJUnit4.class) -public class InstanceManagerTest { - @Test - public void managerDoesNotTriggerFinalizationListenerWhenStopped() throws InterruptedException { - final boolean[] callbackTriggered = {false}; - final InstanceManager instanceManager = - InstanceManager.create(identifier -> callbackTriggered[0] = true); - instanceManager.stopFinalizationListener(); - - Object object = new Object(); - instanceManager.addDartCreatedInstance(object, 0); - - assertEquals(object, instanceManager.remove(0)); - - // To allow for object to be garbage collected. - //noinspection UnusedAssignment - object = null; - - Runtime.getRuntime().gc(); - - // Wait for the interval after finalized callbacks are made for garbage collected objects. - // See InstanceManager.CLEAR_FINALIZED_WEAK_REFERENCES_INTERVAL. - Thread.sleep(30000); - - assertNull(instanceManager.getInstance(0)); - assertFalse(callbackTriggered[0]); - } -} diff --git a/packages/camera/camera_android_camerax/example/lib/main.dart b/packages/camera/camera_android_camerax/example/lib/main.dart index 9eee18c45738..bb8e6af20bd7 100644 --- a/packages/camera/camera_android_camerax/example/lib/main.dart +++ b/packages/camera/camera_android_camerax/example/lib/main.dart @@ -435,7 +435,8 @@ class _CameraExampleHomeState extends State min: _minAvailableExposureOffset, max: _maxAvailableExposureOffset, label: _currentExposureOffset.toString(), - onChanged: _minAvailableExposureOffset == + onChanged: (_) {}, + onChangeEnd: _minAvailableExposureOffset == _maxAvailableExposureOffset ? null : setExposureOffset, diff --git a/packages/camera/camera_android_camerax/lib/src/analyzer.dart b/packages/camera/camera_android_camerax/lib/src/analyzer.dart deleted file mode 100644 index 8da367f00468..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/analyzer.dart +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'dart:async'; - -import 'package:flutter/services.dart' show BinaryMessenger; -import 'package:meta/meta.dart' show immutable, protected; - -import 'android_camera_camerax_flutter_api_impls.dart'; -import 'camerax_library.g.dart'; -import 'image_proxy.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; - -/// Wrapper of callback for analyzing images. -/// -/// See https://developer.android.com/reference/androidx/camera/core/ImageAnalysis.Analyzer. -@immutable -class Analyzer extends JavaObject { - /// Creates an [Analyzer]. - Analyzer( - {BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - required this.analyze}) - : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = _AnalyzerHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - _api.createfromInstances(this); - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - } - - /// Constructs a [Analyzer] that is not automatically attached to a native object. - Analyzer.detached( - {BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - required this.analyze}) - : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = _AnalyzerHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - } - - late final _AnalyzerHostApiImpl _api; - - /// Analyzes an image to produce a result. - final Future Function(ImageProxy imageProxy) analyze; -} - -/// Host API implementation of [Analyzer]. -class _AnalyzerHostApiImpl extends AnalyzerHostApi { - _AnalyzerHostApiImpl({ - this.binaryMessenger, - InstanceManager? instanceManager, - }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager, - super(binaryMessenger: binaryMessenger); - - final BinaryMessenger? binaryMessenger; - - final InstanceManager instanceManager; - - /// Creates an [Analyzer] instance on the native side. - Future createfromInstances( - Analyzer instance, - ) { - return create( - instanceManager.addDartCreatedInstance( - instance, - onCopy: (Analyzer original) => Analyzer.detached( - analyze: original.analyze, - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ), - ), - ); - } -} - -/// Flutter API implementation for [Analyzer]. -/// -/// This class may handle instantiating and adding Dart instances that are -/// attached to a native instance or receiving callback methods from an -/// overridden native class. -@protected -class AnalyzerFlutterApiImpl implements AnalyzerFlutterApi { - /// Constructs a [AnalyzerFlutterApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - AnalyzerFlutterApiImpl({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - }) : _binaryMessenger = binaryMessenger, - _instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - - /// Receives binary data across the Flutter platform barrier. - final BinaryMessenger? _binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager _instanceManager; - - @override - void create( - int identifier, - ) { - _instanceManager.addHostCreatedInstance( - Analyzer.detached( - analyze: (ImageProxy imageProxy) async {}, - binaryMessenger: _binaryMessenger, - instanceManager: _instanceManager, - ), - identifier, - onCopy: (Analyzer original) => Analyzer.detached( - analyze: original.analyze, - binaryMessenger: _binaryMessenger, - instanceManager: _instanceManager, - ), - ); - } - - @override - void analyze( - int identifier, - int imageProxyIdentifier, - ) { - final Analyzer instance = - _instanceManager.getInstanceWithWeakReference(identifier)!; - final ImageProxy imageProxy = - _instanceManager.getInstanceWithWeakReference(imageProxyIdentifier)!; - instance.analyze( - imageProxy, - ); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/android_camera_camerax.dart b/packages/camera/camera_android_camerax/lib/src/android_camera_camerax.dart index a35ed56188fb..8f9454cfcc96 100644 --- a/packages/camera/camera_android_camerax/lib/src/android_camera_camerax.dart +++ b/packages/camera/camera_android_camerax/lib/src/android_camera_camerax.dart @@ -9,50 +9,11 @@ import 'package:async/async.dart'; import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:flutter/services.dart' show DeviceOrientation, PlatformException; -import 'package:flutter/widgets.dart' - show Size, Texture, Widget, visibleForTesting; +import 'package:flutter/widgets.dart' show Texture, Widget, visibleForTesting; import 'package:stream_transform/stream_transform.dart'; - -import 'analyzer.dart'; -import 'aspect_ratio_strategy.dart'; -import 'camera.dart'; -import 'camera2_camera_control.dart'; -import 'camera2_camera_info.dart'; -import 'camera_control.dart'; -import 'camera_info.dart'; -import 'camera_metadata.dart'; -import 'camera_selector.dart'; -import 'camera_state.dart'; -import 'camerax_library.g.dart'; +import 'camerax_library.dart'; import 'camerax_proxy.dart'; -import 'capture_request_options.dart'; -import 'device_orientation_manager.dart'; -import 'exposure_state.dart'; -import 'fallback_strategy.dart'; -import 'focus_metering_action.dart'; -import 'focus_metering_result.dart'; -import 'image_analysis.dart'; -import 'image_capture.dart'; -import 'image_proxy.dart'; -import 'live_data.dart'; -import 'metering_point.dart'; -import 'observer.dart'; -import 'pending_recording.dart'; -import 'plane_proxy.dart'; -import 'preview.dart'; -import 'process_camera_provider.dart'; -import 'quality_selector.dart'; -import 'recorder.dart'; -import 'recording.dart'; -import 'resolution_filter.dart'; -import 'resolution_selector.dart'; -import 'resolution_strategy.dart'; import 'rotated_preview.dart'; -import 'surface.dart'; -import 'system_services.dart'; -import 'use_case.dart'; -import 'video_capture.dart'; -import 'zoom_state.dart'; /// The Android implementation of [CameraPlatform] that uses the CameraX library. class AndroidCameraCameraX extends CameraPlatform { @@ -114,11 +75,54 @@ class AndroidCameraCameraX extends CameraPlatform { @visibleForTesting String? videoOutputPath; + /// Handles access to system resources. + late final SystemServicesManager systemServicesManager = + proxy.newSystemServicesManager( + onCameraError: (_, String errorDescription) { + cameraErrorStreamController.add(errorDescription); + }, + ); + + /// Handles retrieving media orientation for a device. + late final DeviceOrientationManager deviceOrientationManager = + proxy.newDeviceOrientationManager( + onDeviceOrientationChanged: (_, String orientation) { + final DeviceOrientation deviceOrientation = + _deserializeDeviceOrientation(orientation); + deviceOrientationChangedStreamController.add( + DeviceOrientationChangedEvent(deviceOrientation), + ); + }, + ); + + /// Stream that emits an event when the corresponding video recording is finalized. + static final StreamController + videoRecordingEventStreamController = + StreamController.broadcast(); + + /// Stream that emits the errors caused by camera usage on the native side. + static final StreamController cameraErrorStreamController = + StreamController.broadcast(); + + /// Stream that emits the device orientation whenever it is changed. + /// + /// Values may start being added to the stream once + /// `startListeningForDeviceOrientationChange(...)` is called. + static final StreamController + deviceOrientationChangedStreamController = + StreamController.broadcast(); + /// Stream queue to pick up finalized viceo recording events in /// [stopVideoRecording]. final StreamQueue videoRecordingEventStreamQueue = - StreamQueue( - PendingRecording.videoRecordingEventStreamController.stream); + StreamQueue(videoRecordingEventStreamController.stream); + + late final VideoRecordEventListener _videoRecordingEventListener = + proxy.newVideoRecordEventListener( + onEvent: (_, VideoRecordEvent event) { + videoRecordingEventStreamController.add(event); + }, + ); /// Whether or not [preview] has been bound to the lifecycle of the camera by /// [createCamera]. @@ -136,7 +140,7 @@ class AndroidCameraCameraX extends CameraPlatform { ImageCapture? imageCapture; /// The flash mode currently configured for [imageCapture]. - int? _currentFlashMode; + CameraXFlashMode? _currentFlashMode; /// Whether or not torch flash mode has been enabled for the [camera]. @visibleForTesting @@ -255,11 +259,13 @@ class AndroidCameraCameraX extends CameraPlatform { /// Returns list of all available cameras and their descriptions. @override Future> availableCameras() async { + proxy.setUpGenericsProxy(); + final List cameraDescriptions = []; - processCameraProvider ??= await proxy.getProcessCameraProvider(); + processCameraProvider ??= await proxy.getInstanceProcessCameraProvider(); final List cameraInfos = - await processCameraProvider!.getAvailableCameraInfos(); + (await processCameraProvider!.getAvailableCameraInfos()).cast(); CameraLensDirection? cameraLensDirection; int cameraCount = 0; @@ -270,12 +276,12 @@ class AndroidCameraCameraX extends CameraPlatform { // Determine the lens direction by filtering the CameraInfo // TODO(gmackall): replace this with call to CameraInfo.getLensFacing when changes containing that method are available if ((await proxy - .createCameraSelector(CameraSelector.lensFacingBack) + .newCameraSelector(requireLensFacing: LensFacing.back) .filter([cameraInfo])) .isNotEmpty) { cameraLensDirection = CameraLensDirection.back; } else if ((await proxy - .createCameraSelector(CameraSelector.lensFacingFront) + .newCameraSelector(requireLensFacing: LensFacing.front) .filter([cameraInfo])) .isNotEmpty) { cameraLensDirection = CameraLensDirection.front; @@ -284,16 +290,19 @@ class AndroidCameraCameraX extends CameraPlatform { continue; } - cameraSensorOrientation = await cameraInfo.getSensorRotationDegrees(); + cameraSensorOrientation = cameraInfo.sensorRotationDegrees; cameraName = 'Camera $cameraCount'; cameraCount++; // TODO(camsim99): Use camera ID retrieved from Camera2CameraInfo as // camera name: https://github.com/flutter/flutter/issues/147545. - cameraDescriptions.add(CameraDescription( + cameraDescriptions.add( + CameraDescription( name: cameraName, lensDirection: cameraLensDirection, - sensorOrientation: cameraSensorOrientation)); + sensorOrientation: cameraSensorOrientation, + ), + ); } return cameraDescriptions; @@ -309,9 +318,10 @@ class AndroidCameraCameraX extends CameraPlatform { bool enableAudio = false, }) => createCameraWithSettings( - description, - MediaSettings( - resolutionPreset: resolutionPreset, enableAudio: enableAudio)); + description, + MediaSettings( + resolutionPreset: resolutionPreset, enableAudio: enableAudio), + ); /// Creates an uninitialized camera instance and returns the camera ID. /// @@ -334,18 +344,26 @@ class AndroidCameraCameraX extends CameraPlatform { CameraDescription cameraDescription, MediaSettings? mediaSettings, ) async { - // Must obtain proper permissions before attempting to access a camera. - await proxy.requestCameraPermissions(mediaSettings?.enableAudio ?? false); + final CameraPermissionsError? error = + await systemServicesManager.requestCameraPermissions( + mediaSettings?.enableAudio ?? false, + ); + + if (error != null) { + throw CameraException(error.errorCode, error.description); + } // Save CameraSelector that matches cameraDescription. - final int cameraSelectorLensDirection = + final LensFacing cameraSelectorLensDirection = _getCameraSelectorLensDirection(cameraDescription.lensDirection); - cameraIsFrontFacing = - cameraSelectorLensDirection == CameraSelector.lensFacingFront; - cameraSelector = proxy.createCameraSelector(cameraSelectorLensDirection); + cameraIsFrontFacing = cameraSelectorLensDirection == LensFacing.front; + cameraSelector = proxy.newCameraSelector( + requireLensFacing: cameraSelectorLensDirection, + ); // Start listening for device orientation changes preceding camera creation. - proxy.startListeningForDeviceOrientationChange( - cameraIsFrontFacing, cameraDescription.sensorOrientation); + unawaited( + deviceOrientationManager.startListeningForDeviceOrientationChange(), + ); // Determine ResolutionSelector and QualitySelector based on // resolutionPreset for camera UseCases. final ResolutionSelector? presetResolutionSelector = @@ -354,43 +372,64 @@ class AndroidCameraCameraX extends CameraPlatform { _getQualitySelectorFromPreset(mediaSettings?.resolutionPreset); // Retrieve a fresh ProcessCameraProvider instance. - processCameraProvider ??= await proxy.getProcessCameraProvider(); - processCameraProvider!.unbindAll(); + processCameraProvider ??= await proxy.getInstanceProcessCameraProvider(); + unawaited(processCameraProvider!.unbindAll()); // Configure Preview instance. - preview = proxy.createPreview(presetResolutionSelector, - /* use CameraX default target rotation */ null); - final int flutterSurfaceTextureId = - await proxy.setPreviewSurfaceProvider(preview!); + preview = proxy.newPreview( + resolutionSelector: presetResolutionSelector, + /* use CameraX default target rotation */ targetRotation: null, + ); + final int flutterSurfaceTextureId = await preview!.setSurfaceProvider( + systemServicesManager, + ); // Configure ImageCapture instance. - imageCapture = proxy.createImageCapture(presetResolutionSelector, - /* use CameraX default target rotation */ null); + imageCapture = proxy.newImageCapture( + resolutionSelector: presetResolutionSelector, + /* use CameraX default target rotation */ targetRotation: null, + ); // Configure ImageAnalysis instance. // Defaults to YUV_420_888 image format. - imageAnalysis = proxy.createImageAnalysis(presetResolutionSelector, - /* use CameraX default target rotation */ null); + imageAnalysis = proxy.newImageAnalysis( + resolutionSelector: presetResolutionSelector, + /* use CameraX default target rotation */ targetRotation: null, + ); // Configure VideoCapture and Recorder instances. - recorder = proxy.createRecorder(presetQualitySelector); - videoCapture = await proxy.createVideoCapture(recorder!); + recorder = proxy.newRecorder(qualitySelector: presetQualitySelector); + videoCapture = proxy.withOutputVideoCapture(videoOutput: recorder!); // Bind configured UseCases to ProcessCameraProvider instance & mark Preview // instance as bound but not paused. Video capture is bound at first use // instead of here. camera = await processCameraProvider!.bindToLifecycle( - cameraSelector!, [preview!, imageCapture!, imageAnalysis!]); + cameraSelector!, + [preview!, imageCapture!, imageAnalysis!], + ); await _updateCameraInfoAndLiveCameraState(flutterSurfaceTextureId); previewInitiallyBound = true; _previewIsPaused = false; // Retrieve info required for correcting the rotation of the camera preview // if necessary. + + final Camera2CameraInfo camera2CameraInfo = proxy.fromCamera2CameraInfo( + cameraInfo: cameraInfo!, + ); + sensorOrientationDegrees = + ((await camera2CameraInfo.getCameraCharacteristic( + proxy.sensorOrientationCameraCharacteristics(), + ))! as int) + .toDouble(); + sensorOrientationDegrees = cameraDescription.sensorOrientation.toDouble(); _handlesCropAndRotation = - await proxy.previewSurfaceProducerHandlesCropAndRotation(preview!); - _initialDeviceOrientation = await proxy.getUiOrientation(); + await preview!.surfaceProducerHandlesCropAndRotation(); + _initialDeviceOrientation = _deserializeDeviceOrientation( + await deviceOrientationManager.getUiOrientation(), + ); return flutterSurfaceTextureId; } @@ -422,7 +461,7 @@ class AndroidCameraCameraX extends CameraPlatform { } final ResolutionInfo previewResolutionInfo = - await preview!.getResolutionInfo(); + (await preview!.getResolutionInfo())!; // Mark auto-focus, auto-exposure and setting points for focus & exposure // as available operations as CameraX does its best across devices to @@ -432,14 +471,17 @@ class AndroidCameraCameraX extends CameraPlatform { const bool exposurePointSupported = true; const bool focusPointSupported = true; - cameraEventStreamController.add(CameraInitializedEvent( + cameraEventStreamController.add( + CameraInitializedEvent( cameraId, - previewResolutionInfo.width.toDouble(), - previewResolutionInfo.height.toDouble(), + previewResolutionInfo.resolution.width.toDouble(), + previewResolutionInfo.resolution.height.toDouble(), exposureMode, exposurePointSupported, focusMode, - focusPointSupported)); + focusPointSupported, + ), + ); } /// Releases the resources of the accessed camera. @@ -447,9 +489,9 @@ class AndroidCameraCameraX extends CameraPlatform { /// [cameraId] not used. @override Future dispose(int cameraId) async { - preview?.releaseFlutterSurfaceTexture(); + await preview?.releaseSurfaceProvider(); await liveCameraState?.removeObservers(); - processCameraProvider?.unbindAll(); + await processCameraProvider?.unbindAll(); await imageAnalysis?.clearAnalyzer(); } @@ -476,14 +518,16 @@ class AndroidCameraCameraX extends CameraPlatform { /// The camera experienced an error. @override Stream onCameraError(int cameraId) { - return StreamGroup.mergeBroadcast< - CameraErrorEvent>(>[ - SystemServices.cameraErrorStreamController.stream - .map((String errorDescription) { - return CameraErrorEvent(cameraId, errorDescription); - }), - _cameraEvents(cameraId).whereType() - ]); + return StreamGroup.mergeBroadcast( + >[ + cameraErrorStreamController.stream.map(( + String errorDescription, + ) { + return CameraErrorEvent(cameraId, errorDescription); + }), + _cameraEvents(cameraId).whereType(), + ], + ); } /// The camera finished recording a video. @@ -505,8 +549,9 @@ class AndroidCameraCameraX extends CameraPlatform { captureOrientationLocked = true; // Get target rotation based on locked orientation. - final int targetLockedRotation = - _getRotationConstantFromDeviceOrientation(orientation); + final int targetLockedRotation = _getRotationConstantFromDeviceOrientation( + orientation, + ); // Update UseCases to use target device orientation. await imageCapture!.setTargetRotation(targetLockedRotation); @@ -538,9 +583,10 @@ class AndroidCameraCameraX extends CameraPlatform { // is implemented with Camera2 interop that will override settings to // achieve the expected exposure mode as needed). await _startFocusAndMeteringForPoint( - point: point, - meteringMode: FocusMeteringAction.flagAe, - disableAutoCancel: _currentFocusMode == FocusMode.locked); + point: point, + meteringMode: MeteringMode.ae, + disableAutoCancel: _currentFocusMode == FocusMode.locked, + ); } /// Gets the minimum supported exposure offset for the selected camera in EV units. @@ -548,8 +594,8 @@ class AndroidCameraCameraX extends CameraPlatform { /// [cameraId] not used. @override Future getMinExposureOffset(int cameraId) async { - final ExposureState exposureState = await cameraInfo!.getExposureState(); - return exposureState.exposureCompensationRange.minCompensation * + final ExposureState exposureState = cameraInfo!.exposureState; + return exposureState.exposureCompensationRange.lower * exposureState.exposureCompensationStep; } @@ -558,8 +604,8 @@ class AndroidCameraCameraX extends CameraPlatform { /// [cameraId] not used. @override Future getMaxExposureOffset(int cameraId) async { - final ExposureState exposureState = await cameraInfo!.getExposureState(); - return exposureState.exposureCompensationRange.maxCompensation * + final ExposureState exposureState = cameraInfo!.exposureState; + return exposureState.exposureCompensationRange.upper * exposureState.exposureCompensationStep; } @@ -586,12 +632,7 @@ class AndroidCameraCameraX extends CameraPlatform { // default auto-focus point if set previously to lock focus. final MeteringPoint? unLockedFocusPoint = _defaultFocusPointLocked ? null - : currentFocusMeteringAction!.meteringPointInfos - .where(((MeteringPoint, int?) meteringPointInfo) => - meteringPointInfo.$2 == FocusMeteringAction.flagAf) - .toList() - .first - .$1; + : currentFocusMeteringAction!.meteringPointsAf.first; _defaultFocusPointLocked = false; autoFocusPoint = unLockedFocusPoint; disableAutoCancel = false; @@ -600,20 +641,26 @@ class AndroidCameraCameraX extends CameraPlatform { // Determine if there is an auto-focus point set currently to lock. if (currentFocusMeteringAction != null) { - final List<(MeteringPoint, int?)> possibleCurrentAfPoints = - currentFocusMeteringAction!.meteringPointInfos - .where(((MeteringPoint, int?) meteringPointInfo) => - meteringPointInfo.$2 == FocusMeteringAction.flagAf) - .toList(); + final List possibleCurrentAfPoints = + currentFocusMeteringAction!.meteringPointsAf; lockedFocusPoint = possibleCurrentAfPoints.isEmpty ? null - : possibleCurrentAfPoints.first.$1; + : possibleCurrentAfPoints.first; } // If there isn't, lock center of entire sensor area by default. if (lockedFocusPoint == null) { - lockedFocusPoint = - proxy.createMeteringPoint(0.5, 0.5, 1, cameraInfo!); + final DisplayOrientedMeteringPointFactory meteringPointFactory = + proxy.newDisplayOrientedMeteringPointFactory( + cameraInfo: cameraInfo!, + width: 1, + height: 1, + ); + lockedFocusPoint = await meteringPointFactory.createPointWithSize( + 0.5, + 0.5, + 1, + ); _defaultFocusPointLocked = true; } @@ -622,9 +669,10 @@ class AndroidCameraCameraX extends CameraPlatform { } // Start appropriate focus and metering action. final bool focusAndMeteringWasSuccessful = await _startFocusAndMeteringFor( - meteringPoint: autoFocusPoint, - meteringMode: FocusMeteringAction.flagAf, - disableAutoCancel: disableAutoCancel); + meteringPoint: autoFocusPoint, + meteringMode: MeteringMode.af, + disableAutoCancel: disableAutoCancel, + ); if (!focusAndMeteringWasSuccessful) { // Do not update current focus mode. @@ -650,7 +698,7 @@ class AndroidCameraCameraX extends CameraPlatform { /// [cameraId] not used. @override Future getExposureOffsetStepSize(int cameraId) async { - final ExposureState exposureState = await cameraInfo!.getExposureState(); + final ExposureState exposureState = cameraInfo!.exposureState; final double exposureOffsetStepSize = exposureState.exposureCompensationStep; if (exposureOffsetStepSize == 0) { @@ -677,10 +725,12 @@ class AndroidCameraCameraX extends CameraPlatform { @override Future setExposureOffset(int cameraId, double offset) async { final double exposureOffsetStepSize = - (await cameraInfo!.getExposureState()).exposureCompensationStep; + cameraInfo!.exposureState.exposureCompensationStep; if (exposureOffsetStepSize == 0) { - throw CameraException(exposureCompensationNotSupported, - 'Exposure compensation not supported'); + throw CameraException( + exposureCompensationNotSupported, + 'Exposure compensation not supported', + ); } // (Exposure compensation index) * (exposure offset step size) = @@ -689,19 +739,30 @@ class AndroidCameraCameraX extends CameraPlatform { (offset / exposureOffsetStepSize).round(); try { - final int? newIndex = await cameraControl - .setExposureCompensationIndex(roundedExposureCompensationIndex); + final int? newIndex = await cameraControl.setExposureCompensationIndex( + roundedExposureCompensationIndex, + ); + if (newIndex == null) { - throw CameraException(setExposureOffsetFailedErrorCode, + cameraErrorStreamController.add( 'Setting exposure compensation index was canceled due to the camera being closed or a new request being submitted.'); + throw CameraException( + setExposureOffsetFailedErrorCode, + 'Setting exposure compensation index was canceled due to the camera being closed or a new request being submitted.', + ); } return newIndex.toDouble(); } on PlatformException catch (e) { + cameraErrorStreamController.add(e.message ?? + 'Setting the camera exposure compensation index failed.'); + // Surfacing error to plugin layer to maintain consistency of + // setExposureOffset implementation across platform implementations. + throw CameraException( - setExposureOffsetFailedErrorCode, - e.message ?? - 'Setting the camera exposure compensation index failed.'); + setExposureOffsetFailedErrorCode, + e.message ?? 'Setting the camera exposure compensation index failed.', + ); } } @@ -722,9 +783,10 @@ class AndroidCameraCameraX extends CameraPlatform { // is implemented with Camera2 interop that will override settings to // achieve the expected exposure mode as needed). await _startFocusAndMeteringForPoint( - point: point, - meteringMode: FocusMeteringAction.flagAf, - disableAutoCancel: _currentFocusMode == FocusMode.locked); + point: point, + meteringMode: MeteringMode.af, + disableAutoCancel: _currentFocusMode == FocusMode.locked, + ); } /// Sets the exposure mode for taking pictures. @@ -735,17 +797,25 @@ class AndroidCameraCameraX extends CameraPlatform { /// [cameraId] is not used. @override Future setExposureMode(int cameraId, ExposureMode mode) async { - final Camera2CameraControl camera2Control = - proxy.getCamera2CameraControl(cameraControl); + final Camera2CameraControl camera2Control = proxy.fromCamera2CameraControl( + cameraControl: cameraControl, + ); final bool lockExposureMode = mode == ExposureMode.locked; - final CaptureRequestOptions captureRequestOptions = proxy - .createCaptureRequestOptions(<( - CaptureRequestKeySupportedType, - Object? - )>[(CaptureRequestKeySupportedType.controlAeLock, lockExposureMode)]); + final CaptureRequestOptions captureRequestOptions = + proxy.newCaptureRequestOptions( + options: { + proxy.controlAELockCaptureRequest(): lockExposureMode, + }, + ); + + try { + await camera2Control.addCaptureRequestOptions(captureRequestOptions); + } on PlatformException catch (e) { + cameraErrorStreamController.add(e.message ?? + 'The camera was unable to set new capture request options due to new options being unavailable or the camera being closed.'); + } - await camera2Control.addCaptureRequestOptions(captureRequestOptions); _currentExposureMode = mode; } @@ -790,14 +860,18 @@ class AndroidCameraCameraX extends CameraPlatform { /// Throws a `CameraException` when an illegal zoom level is supplied. @override Future setZoomLevel(int cameraId, double zoom) async { - await cameraControl.setZoomRatio(zoom); + try { + await cameraControl.setZoomRatio(zoom); + } on PlatformException catch (e) { + cameraErrorStreamController.add(e.message ?? + 'Zoom ratio was unable to be set. If ratio was not out of range, newer value may have been set; otherwise, the camera may be closed.'); + } } /// The ui orientation changed. @override Stream onDeviceOrientationChanged() { - return DeviceOrientationManager - .deviceOrientationChangedStreamController.stream; + return deviceOrientationChangedStreamController.stream; } /// Pause the active preview on the current frame for the selected camera. @@ -849,8 +923,9 @@ class AndroidCameraCameraX extends CameraPlatform { } final Stream deviceOrientationStream = - onDeviceOrientationChanged() - .map((DeviceOrientationChangedEvent e) => e.orientation); + onDeviceOrientationChanged().map( + (DeviceOrientationChangedEvent e) => e.orientation, + ); if (cameraIsFrontFacing) { return RotatedPreview.frontFacingCamera( _initialDeviceOrientation, @@ -880,14 +955,15 @@ class AndroidCameraCameraX extends CameraPlatform { } else if (torchEnabled) { // Ensure any previously set flash modes are unset when torch mode has // been enabled. - await imageCapture!.setFlashMode(ImageCapture.flashModeOff); + await imageCapture!.setFlashMode(CameraXFlashMode.off); } // Set target rotation to default CameraX rotation only if capture // orientation not locked. if (!(captureOrientationLocked && shouldSetDefaultRotation)) { - await imageCapture! - .setTargetRotation(await proxy.getDefaultDisplayRotation()); + await imageCapture!.setTargetRotation( + await deviceOrientationManager.getDefaultDisplayRotation(), + ); } final String picturePath = await imageCapture!.takePicture(); @@ -910,24 +986,25 @@ class AndroidCameraCameraX extends CameraPlatform { Future setFlashMode(int cameraId, FlashMode mode) async { // Turn off torch mode if it is enabled and not being redundantly set. if (mode != FlashMode.torch && torchEnabled) { - await cameraControl.enableTorch(false); + await _enableTorchMode(false); torchEnabled = false; } switch (mode) { case FlashMode.off: - _currentFlashMode = ImageCapture.flashModeOff; + _currentFlashMode = CameraXFlashMode.off; case FlashMode.auto: - _currentFlashMode = ImageCapture.flashModeAuto; + _currentFlashMode = CameraXFlashMode.auto; case FlashMode.always: - _currentFlashMode = ImageCapture.flashModeOn; + _currentFlashMode = CameraXFlashMode.on; case FlashMode.torch: _currentFlashMode = null; if (torchEnabled) { // Torch mode enabled already. return; } - await cameraControl.enableTorch(true); + + await _enableTorchMode(true); torchEnabled = true; } } @@ -950,8 +1027,10 @@ class AndroidCameraCameraX extends CameraPlatform { /// /// This method is deprecated in favour of [startVideoCapturing]. @override - Future startVideoRecording(int cameraId, - {Duration? maxVideoDuration}) async { + Future startVideoRecording( + int cameraId, { + Duration? maxVideoDuration, + }) async { // Ignore maxVideoDuration, as it is unimplemented and deprecated. return startVideoCapturing(VideoCaptureOptions(cameraId)); } @@ -978,15 +1057,17 @@ class AndroidCameraCameraX extends CameraPlatform { // the preview must be paused in order to allow those concurrently. See // https://developer.android.com/media/camera/camerax/architecture#combine-use-cases // for more information on supported concurrent camera use cases. - final Camera2CameraInfo camera2CameraInfo = - await proxy.getCamera2CameraInfo(cameraInfo!); - final int cameraInfoSupportedHardwareLevel = - await camera2CameraInfo.getSupportedHardwareLevel(); + final Camera2CameraInfo camera2CameraInfo = proxy.fromCamera2CameraInfo( + cameraInfo: cameraInfo!, + ); + final InfoSupportedHardwareLevel cameraInfoSupportedHardwareLevel = + (await camera2CameraInfo.getCameraCharacteristic( + proxy.infoSupportedHardwareLevelCameraCharacteristics(), + ))! as InfoSupportedHardwareLevel; // Handle limited level device restrictions: final bool cameraSupportsConcurrentImageCapture = - cameraInfoSupportedHardwareLevel != - CameraMetadata.infoSupportedHardwareLevelLegacy; + cameraInfoSupportedHardwareLevel != InfoSupportedHardwareLevel.legacy; if (!cameraSupportsConcurrentImageCapture) { // Concurrent preview + video recording + image capture is not supported // unless the camera device is cameraSupportsHardwareLevelLimited or @@ -996,8 +1077,7 @@ class AndroidCameraCameraX extends CameraPlatform { // Handle level 3 device restrictions: final bool cameraSupportsHardwareLevel3 = - cameraInfoSupportedHardwareLevel == - CameraMetadata.infoSupportedHardwareLevel3; + cameraInfoSupportedHardwareLevel == InfoSupportedHardwareLevel.level3; if (!cameraSupportsHardwareLevel3 || streamCallback == null) { // Concurrent preview + video recording + image streaming is not supported // unless the camera device is cameraSupportsHardwareLevel3 or better. @@ -1015,14 +1095,18 @@ class AndroidCameraCameraX extends CameraPlatform { // Set target rotation to default CameraX rotation only if capture // orientation not locked. if (!captureOrientationLocked && shouldSetDefaultRotation) { - await videoCapture! - .setTargetRotation(await proxy.getDefaultDisplayRotation()); + await videoCapture!.setTargetRotation( + await deviceOrientationManager.getDefaultDisplayRotation(), + ); } - videoOutputPath = - await SystemServices.getTempFilePath(videoPrefix, '.temp'); + videoOutputPath = await systemServicesManager.getTempFilePath( + videoPrefix, + '.temp', + ); pendingRecording = await recorder!.prepareRecording(videoOutputPath!); - recording = await pendingRecording!.start(); + + recording = await pendingRecording!.start(_videoRecordingEventListener); if (streamCallback != null) { onStreamedFrameAvailable(options.cameraId).listen(streamCallback); @@ -1030,7 +1114,7 @@ class AndroidCameraCameraX extends CameraPlatform { // Wait for video recording to start. VideoRecordEvent event = await videoRecordingEventStreamQueue.next; - while (event != VideoRecordEvent.start) { + while (event is! VideoRecordEventStart) { event = await videoRecordingEventStreamQueue.next; } } @@ -1045,15 +1129,16 @@ class AndroidCameraCameraX extends CameraPlatform { Future stopVideoRecording(int cameraId) async { if (recording == null) { throw CameraException( - 'videoRecordingFailed', - 'Attempting to stop a ' - 'video recording while no recording is in progress.'); + 'videoRecordingFailed', + 'Attempting to stop a ' + 'video recording while no recording is in progress.', + ); } /// Stop the active recording and wait for the video recording to be finalized. await recording!.close(); VideoRecordEvent event = await videoRecordingEventStreamQueue.next; - while (event != VideoRecordEvent.finalize) { + while (event is! VideoRecordEventFinalize) { event = await videoRecordingEventStreamQueue.next; } recording = null; @@ -1062,16 +1147,18 @@ class AndroidCameraCameraX extends CameraPlatform { if (videoOutputPath == null) { // Handle any errors with finalizing video recording. throw CameraException( - 'INVALID_PATH', - 'The platform did not return a path ' - 'while reporting success. The platform should always ' - 'return a valid path or report an error.'); + 'INVALID_PATH', + 'The platform did not return a path ' + 'while reporting success. The platform should always ' + 'return a valid path or report an error.', + ); } await _unbindUseCaseFromLifecycle(videoCapture!); final XFile videoFile = XFile(videoOutputPath!); - cameraEventStreamController - .add(VideoRecordedEvent(cameraId, videoFile, /* duration */ null)); + cameraEventStreamController.add( + VideoRecordedEvent(cameraId, videoFile, /* duration */ null), + ); return videoFile; } @@ -1105,8 +1192,10 @@ class AndroidCameraCameraX extends CameraPlatform { /// /// [cameraId] and [options] are not used. @override - Stream onStreamedFrameAvailable(int cameraId, - {CameraImageStreamOptions? options}) { + Stream onStreamedFrameAvailable( + int cameraId, { + CameraImageStreamOptions? options, + }) { cameraImageDataStreamController = StreamController( onListen: () async => _configureImageAnalysis(cameraId), onCancel: _onFrameStreamCancel, @@ -1133,8 +1222,10 @@ class AndroidCameraCameraX extends CameraPlatform { return; } - camera = await processCameraProvider! - .bindToLifecycle(cameraSelector!, [useCase]); + camera = await processCameraProvider!.bindToLifecycle( + cameraSelector!, + [useCase], + ); await _updateCameraInfoAndLiveCameraState(cameraId); } @@ -1146,8 +1237,9 @@ class AndroidCameraCameraX extends CameraPlatform { // Set target rotation to default CameraX rotation only if capture // orientation not locked. if (!captureOrientationLocked && shouldSetDefaultRotation) { - await imageAnalysis! - .setTargetRotation(await proxy.getDefaultDisplayRotation()); + await imageAnalysis!.setTargetRotation( + await deviceOrientationManager.getDefaultDisplayRotation(), + ); } // Create and set Analyzer that can read image data for image streaming. @@ -1157,29 +1249,35 @@ class AndroidCameraCameraX extends CameraPlatform { final List planes = await imageProxy.getPlanes(); final List cameraImagePlanes = []; for (final PlaneProxy plane in planes) { - cameraImagePlanes.add(CameraImagePlane( + cameraImagePlanes.add( + CameraImagePlane( bytes: plane.buffer, bytesPerRow: plane.rowStride, - bytesPerPixel: plane.pixelStride)); + bytesPerPixel: plane.pixelStride, + ), + ); } final int format = imageProxy.format; final CameraImageFormat cameraImageFormat = CameraImageFormat( - _imageFormatGroupFromPlatformData(format), - raw: format); + _imageFormatGroupFromPlatformData(format), + raw: format, + ); final CameraImageData cameraImageData = CameraImageData( - format: cameraImageFormat, - planes: cameraImagePlanes, - height: imageProxy.height, - width: imageProxy.width); + format: cameraImageFormat, + planes: cameraImagePlanes, + height: imageProxy.height, + width: imageProxy.width, + ); weakThis.target!.cameraImageDataStreamController!.add(cameraImageData); await imageProxy.close(); } - final Analyzer analyzer = proxy.createAnalyzer(analyze); - await imageAnalysis!.setAnalyzer(analyzer); + await imageAnalysis!.setAnalyzer( + proxy.newAnalyzer(analyze: (_, ImageProxy image) => analyze(image)), + ); } /// Unbinds [useCase] from camera lifecycle controlled by the @@ -1190,7 +1288,7 @@ class AndroidCameraCameraX extends CameraPlatform { return; } - processCameraProvider!.unbind([useCase]); + await processCameraProvider!.unbind([useCase]); } // Methods for configuring image streaming: @@ -1227,8 +1325,8 @@ class AndroidCameraCameraX extends CameraPlatform { /// If a previous [liveCameraState] was stored, existing observers are /// removed, as well. Future _updateCameraInfoAndLiveCameraState(int cameraId) async { - cameraInfo = await camera!.getCameraInfo(); - cameraControl = await camera!.getCameraControl(); + cameraInfo = (await camera!.getCameraInfo()) as CameraInfo; + cameraControl = camera!.cameraControl; await liveCameraState?.removeObservers(); liveCameraState = await cameraInfo!.getCameraState(); await liveCameraState!.observe(_createCameraClosingObserver(cameraId)); @@ -1245,36 +1343,64 @@ class AndroidCameraCameraX extends CameraPlatform { WeakReference(this); // Callback method used to implement the behavior described above: - void onChanged(Object stateAsObject) { - // This cast is safe because the Observer implementation ensures - // the type of stateAsObject is the same as the observer this callback - // is attached to. - final CameraState state = stateAsObject as CameraState; + void onChanged(CameraState state) { if (state.type == CameraStateType.closing) { - weakThis.target!.cameraEventStreamController - .add(CameraClosingEvent(cameraId)); + weakThis.target!.cameraEventStreamController.add( + CameraClosingEvent(cameraId), + ); } if (state.error != null) { - weakThis.target!.cameraEventStreamController - .add(CameraErrorEvent(cameraId, state.error!.getDescription())); + late final String errorDescription; + switch (state.error!.code) { + case CameraStateErrorCode.cameraInUse: + errorDescription = + 'The camera was already in use, possibly by a higher-priority camera client.'; + case CameraStateErrorCode.maxCamerasInUse: + errorDescription = + 'The limit number of open cameras has been reached, and more cameras cannot be opened until other instances are closed.'; + case CameraStateErrorCode.otherRecoverableError: + errorDescription = + 'The camera device has encountered a recoverable error. CameraX will attempt to recover from the error.'; + case CameraStateErrorCode.streamConfig: + errorDescription = 'Configuring the camera has failed.'; + case CameraStateErrorCode.cameraDisabled: + errorDescription = + 'The camera device could not be opened due to a device policy. Thia may be caused by a client from a background process attempting to open the camera.'; + case CameraStateErrorCode.cameraFatalError: + errorDescription = + 'The camera was closed due to a fatal error. This may require the Android device be shut down and restarted to restore camera function or may indicate a persistent camera hardware problem.'; + case CameraStateErrorCode.doNotDisturbModeEnabled: + errorDescription = + 'The camera could not be opened because "Do Not Disturb" mode is enabled. Please disable this mode, and try opening the camera again.'; + case CameraStateErrorCode.unknown: + errorDescription = + 'There was an unspecified issue with the current camera state.'; + } + weakThis.target!.cameraEventStreamController.add( + CameraErrorEvent(cameraId, errorDescription), + ); } } - return proxy.createCameraStateObserver(onChanged); + return proxy.newObserver( + onChanged: (_, CameraState value) => onChanged(value), + ); } // Methods for mapping Flutter camera constants to CameraX constants: /// Returns [CameraSelector] lens direction that maps to specified /// [CameraLensDirection]. - int _getCameraSelectorLensDirection(CameraLensDirection lensDirection) { + LensFacing _getCameraSelectorLensDirection( + CameraLensDirection lensDirection, + ) { switch (lensDirection) { case CameraLensDirection.front: - return CameraSelector.lensFacingFront; + return LensFacing.front; case CameraLensDirection.back: - return CameraSelector.lensFacingBack; + return LensFacing.back; case CameraLensDirection.external: - return CameraSelector.lensFacingExternal; + return LensFacing.external; } } @@ -1300,50 +1426,61 @@ class AndroidCameraCameraX extends CameraPlatform { /// If the specified [preset] is unavailable, the camera will fall back to the /// closest lower resolution available. ResolutionSelector? _getResolutionSelectorFromPreset( - ResolutionPreset? preset) { - const int fallbackRule = - ResolutionStrategy.fallbackRuleClosestLowerThenHigher; + ResolutionPreset? preset, + ) { + const ResolutionStrategyFallbackRule fallbackRule = + ResolutionStrategyFallbackRule.closestLowerThenHigher; - Size? boundSize; - int? aspectRatio; + CameraSize? boundSize; + AspectRatio? aspectRatio; ResolutionStrategy? resolutionStrategy; switch (preset) { case ResolutionPreset.low: - boundSize = const Size(320, 240); + boundSize = proxy.newCameraSize(width: 320, height: 240); aspectRatio = AspectRatio.ratio4To3; case ResolutionPreset.medium: - boundSize = const Size(720, 480); + boundSize = proxy.newCameraSize(width: 720, height: 480); case ResolutionPreset.high: - boundSize = const Size(1280, 720); + boundSize = proxy.newCameraSize(width: 1280, height: 720); aspectRatio = AspectRatio.ratio16To9; case ResolutionPreset.veryHigh: - boundSize = const Size(1920, 1080); + boundSize = proxy.newCameraSize(width: 1920, height: 1080); aspectRatio = AspectRatio.ratio16To9; case ResolutionPreset.ultraHigh: - boundSize = const Size(3840, 2160); + boundSize = proxy.newCameraSize(width: 3840, height: 2160); aspectRatio = AspectRatio.ratio16To9; case ResolutionPreset.max: // Automatically set strategy to choose highest available. - resolutionStrategy = - proxy.createResolutionStrategy(highestAvailable: true); - return proxy.createResolutionSelector(resolutionStrategy, - /* ResolutionFilter */ null, /* AspectRatioStrategy */ null); + resolutionStrategy = proxy.highestAvailableStrategyResolutionStrategy(); + return proxy.newResolutionSelector( + resolutionStrategy: resolutionStrategy, + ); case null: // If no preset is specified, default to CameraX's default behavior // for each UseCase. return null; } - resolutionStrategy = proxy.createResolutionStrategy( - boundSize: boundSize, fallbackRule: fallbackRule); - final ResolutionFilter resolutionFilter = - proxy.createResolutionFilterWithOnePreferredSize(boundSize); + resolutionStrategy = proxy.newResolutionStrategy( + boundSize: proxy.newCameraSize( + width: boundSize.width, + height: boundSize.height, + ), + fallbackRule: fallbackRule, + ); + final ResolutionFilter resolutionFilter = proxy + .createWithOnePreferredSizeResolutionFilter(preferredSize: boundSize); final AspectRatioStrategy? aspectRatioStrategy = aspectRatio == null ? null - : proxy.createAspectRatioStrategy( - aspectRatio, AspectRatioStrategy.fallbackRuleAuto); - return proxy.createResolutionSelector( - resolutionStrategy, resolutionFilter, aspectRatioStrategy); + : proxy.newAspectRatioStrategy( + preferredAspectRatio: aspectRatio, + fallbackRule: AspectRatioStrategyFallbackRule.auto, + ); + return proxy.newResolutionSelector( + resolutionStrategy: resolutionStrategy, + resolutionFilter: resolutionFilter, + aspectRatioStrategy: aspectRatioStrategy, + ); } /// Returns the [QualitySelector] that maps to the specified resolution @@ -1374,28 +1511,44 @@ class AndroidCameraCameraX extends CameraPlatform { // We will choose the next highest video quality if the one desired // is unavailable. - const VideoResolutionFallbackRule fallbackRule = - VideoResolutionFallbackRule.lowerQualityOrHigherThan; - final FallbackStrategy fallbackStrategy = proxy.createFallbackStrategy( - quality: videoQuality, fallbackRule: fallbackRule); + final FallbackStrategy fallbackStrategy = + proxy.lowerQualityOrHigherThanFallbackStrategy(quality: videoQuality); - return proxy.createQualitySelector( - videoQuality: videoQuality, fallbackStrategy: fallbackStrategy); + return proxy.fromQualitySelector( + quality: videoQuality, + fallbackStrategy: fallbackStrategy, + ); } // Methods for configuring auto-focus and auto-exposure: - Future _startFocusAndMeteringForPoint( - {required Point? point, - required int meteringMode, - bool disableAutoCancel = false}) async { + Future _startFocusAndMeteringForPoint({ + required Point? point, + required MeteringMode meteringMode, + bool disableAutoCancel = false, + }) async { + MeteringPoint? meteringPoint; + if (point != null) { + if (point.x < 0 || point.x > 1 || point.y < 0 || point.y > 1) { + throw CameraException( + 'pointInvalid', + 'The coordinates of a metering point for an auto-focus or auto-exposure action must be within (0,0) and (1,1), but a point with coordinates (${point.x}, ${point.y}) was provided for metering mode $meteringMode.', + ); + } + + final DisplayOrientedMeteringPointFactory meteringPointFactory = + proxy.newDisplayOrientedMeteringPointFactory( + width: 1.0, + height: 1.0, + cameraInfo: cameraInfo!, + ); + meteringPoint = await meteringPointFactory.createPoint(point.x, point.y); + } return _startFocusAndMeteringFor( - meteringPoint: point == null - ? null - : proxy.createMeteringPoint( - point.x, point.y, /* size */ null, cameraInfo!), - meteringMode: meteringMode, - disableAutoCancel: disableAutoCancel); + meteringPoint: meteringPoint, + meteringMode: meteringMode, + disableAutoCancel: disableAutoCancel, + ); } /// Starts a focus and metering action and returns whether or not it was @@ -1419,10 +1572,11 @@ class AndroidCameraCameraX extends CameraPlatform { /// to [currentFocusMeteringAction] that do not share a metering mode with /// [meteringPoint]. If [meteringPoint] and [currentFocusMeteringAction] are /// null, then focus and metering will be canceled. - Future _startFocusAndMeteringFor( - {required MeteringPoint? meteringPoint, - required int meteringMode, - bool disableAutoCancel = false}) async { + Future _startFocusAndMeteringFor({ + required MeteringPoint? meteringPoint, + required MeteringMode meteringMode, + bool disableAutoCancel = false, + }) async { if (meteringPoint == null) { // Try to clear any metering point from previous action with the specified // meteringMode. @@ -1432,17 +1586,22 @@ class AndroidCameraCameraX extends CameraPlatform { return false; } + final Iterable<(MeteringPoint, MeteringMode)> originalMeteringPoints = + _combineMeteringPoints(currentFocusMeteringAction!); + // Remove metering point with specified meteringMode from current focus // and metering action, as only one focus or exposure point may be set // at once in this plugin. - final List<(MeteringPoint, int?)> newMeteringPointInfos = - currentFocusMeteringAction!.meteringPointInfos - .where(((MeteringPoint, int?) meteringPointInfo) => - // meteringPointInfo may technically include points without a - // mode specified, but this logic is safe because this plugin - // only uses points that explicitly have mode - // FocusMeteringAction.flagAe or FocusMeteringAction.flagAf. - meteringPointInfo.$2 != meteringMode) + final List<(MeteringPoint, MeteringMode)> newMeteringPointInfos = + originalMeteringPoints + .where( + ((MeteringPoint, MeteringMode) meteringPointInfo) => + // meteringPointInfo may technically include points without a + // mode specified, but this logic is safe because this plugin + // only uses points that explicitly have mode + // FocusMeteringAction.flagAe or FocusMeteringAction.flagAf. + meteringPointInfo.$2 != meteringMode, + ) .toList(); if (newMeteringPointInfos.isEmpty) { @@ -1452,38 +1611,138 @@ class AndroidCameraCameraX extends CameraPlatform { currentFocusMeteringAction = null; return true; } - currentFocusMeteringAction = proxy.createFocusMeteringAction( - newMeteringPointInfos, disableAutoCancel); - } else if (meteringPoint.x < 0 || - meteringPoint.x > 1 || - meteringPoint.y < 0 || - meteringPoint.y > 1) { - throw CameraException('pointInvalid', - 'The coordinates of a metering point for an auto-focus or auto-exposure action must be within (0,0) and (1,1), but a point with coordinates (${meteringPoint.x}, ${meteringPoint.y}) was provided for metering mode $meteringMode.'); + // Create builder to potentially add more MeteringPoints to. + final FocusMeteringActionBuilder actionBuilder = + proxy.withModeFocusMeteringActionBuilder( + point: newMeteringPointInfos.first.$1, + mode: newMeteringPointInfos.first.$2, + ); + if (disableAutoCancel) { + unawaited(actionBuilder.disableAutoCancel()); + } + + // Add any additional metering points in order as specified by input lists. + newMeteringPointInfos.skip(1).forEach(( + (MeteringPoint point, MeteringMode) info, + ) { + actionBuilder.addPointWithMode(info.$1, info.$2); + }); + currentFocusMeteringAction = await actionBuilder.build(); } else { // Add new metering point with specified meteringMode, which may involve // replacing a metering point with the same specified meteringMode from // the current focus and metering action. - List<(MeteringPoint, int?)> newMeteringPointInfos = - <(MeteringPoint, int?)>[]; + List<(MeteringPoint, MeteringMode)> newMeteringPointInfos = + <(MeteringPoint, MeteringMode)>[]; if (currentFocusMeteringAction != null) { - newMeteringPointInfos = currentFocusMeteringAction!.meteringPointInfos - .where(((MeteringPoint, int?) meteringPointInfo) => - // meteringPointInfo may technically include points without a - // mode specified, but this logic is safe because this plugin - // only uses points that explicitly have mode - // FocusMeteringAction.flagAe or FocusMeteringAction.flagAf. - meteringPointInfo.$2 != meteringMode) + final Iterable<(MeteringPoint, MeteringMode)> originalMeteringPoints = + _combineMeteringPoints(currentFocusMeteringAction!); + + newMeteringPointInfos = originalMeteringPoints + .where( + ((MeteringPoint, MeteringMode) meteringPointInfo) => + // meteringPointInfo may technically include points without a + // mode specified, but this logic is safe because this plugin + // only uses points that explicitly have mode + // FocusMeteringAction.flagAe or FocusMeteringAction.flagAf. + meteringPointInfo.$2 != meteringMode, + ) .toList(); } + newMeteringPointInfos.add((meteringPoint, meteringMode)); - currentFocusMeteringAction = proxy.createFocusMeteringAction( - newMeteringPointInfos, disableAutoCancel); + + final FocusMeteringActionBuilder actionBuilder = + proxy.withModeFocusMeteringActionBuilder( + point: newMeteringPointInfos.first.$1, + mode: newMeteringPointInfos.first.$2, + ); + + if (disableAutoCancel) { + unawaited(actionBuilder.disableAutoCancel()); + } + + newMeteringPointInfos.skip(1).forEach(( + (MeteringPoint point, MeteringMode mode) info, + ) { + actionBuilder.addPointWithMode(info.$1, info.$2); + }); + currentFocusMeteringAction = await actionBuilder.build(); } - final FocusMeteringResult? result = - await cameraControl.startFocusAndMetering(currentFocusMeteringAction!); - return await result?.isFocusSuccessful() ?? false; + try { + final FocusMeteringResult? result = await cameraControl + .startFocusAndMetering(currentFocusMeteringAction!); + + if (result == null) { + cameraErrorStreamController.add( + 'Starting focus and metering was canceled due to the camera being closed or a new request being submitted.', + ); + } + + return result?.isFocusSuccessful ?? false; + } on PlatformException catch (e) { + cameraErrorStreamController.add( + e.message ?? 'Starting focus and metering failed.', + ); + // Surfacing error to differentiate an operation cancellation from an + // illegal argument exception at a plugin layer. + rethrow; + } + } + + // Combines the metering points and metering modes of a `FocusMeteringAction` + // into a single list. + Iterable<(MeteringPoint, MeteringMode)> _combineMeteringPoints( + FocusMeteringAction focusMeteringAction, + ) { + Iterable<(MeteringPoint, MeteringMode)> toMeteringPointRecords( + Iterable points, + MeteringMode mode, + ) { + return points.map((MeteringPoint point) => (point, mode)); + } + + return <(MeteringPoint, MeteringMode)>[ + ...toMeteringPointRecords( + focusMeteringAction.meteringPointsAf, + MeteringMode.af, + ), + ...toMeteringPointRecords( + focusMeteringAction.meteringPointsAe, + MeteringMode.ae, + ), + ...toMeteringPointRecords( + focusMeteringAction.meteringPointsAwb, + MeteringMode.awb, + ), + ]; + } + + Future _enableTorchMode(bool value) async { + try { + await cameraControl.enableTorch(value); + } on PlatformException catch (e) { + cameraErrorStreamController + .add(e.message ?? 'The camera was unable to change torch modes.'); + } + } + + static DeviceOrientation _deserializeDeviceOrientation(String orientation) { + switch (orientation) { + case 'LANDSCAPE_LEFT': + return DeviceOrientation.landscapeLeft; + case 'LANDSCAPE_RIGHT': + return DeviceOrientation.landscapeRight; + case 'PORTRAIT_DOWN': + return DeviceOrientation.portraitDown; + case 'PORTRAIT_UP': + return DeviceOrientation.portraitUp; + default: + throw ArgumentError( + '"$orientation" is not a valid DeviceOrientation value', + ); + } } } diff --git a/packages/camera/camera_android_camerax/lib/src/android_camera_camerax_flutter_api_impls.dart b/packages/camera/camera_android_camerax/lib/src/android_camera_camerax_flutter_api_impls.dart deleted file mode 100644 index 5a2af4e576a8..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/android_camera_camerax_flutter_api_impls.dart +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'analyzer.dart'; -import 'camera.dart'; -import 'camera2_camera_info.dart'; -import 'camera_control.dart'; -import 'camera_info.dart'; -import 'camera_selector.dart'; -import 'camera_state.dart'; -import 'camera_state_error.dart'; -import 'camerax_library.g.dart'; -import 'device_orientation_manager.dart'; -import 'exposure_state.dart'; -import 'focus_metering_result.dart'; -import 'image_proxy.dart'; -import 'java_object.dart'; -import 'live_data.dart'; -import 'observer.dart'; -import 'pending_recording.dart'; -import 'plane_proxy.dart'; -import 'process_camera_provider.dart'; -import 'recorder.dart'; -import 'recording.dart'; -import 'system_services.dart'; -import 'video_capture.dart'; -import 'zoom_state.dart'; - -/// Handles initialization of Flutter APIs for the Android CameraX library. -class AndroidCameraXCameraFlutterApis { - /// Creates a [AndroidCameraXCameraFlutterApis]. - AndroidCameraXCameraFlutterApis( - {JavaObjectFlutterApiImpl? javaObjectFlutterApiImpl, - CameraFlutterApiImpl? cameraFlutterApiImpl, - CameraInfoFlutterApiImpl? cameraInfoFlutterApiImpl, - CameraSelectorFlutterApiImpl? cameraSelectorFlutterApiImpl, - ProcessCameraProviderFlutterApiImpl? processCameraProviderFlutterApiImpl, - SystemServicesFlutterApiImpl? systemServicesFlutterApiImpl, - DeviceOrientationManagerFlutterApiImpl? - deviceOrientationManagerFlutterApiImpl, - CameraStateErrorFlutterApiImpl? cameraStateErrorFlutterApiImpl, - CameraStateFlutterApiImpl? cameraStateFlutterApiImpl, - PendingRecordingFlutterApiImpl? pendingRecordingFlutterApiImpl, - RecordingFlutterApiImpl? recordingFlutterApiImpl, - RecorderFlutterApiImpl? recorderFlutterApiImpl, - VideoCaptureFlutterApiImpl? videoCaptureFlutterApiImpl, - ExposureStateFlutterApiImpl? exposureStateFlutterApiImpl, - ZoomStateFlutterApiImpl? zoomStateFlutterApiImpl, - LiveDataFlutterApiImpl? liveDataFlutterApiImpl, - ObserverFlutterApiImpl? observerFlutterApiImpl, - ImageProxyFlutterApiImpl? imageProxyFlutterApiImpl, - PlaneProxyFlutterApiImpl? planeProxyFlutterApiImpl, - AnalyzerFlutterApiImpl? analyzerFlutterApiImpl, - CameraControlFlutterApiImpl? cameraControlFlutterApiImpl, - FocusMeteringResultFlutterApiImpl? focusMeteringResultFlutterApiImpl, - Camera2CameraInfoFlutterApiImpl? camera2CameraInfoFlutterApiImpl}) { - this.javaObjectFlutterApiImpl = - javaObjectFlutterApiImpl ?? JavaObjectFlutterApiImpl(); - this.cameraInfoFlutterApiImpl = - cameraInfoFlutterApiImpl ?? CameraInfoFlutterApiImpl(); - this.cameraSelectorFlutterApiImpl = - cameraSelectorFlutterApiImpl ?? CameraSelectorFlutterApiImpl(); - this.processCameraProviderFlutterApiImpl = - processCameraProviderFlutterApiImpl ?? - ProcessCameraProviderFlutterApiImpl(); - this.cameraFlutterApiImpl = cameraFlutterApiImpl ?? CameraFlutterApiImpl(); - this.systemServicesFlutterApiImpl = - systemServicesFlutterApiImpl ?? SystemServicesFlutterApiImpl(); - this.deviceOrientationManagerFlutterApiImpl = - deviceOrientationManagerFlutterApiImpl ?? - DeviceOrientationManagerFlutterApiImpl(); - this.cameraStateErrorFlutterApiImpl = - cameraStateErrorFlutterApiImpl ?? CameraStateErrorFlutterApiImpl(); - this.cameraStateFlutterApiImpl = - cameraStateFlutterApiImpl ?? CameraStateFlutterApiImpl(); - this.pendingRecordingFlutterApiImpl = - pendingRecordingFlutterApiImpl ?? PendingRecordingFlutterApiImpl(); - this.recordingFlutterApiImpl = - recordingFlutterApiImpl ?? RecordingFlutterApiImpl(); - this.recorderFlutterApiImpl = - recorderFlutterApiImpl ?? RecorderFlutterApiImpl(); - this.videoCaptureFlutterApiImpl = - videoCaptureFlutterApiImpl ?? VideoCaptureFlutterApiImpl(); - this.exposureStateFlutterApiImpl = - exposureStateFlutterApiImpl ?? ExposureStateFlutterApiImpl(); - this.zoomStateFlutterApiImpl = - zoomStateFlutterApiImpl ?? ZoomStateFlutterApiImpl(); - this.liveDataFlutterApiImpl = - liveDataFlutterApiImpl ?? LiveDataFlutterApiImpl(); - this.observerFlutterApiImpl = - observerFlutterApiImpl ?? ObserverFlutterApiImpl(); - this.analyzerFlutterApiImpl = - analyzerFlutterApiImpl ?? AnalyzerFlutterApiImpl(); - this.imageProxyFlutterApiImpl = - imageProxyFlutterApiImpl ?? ImageProxyFlutterApiImpl(); - this.planeProxyFlutterApiImpl = - planeProxyFlutterApiImpl ?? PlaneProxyFlutterApiImpl(); - this.cameraControlFlutterApiImpl = - cameraControlFlutterApiImpl ?? CameraControlFlutterApiImpl(); - this.focusMeteringResultFlutterApiImpl = - focusMeteringResultFlutterApiImpl ?? - FocusMeteringResultFlutterApiImpl(); - this.camera2CameraInfoFlutterApiImpl = - camera2CameraInfoFlutterApiImpl ?? Camera2CameraInfoFlutterApiImpl(); - } - - static bool _haveBeenSetUp = false; - - /// Mutable instance containing all Flutter Apis for Android CameraX Camera. - /// - /// This should only be changed for testing purposes. - static AndroidCameraXCameraFlutterApis instance = - AndroidCameraXCameraFlutterApis(); - - /// Handles callbacks methods for the native Java Object class. - late final JavaObjectFlutterApi javaObjectFlutterApiImpl; - - /// Flutter Api implementation for [CameraInfo]. - late final CameraInfoFlutterApiImpl cameraInfoFlutterApiImpl; - - /// Flutter Api implementation for [CameraSelector]. - late final CameraSelectorFlutterApiImpl cameraSelectorFlutterApiImpl; - - /// Flutter Api implementation for [ProcessCameraProvider]. - late final ProcessCameraProviderFlutterApiImpl - processCameraProviderFlutterApiImpl; - - /// Flutter Api implementation for [Camera]. - late final CameraFlutterApiImpl cameraFlutterApiImpl; - - /// Flutter Api implementation for [SystemServices]. - late final SystemServicesFlutterApiImpl systemServicesFlutterApiImpl; - - /// Flutter Api implementation for [DeviceOrientationManager]. - late final DeviceOrientationManagerFlutterApiImpl - deviceOrientationManagerFlutterApiImpl; - - /// Flutter Api implementation for [CameraStateError]. - late final CameraStateErrorFlutterApiImpl? cameraStateErrorFlutterApiImpl; - - /// Flutter Api implementation for [CameraState]. - late final CameraStateFlutterApiImpl? cameraStateFlutterApiImpl; - - /// Flutter Api implementation for [LiveData]. - late final LiveDataFlutterApiImpl? liveDataFlutterApiImpl; - - /// Flutter Api implementation for [Observer]. - late final ObserverFlutterApiImpl? observerFlutterApiImpl; - - /// Flutter Api for [PendingRecording]. - late final PendingRecordingFlutterApiImpl pendingRecordingFlutterApiImpl; - - /// Flutter Api for [Recording]. - late final RecordingFlutterApiImpl recordingFlutterApiImpl; - - /// Flutter Api for [Recorder]. - late final RecorderFlutterApiImpl recorderFlutterApiImpl; - - /// Flutter Api for [VideoCapture]. - late final VideoCaptureFlutterApiImpl videoCaptureFlutterApiImpl; - - /// Flutter Api for [ExposureState]. - late final ExposureStateFlutterApiImpl exposureStateFlutterApiImpl; - - /// Flutter Api for [ZoomState]. - late final ZoomStateFlutterApiImpl zoomStateFlutterApiImpl; - - /// Flutter Api implementation for [Analyzer]. - late final AnalyzerFlutterApiImpl analyzerFlutterApiImpl; - - /// Flutter Api implementation for [ImageProxy]. - late final ImageProxyFlutterApiImpl imageProxyFlutterApiImpl; - - /// Flutter Api implementation for [PlaneProxy]. - late final PlaneProxyFlutterApiImpl planeProxyFlutterApiImpl; - - /// Flutter Api implementation for [CameraControl]. - late final CameraControlFlutterApiImpl cameraControlFlutterApiImpl; - - /// Flutter Api implementation for [FocusMeteringResult]. - late final FocusMeteringResultFlutterApiImpl - focusMeteringResultFlutterApiImpl; - - /// Flutter Api implementation for [Camera2CameraInfo]. - late final Camera2CameraInfoFlutterApiImpl camera2CameraInfoFlutterApiImpl; - - /// Ensures all the Flutter APIs have been setup to receive calls from native code. - void ensureSetUp() { - if (!_haveBeenSetUp) { - JavaObjectFlutterApi.setup(javaObjectFlutterApiImpl); - CameraInfoFlutterApi.setup(cameraInfoFlutterApiImpl); - CameraSelectorFlutterApi.setup(cameraSelectorFlutterApiImpl); - ProcessCameraProviderFlutterApi.setup( - processCameraProviderFlutterApiImpl); - CameraFlutterApi.setup(cameraFlutterApiImpl); - SystemServicesFlutterApi.setup(systemServicesFlutterApiImpl); - DeviceOrientationManagerFlutterApi.setup( - deviceOrientationManagerFlutterApiImpl); - CameraStateErrorFlutterApi.setup(cameraStateErrorFlutterApiImpl); - CameraStateFlutterApi.setup(cameraStateFlutterApiImpl); - PendingRecordingFlutterApi.setup(pendingRecordingFlutterApiImpl); - RecordingFlutterApi.setup(recordingFlutterApiImpl); - RecorderFlutterApi.setup(recorderFlutterApiImpl); - VideoCaptureFlutterApi.setup(videoCaptureFlutterApiImpl); - ExposureStateFlutterApi.setup(exposureStateFlutterApiImpl); - ZoomStateFlutterApi.setup(zoomStateFlutterApiImpl); - AnalyzerFlutterApi.setup(analyzerFlutterApiImpl); - ImageProxyFlutterApi.setup(imageProxyFlutterApiImpl); - PlaneProxyFlutterApi.setup(planeProxyFlutterApiImpl); - LiveDataFlutterApi.setup(liveDataFlutterApiImpl); - ObserverFlutterApi.setup(observerFlutterApiImpl); - CameraControlFlutterApi.setup(cameraControlFlutterApiImpl); - FocusMeteringResultFlutterApi.setup(focusMeteringResultFlutterApiImpl); - Camera2CameraInfoFlutterApi.setup(camera2CameraInfoFlutterApiImpl); - _haveBeenSetUp = true; - } - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/aspect_ratio_strategy.dart b/packages/camera/camera_android_camerax/lib/src/aspect_ratio_strategy.dart deleted file mode 100644 index 621f4ddb2edc..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/aspect_ratio_strategy.dart +++ /dev/null @@ -1,138 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart'; -import 'package:meta/meta.dart' show immutable; - -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; - -/// The aspect ratio of a UseCase. -/// -/// Aspect ratio is the ratio of width to height. -/// -/// See https://developer.android.com/reference/androidx/camera/core/AspectRatio. -class AspectRatio { - AspectRatio._(); - - /// 4:3 standard aspect ratio. - /// - /// See https://developer.android.com/reference/androidx/camera/core/AspectRatio#RATIO_4_3(). - static const int ratio4To3 = 0; - - /// 16:9 standard aspect ratio. - /// - /// See https://developer.android.com/reference/androidx/camera/core/AspectRatio#RATIO_16_9(). - static const int ratio16To9 = 1; - - /// The aspect ratio representing no preference for aspect ratio. - /// - /// See https://developer.android.com/reference/androidx/camera/core/AspectRatio#RATIO_DEFAULT(). - static const int ratioDefault = -1; -} - -/// The aspect ratio strategy defines the sequence of aspect ratios that are -/// used to select the best size for a particular image. -/// -/// See https://developer.android.com/reference/androidx/camera/core/resolutionselector/AspectRatioStrategy. -@immutable -class AspectRatioStrategy extends JavaObject { - /// Construct a [AspectRatioStrategy]. - AspectRatioStrategy({ - required this.preferredAspectRatio, - required this.fallbackRule, - super.binaryMessenger, - super.instanceManager, - }) : _api = _AspectRatioStrategyHostApiImpl( - instanceManager: instanceManager, - binaryMessenger: binaryMessenger, - ), - super.detached() { - _api.createFromInstances(this, preferredAspectRatio, fallbackRule); - } - - /// Instantiates a [AspectRatioStrategy] without creating and attaching to an - /// instance of the associated native class. - /// - /// This should only be used outside of tests by subclasses created by this - /// library or to create a copy for an [InstanceManager]. - AspectRatioStrategy.detached({ - required this.preferredAspectRatio, - required this.fallbackRule, - super.binaryMessenger, - super.instanceManager, - }) : _api = _AspectRatioStrategyHostApiImpl( - instanceManager: instanceManager, - binaryMessenger: binaryMessenger, - ), - super.detached(); - - /// CameraX doesn't fall back to select sizes of any other aspect ratio when - /// this fallback rule is used. - /// - /// See https://developer.android.com/reference/androidx/camera/core/resolutionselector/AspectRatioStrategy#FALLBACK_RULE_NONE(). - static const int fallbackRuleNone = 0; - - /// CameraX automatically chooses the next best aspect ratio which contains - /// the closest field of view (FOV) of the camera sensor, from the remaining - /// options. - /// - /// See https://developer.android.com/reference/androidx/camera/core/resolutionselector/AspectRatioStrategy#FALLBACK_RULE_AUTO(). - static const int fallbackRuleAuto = 1; - - final _AspectRatioStrategyHostApiImpl _api; - - /// The preferred aspect ratio captured by the camera. - final int preferredAspectRatio; - - /// The specified fallback rule for choosing the aspect ratio when the - /// preferred aspect ratio is not available. - final int fallbackRule; -} - -/// Host API implementation of [AspectRatioStrategy]. -class _AspectRatioStrategyHostApiImpl extends AspectRatioStrategyHostApi { - /// Constructs an [_AspectRatioStrategyHostApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - _AspectRatioStrategyHostApiImpl({ - this.binaryMessenger, - InstanceManager? instanceManager, - }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager, - super(binaryMessenger: binaryMessenger); - - /// Receives binary data across the Flutter platform barrier. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager instanceManager; - - /// Creates a [AspectRatioStrategy] on the native side with the preferred - /// aspect ratio and fallback rule specified. - Future createFromInstances( - AspectRatioStrategy instance, - int preferredAspectRatio, - int fallbackRule, - ) { - return create( - instanceManager.addDartCreatedInstance( - instance, - onCopy: (AspectRatioStrategy original) => AspectRatioStrategy.detached( - preferredAspectRatio: original.preferredAspectRatio, - fallbackRule: original.fallbackRule, - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ), - ), - preferredAspectRatio, - fallbackRule, - ); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/camera.dart b/packages/camera/camera_android_camerax/lib/src/camera.dart deleted file mode 100644 index 1001450353be..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/camera.dart +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart' show BinaryMessenger; -import 'package:meta/meta.dart' show immutable; - -import 'android_camera_camerax_flutter_api_impls.dart'; -import 'camera_control.dart'; -import 'camera_info.dart'; -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; - -/// The interface used to control the flow of data of use cases, control the -/// camera, and publich the state of the camera. -/// -/// See https://developer.android.com/reference/androidx/camera/core/Camera. -@immutable -class Camera extends JavaObject { - /// Constructs a [Camera] that is not automatically attached to a native object. - Camera.detached( - {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager}) - : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = _CameraHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - } - - late final _CameraHostApiImpl _api; - - /// Retrieves the [CameraInfo] instance that contains information about this - /// instance. - Future getCameraInfo() async { - return _api.getCameraInfoFromInstance(this); - } - - /// Retrieves the [CameraControl] instance that provides asynchronous - /// operations like zoom and focus & metering for this instance. - Future getCameraControl() async { - return _api.getCameraControlFromInstance(this); - } -} - -/// Host API implementation of [Camera]. -class _CameraHostApiImpl extends CameraHostApi { - /// Constructs a [_CameraHostApiImpl]. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. - _CameraHostApiImpl({this.binaryMessenger, InstanceManager? instanceManager}) - : super(binaryMessenger: binaryMessenger) { - this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - } - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default BinaryMessenger will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - late final InstanceManager instanceManager; - - /// Gets the [CameraInfo] associated with the specified [Camera] instance. - Future getCameraInfoFromInstance(Camera instance) async { - final int identifier = instanceManager.getIdentifier(instance)!; - final int cameraInfoId = await getCameraInfo(identifier); - - return instanceManager - .getInstanceWithWeakReference(cameraInfoId)!; - } - - /// Gets the [CameraControl] associated with the specified [Camera] instance. - Future getCameraControlFromInstance(Camera instance) async { - final int identifier = instanceManager.getIdentifier(instance)!; - final int cameraControlId = await getCameraControl(identifier); - - return instanceManager - .getInstanceWithWeakReference(cameraControlId)!; - } -} - -/// Flutter API implementation of [Camera]. -class CameraFlutterApiImpl implements CameraFlutterApi { - /// Constructs a [CameraFlutterApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - CameraFlutterApiImpl({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - }) : _binaryMessenger = binaryMessenger, - _instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - - /// Receives binary data across the Flutter platform barrier. - final BinaryMessenger? _binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager _instanceManager; - - @override - void create(int identifier) { - _instanceManager.addHostCreatedInstance( - Camera.detached( - binaryMessenger: _binaryMessenger, instanceManager: _instanceManager), - identifier, - onCopy: (Camera original) { - return Camera.detached( - binaryMessenger: _binaryMessenger, - instanceManager: _instanceManager); - }, - ); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/camera2_camera_control.dart b/packages/camera/camera_android_camerax/lib/src/camera2_camera_control.dart deleted file mode 100644 index 87fa9734a5b0..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/camera2_camera_control.dart +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart'; -import 'package:meta/meta.dart' show immutable; - -import 'android_camera_camerax_flutter_api_impls.dart'; -import 'camera_control.dart'; -import 'camerax_library.g.dart'; -import 'capture_request_options.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; -import 'system_services.dart'; - -/// Class that provides ability to interoperate with android.hardware.camera2 -/// APIs and apply options to its specific controls like capture request -/// options. -/// -/// See https://developer.android.com/reference/androidx/camera/camera2/interop/Camera2CameraControl#from(androidx.camera.core.CameraControl). -@immutable -class Camera2CameraControl extends JavaObject { - /// Creates a [Camera2CameraControl]. - Camera2CameraControl( - {BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - required this.cameraControl}) - : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = _Camera2CameraControlHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - _api.createFromInstances(this, cameraControl); - } - - /// Constructs a [Camera2CameraControl] that is not automatically attached to a - /// native object. - Camera2CameraControl.detached( - {BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - required this.cameraControl}) - : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = _Camera2CameraControlHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - } - - late final _Camera2CameraControlHostApiImpl _api; - - /// The [CameraControl] info that this instance is based on. - /// - /// Note that options specified with this [Camera2CameraControl] instance will - /// have higher priority than [cameraControl]. - final CameraControl cameraControl; - - /// Updates capture session with options that the specified - /// [CaptureRequestOptions] contains. - /// - /// Options will be merged with existing options, and if conflicting with what - /// was previously set, these options will override those pre-existing. Once - /// merged, these values will be submitted with every repeating and single - /// capture request issued by CameraX. - Future addCaptureRequestOptions( - CaptureRequestOptions captureRequestOptions) { - return _api.addCaptureRequestOptionsFromInstances( - this, captureRequestOptions); - } -} - -/// Host API implementation of [Camera2CameraControl]. -class _Camera2CameraControlHostApiImpl extends Camera2CameraControlHostApi { - /// Constructs a [_Camera2CameraControlHostApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - _Camera2CameraControlHostApiImpl({ - this.binaryMessenger, - InstanceManager? instanceManager, - }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager, - super(binaryMessenger: binaryMessenger); - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default [BinaryMessenger] will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager instanceManager; - - /// Creates a [Camera2CameraControl] instance derived from the specified - /// [CameraControl] instance. - Future createFromInstances( - Camera2CameraControl instance, - CameraControl cameraControl, - ) { - return create( - instanceManager.addDartCreatedInstance( - instance, - onCopy: (Camera2CameraControl original) => - Camera2CameraControl.detached( - cameraControl: original.cameraControl, - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ), - ), - instanceManager.getIdentifier(cameraControl)!, - ); - } - - /// Updates capture session corresponding to the specified - /// [Camera2CameraControl] instance with options that the specified - /// [CaptureRequestOptions] contains. - Future addCaptureRequestOptionsFromInstances( - Camera2CameraControl instance, - CaptureRequestOptions captureRequestOptions, - ) async { - try { - return addCaptureRequestOptions( - instanceManager.getIdentifier(instance)!, - instanceManager.getIdentifier(captureRequestOptions)!, - ); - } on PlatformException catch (e) { - SystemServices.cameraErrorStreamController.add(e.message ?? - 'The camera was unable to set new capture request options due to new options being unavailable or the camera being closed.'); - } - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/camera2_camera_info.dart b/packages/camera/camera_android_camerax/lib/src/camera2_camera_info.dart deleted file mode 100644 index 88b44238f3b9..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/camera2_camera_info.dart +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'dart:async'; - -import 'package:flutter/services.dart' show BinaryMessenger; -import 'package:meta/meta.dart' show immutable; - -import 'android_camera_camerax_flutter_api_impls.dart'; -import 'camera_info.dart'; -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; - -/// Interface for retrieving Camera2-related camera information. -/// -/// See https://developer.android.com/reference/androidx/camera/camera2/interop/Camera2CameraInfo. -@immutable -class Camera2CameraInfo extends JavaObject { - /// Constructs a [Camera2CameraInfo] that is not automatically attached to a native object. - Camera2CameraInfo.detached( - {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager}) - : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = _Camera2CameraInfoHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - } - - late final _Camera2CameraInfoHostApiImpl _api; - - /// Retrieves [Camera2CameraInfo] instance from [cameraInfo]. - static Future from(CameraInfo cameraInfo, - {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager}) { - final _Camera2CameraInfoHostApiImpl api = _Camera2CameraInfoHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - return api.fromInstances(cameraInfo); - } - - /// Retrieves the value of `CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL` - /// for the device to which this instance pertains to. - /// - /// See https://developer.android.com/reference/android/hardware/camera2/CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL - /// for more information. - Future getSupportedHardwareLevel() => - _api.getSupportedHardwareLevelFromInstance(this); - - /// Gets the camera ID. - /// - /// The ID may change based on the internal configuration of the camera to which - /// this instances pertains. - Future getCameraId() => _api.getCameraIdFromInstance(this); - - /// Retrieves the orientation of the camera sensor. - Future getSensorOrientation() => - _api.getSensorOrientationFromInstance(this); -} - -/// Host API implementation of [Camera2CameraInfo]. -class _Camera2CameraInfoHostApiImpl extends Camera2CameraInfoHostApi { - /// Constructs a [_Camera2CameraInfoHostApiImpl]. - _Camera2CameraInfoHostApiImpl( - {this.binaryMessenger, InstanceManager? instanceManager}) - : instanceManager = instanceManager ?? JavaObject.globalInstanceManager, - super(binaryMessenger: binaryMessenger); - - /// Maintains instances stored to communicate with native language objects. - late final InstanceManager instanceManager; - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default [BinaryMessenger] will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Gets sensor orientation degrees of the specified [CameraInfo] instance. - Future fromInstances( - CameraInfo cameraInfo, - ) async { - final int? cameraInfoIdentifier = instanceManager.getIdentifier(cameraInfo); - return instanceManager.getInstanceWithWeakReference( - await createFrom(cameraInfoIdentifier!))!; - } - - Future getSupportedHardwareLevelFromInstance( - Camera2CameraInfo instance) { - final int? identifier = instanceManager.getIdentifier(instance); - return getSupportedHardwareLevel(identifier!); - } - - Future getCameraIdFromInstance(Camera2CameraInfo instance) { - final int? identifier = instanceManager.getIdentifier(instance); - return getCameraId(identifier!); - } - - Future getSensorOrientationFromInstance(Camera2CameraInfo instance) { - final int? identifier = instanceManager.getIdentifier(instance); - return getSensorOrientation(identifier!); - } -} - -/// Flutter API Implementation of [Camera2CameraInfo]. -class Camera2CameraInfoFlutterApiImpl implements Camera2CameraInfoFlutterApi { - /// Constructs an [Camera2CameraInfoFlutterApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - Camera2CameraInfoFlutterApiImpl({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - }) : _binaryMessenger = binaryMessenger, - _instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - - /// Receives binary data across the Flutter platform barrier. - final BinaryMessenger? _binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager _instanceManager; - - @override - void create(int identifier) { - _instanceManager.addHostCreatedInstance( - Camera2CameraInfo.detached( - binaryMessenger: _binaryMessenger, instanceManager: _instanceManager), - identifier, - onCopy: (Camera2CameraInfo original) { - return Camera2CameraInfo.detached( - binaryMessenger: _binaryMessenger, - instanceManager: _instanceManager); - }, - ); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/camera_control.dart b/packages/camera/camera_android_camerax/lib/src/camera_control.dart deleted file mode 100644 index 0a307f3afc4a..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/camera_control.dart +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart' show BinaryMessenger, PlatformException; -import 'package:meta/meta.dart' show immutable; - -import 'android_camera_camerax_flutter_api_impls.dart'; -import 'camerax_library.g.dart'; -import 'focus_metering_action.dart'; -import 'focus_metering_result.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; -import 'system_services.dart'; - -/// The interface that provides asynchronous operations like zoom and focus & -/// metering, which affects output of all [UseCase]s currently bound to the -/// corresponding [Camera] instance. -/// -/// See https://developer.android.com/reference/androidx/camera/core/CameraControl. -@immutable -class CameraControl extends JavaObject { - /// Constructs a [CameraControl] that is not automatically attached to a native object. - CameraControl.detached( - {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager}) - : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = _CameraControlHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - } - - late final _CameraControlHostApiImpl _api; - - /// Enables or disables the torch of related [Camera] instance. - /// - /// If the torch mode was unable to be changed, an error message will be - /// added to [SystemServices.cameraErrorStreamController]. - Future enableTorch(bool torch) async { - return _api.enableTorchFromInstance(this, torch); - } - - /// Sets zoom of related [Camera] by ratio. - /// - /// Ratio should be between what the `minZoomRatio` and `maxZoomRatio` of the - /// [ZoomState] of the [CameraInfo] instance that is retrievable from the same - /// [Camera] instance; otherwise, an error message will be added to - /// [SystemServices.cameraErrorStreamController]. - Future setZoomRatio(double ratio) async { - return _api.setZoomRatioFromInstance(this, ratio); - } - - /// Starts a focus and metering action configured by the [FocusMeteringAction]. - /// - /// Will trigger an auto focus action and enable auto focus/auto exposure/ - /// auto white balance metering regions. - /// - /// Only one [FocusMeteringAction] is allowed to run at a time; if multiple - /// are executed in a row, only the latest one will work and other actions - /// will be canceled. - /// - /// Returns null if focus and metering could not be started. - Future startFocusAndMetering( - FocusMeteringAction action) { - return _api.startFocusAndMeteringFromInstance(this, action); - } - - /// Cancels current [FocusMeteringAction] and clears auto focus/auto exposure/ - /// auto white balance regions. - Future cancelFocusAndMetering() => - _api.cancelFocusAndMeteringFromInstance(this); - - /// Sets the exposure compensation value for related [Camera] and returns the - /// new target exposure value. - /// - /// The exposure compensation value set on the camera must be within the range - /// of the current [ExposureState]'s `exposureCompensationRange` for the call - /// to succeed. - /// - /// Only one [setExposureCompensationIndex] is allowed to run at a time; if - /// multiple are executed in a row, only the latest setting will be kept in - /// the camera. - /// - /// Returns null if the exposure compensation index failed to be set. - Future setExposureCompensationIndex(int index) async { - return _api.setExposureCompensationIndexFromInstance(this, index); - } -} - -/// Host API implementation of [CameraControl]. -class _CameraControlHostApiImpl extends CameraControlHostApi { - /// Constructs a [_CameraControlHostApiImpl]. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. - _CameraControlHostApiImpl( - {this.binaryMessenger, InstanceManager? instanceManager}) - : super(binaryMessenger: binaryMessenger) { - this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - } - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default BinaryMessenger will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - late final InstanceManager instanceManager; - - /// Enables or disables the torch for the specified [CameraControl] instance. - Future enableTorchFromInstance( - CameraControl instance, bool torch) async { - final int identifier = instanceManager.getIdentifier(instance)!; - try { - await enableTorch(identifier, torch); - } on PlatformException catch (e) { - SystemServices.cameraErrorStreamController - .add(e.message ?? 'The camera was unable to change torch modes.'); - } - } - - /// Sets zoom of specified [CameraControl] instance by ratio. - Future setZoomRatioFromInstance( - CameraControl instance, double ratio) async { - final int identifier = instanceManager.getIdentifier(instance)!; - try { - await setZoomRatio(identifier, ratio); - } on PlatformException catch (e) { - SystemServices.cameraErrorStreamController.add(e.message ?? - 'Zoom ratio was unable to be set. If ratio was not out of range, newer value may have been set; otherwise, the camera may be closed.'); - } - } - - /// Starts a focus and metering action configured by the [FocusMeteringAction] - /// for the specified [CameraControl] instance. - Future startFocusAndMeteringFromInstance( - CameraControl instance, FocusMeteringAction action) async { - final int cameraControlIdentifier = - instanceManager.getIdentifier(instance)!; - final int actionIdentifier = instanceManager.getIdentifier(action)!; - try { - final int? focusMeteringResultId = await startFocusAndMetering( - cameraControlIdentifier, actionIdentifier); - if (focusMeteringResultId == null) { - SystemServices.cameraErrorStreamController.add( - 'Starting focus and metering was canceled due to the camera being closed or a new request being submitted.'); - return Future.value(); - } - return instanceManager.getInstanceWithWeakReference( - focusMeteringResultId); - } on PlatformException catch (e) { - SystemServices.cameraErrorStreamController - .add(e.message ?? 'Starting focus and metering failed.'); - // Surfacing error to differentiate an operation cancellation from an - // illegal argument exception at a plugin layer. - rethrow; - } - } - - /// Cancels current [FocusMeteringAction] and clears AF/AE/AWB regions for the - /// specified [CameraControl] instance. - Future cancelFocusAndMeteringFromInstance( - CameraControl instance) async { - final int identifier = instanceManager.getIdentifier(instance)!; - await cancelFocusAndMetering(identifier); - } - - /// Sets exposure compensation index for specified [CameraControl] instance - /// and returns the new target exposure value. - Future setExposureCompensationIndexFromInstance( - CameraControl instance, int index) async { - final int identifier = instanceManager.getIdentifier(instance)!; - try { - final int? exposureCompensationIndex = - await setExposureCompensationIndex(identifier, index); - if (exposureCompensationIndex == null) { - SystemServices.cameraErrorStreamController.add( - 'Setting exposure compensation index was canceled due to the camera being closed or a new request being submitted.'); - return Future.value(); - } - return exposureCompensationIndex; - } on PlatformException catch (e) { - SystemServices.cameraErrorStreamController.add(e.message ?? - 'Setting the camera exposure compensation index failed.'); - // Surfacing error to plugin layer to maintain consistency of - // setExposureOffset implementation across platform implementations. - rethrow; - } - } -} - -/// Flutter API implementation of [CameraControl]. -class CameraControlFlutterApiImpl extends CameraControlFlutterApi { - /// Constructs a [CameraControlFlutterApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - CameraControlFlutterApiImpl({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - }) : _binaryMessenger = binaryMessenger, - _instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - - /// Receives binary data across the Flutter platform barrier. - final BinaryMessenger? _binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager _instanceManager; - - @override - void create(int identifier) { - _instanceManager.addHostCreatedInstance( - CameraControl.detached( - binaryMessenger: _binaryMessenger, instanceManager: _instanceManager), - identifier, - onCopy: (CameraControl original) { - return CameraControl.detached( - binaryMessenger: _binaryMessenger, - instanceManager: _instanceManager); - }, - ); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/camera_info.dart b/packages/camera/camera_android_camerax/lib/src/camera_info.dart deleted file mode 100644 index 6c0a62f9fd5d..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/camera_info.dart +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'dart:async'; - -import 'package:flutter/services.dart' show BinaryMessenger; -import 'package:meta/meta.dart' show immutable; - -import 'android_camera_camerax_flutter_api_impls.dart'; -import 'camera_state.dart'; -import 'camerax_library.g.dart'; -import 'exposure_state.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; -import 'live_data.dart'; -import 'zoom_state.dart'; - -/// The metadata of a camera. -/// -/// See https://developer.android.com/reference/androidx/camera/core/CameraInfo. -@immutable -class CameraInfo extends JavaObject { - /// Constructs a [CameraInfo] that is not automatically attached to a native object. - CameraInfo.detached( - {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager}) - : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = _CameraInfoHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - } - - late final _CameraInfoHostApiImpl _api; - - /// Gets sensor orientation degrees of the camera. - Future getSensorRotationDegrees() => - _api.getSensorRotationDegreesFromInstance(this); - - /// Starts listening for the camera closing. - Future> getCameraState() => - _api.getCameraStateFromInstance(this); - - /// Gets the exposure state of the camera. - Future getExposureState() => - _api.getExposureStateFromInstance(this); - - /// Gets the live zoom state of the camera. - Future> getZoomState() => - _api.getZoomStateFromInstance(this); -} - -/// Host API implementation of [CameraInfo]. -class _CameraInfoHostApiImpl extends CameraInfoHostApi { - /// Constructs a [_CameraInfoHostApiImpl]. - _CameraInfoHostApiImpl( - {super.binaryMessenger, InstanceManager? instanceManager}) { - this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - } - - /// Maintains instances stored to communicate with native language objects. - late final InstanceManager instanceManager; - - /// Gets sensor orientation degrees of the specified [CameraInfo] instance. - Future getSensorRotationDegreesFromInstance( - CameraInfo instance, - ) async { - final int sensorRotationDegrees = await getSensorRotationDegrees( - instanceManager.getIdentifier(instance)!); - return sensorRotationDegrees; - } - - /// Gets the [LiveData] that represents the state of the camera - /// to which the CameraInfo [instance] pertains. - Future> getCameraStateFromInstance( - CameraInfo instance) async { - final int? identifier = instanceManager.getIdentifier(instance); - final int liveCameraStateId = await getCameraState(identifier!); - final LiveData liveCameraState = - instanceManager.getInstanceWithWeakReference>( - liveCameraStateId)!; - return liveCameraState; - } - - /// Gets the [ExposureState] of the specified [CameraInfo] instance. - Future getExposureStateFromInstance( - CameraInfo instance) async { - final int? identifier = instanceManager.getIdentifier(instance); - final int exposureStateIdentifier = await getExposureState(identifier!); - return instanceManager - .getInstanceWithWeakReference(exposureStateIdentifier)!; - } - - /// Gets the [LiveData] of the specified [CameraInfo] instance. - Future> getZoomStateFromInstance( - CameraInfo instance) async { - final int? identifier = instanceManager.getIdentifier(instance); - final int zoomStateIdentifier = await getZoomState(identifier!); - return instanceManager.getInstanceWithWeakReference>( - zoomStateIdentifier)!; - } -} - -/// Flutter API implementation of [CameraInfo]. -class CameraInfoFlutterApiImpl extends CameraInfoFlutterApi { - /// Constructs a [CameraInfoFlutterApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - CameraInfoFlutterApiImpl({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - }) : _binaryMessenger = binaryMessenger, - _instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - - /// Receives binary data across the Flutter platform barrier. - final BinaryMessenger? _binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager _instanceManager; - - @override - void create(int identifier) { - _instanceManager.addHostCreatedInstance( - CameraInfo.detached( - binaryMessenger: _binaryMessenger, instanceManager: _instanceManager), - identifier, - onCopy: (CameraInfo original) { - return CameraInfo.detached( - binaryMessenger: _binaryMessenger, - instanceManager: _instanceManager); - }, - ); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/camera_metadata.dart b/packages/camera/camera_android_camerax/lib/src/camera_metadata.dart deleted file mode 100644 index 65098b747c67..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/camera_metadata.dart +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:meta/meta.dart' show immutable; - -/// Base class for camera controls and information. -/// -/// See https://developer.android.com/reference/android/hardware/camera2/CameraMetadata. -@immutable -class CameraMetadata { - /// Constant that specifies a camera device does not have enough to quality as - /// a [infoSupportedHardwareLevelFull] level device or better. - /// - /// See https://developer.android.com/reference/android/hardware/camera2/CameraMetadata#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED. - static const int infoSupportedHardwareLevelLimited = 0; - - /// Constant that specifies a camera device is capable of supporting advanced - /// imaging applications. - /// - /// See https://developer.android.com/reference/android/hardware/camera2/CameraMetadata#INFO_SUPPORTED_HARDWARE_LEVEL_FULL. - static const int infoSupportedHardwareLevelFull = 1; - - /// Constant that specifies a camera device is running in backward - /// compatibility mode. - /// - /// See https://developer.android.com/reference/android/hardware/camera2/CameraMetadata#INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY. - static const int infoSupportedHardwareLevelLegacy = 2; - - /// Constant that specifies a camera device is capable of YUV reprocessing and - /// RAW data capture in addition to [infoSupportedHardwareLevelFull] level - /// capabilities. - /// - /// See https://developer.android.com/reference/android/hardware/camera2/CameraMetadata#INFO_SUPPORTED_HARDWARE_LEVEL_3. - static const int infoSupportedHardwareLevel3 = 3; - - /// Constant taht specifies a camera device is backed by an external camera - /// connected to this Android device. - /// - /// See https://developer.android.com/reference/android/hardware/camera2/CameraMetadata#INFO_SUPPORTED_HARDWARE_LEVEL_EXTERNAL. - static const int infoSupportedHardwareLevelExternal = 4; -} diff --git a/packages/camera/camera_android_camerax/lib/src/camera_selector.dart b/packages/camera/camera_android_camerax/lib/src/camera_selector.dart deleted file mode 100644 index 0e489d42457f..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/camera_selector.dart +++ /dev/null @@ -1,203 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart'; -import 'package:meta/meta.dart' show immutable; - -import 'android_camera_camerax_flutter_api_impls.dart'; -import 'camera_info.dart'; -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; - -/// Selects a camera for use. -/// -/// See https://developer.android.com/reference/androidx/camera/core/CameraSelector. -@immutable -class CameraSelector extends JavaObject { - /// Creates a [CameraSelector]. - CameraSelector( - {BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - this.lensFacing}) - : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = CameraSelectorHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - _api.createFromInstance(this, lensFacing); - } - - /// Creates a detached [CameraSelector]. - CameraSelector.detached( - {BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - this.lensFacing}) - : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = CameraSelectorHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - } - - late final CameraSelectorHostApiImpl _api; - - /// ID for front facing lens. - /// - /// See https://developer.android.com/reference/androidx/camera/core/CameraSelector#LENS_FACING_FRONT(). - static const int lensFacingFront = 0; - - /// ID for back facing lens. - /// - /// See https://developer.android.com/reference/androidx/camera/core/CameraSelector#LENS_FACING_BACK(). - static const int lensFacingBack = 1; - - /// ID for external lens. - /// - /// See https://developer.android.com/reference/androidx/camera/core/CameraSelector#LENS_FACING_EXTERNAL(). - static const int lensFacingExternal = 2; - - /// ID for unknown lens. - /// - /// See https://developer.android.com/reference/androidx/camera/core/CameraSelector#LENS_FACING_UNKNOWN(). - static const int lensFacingUnknown = -1; - - /// Selector for default front facing camera. - static CameraSelector getDefaultFrontCamera({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - }) { - return CameraSelector( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - lensFacing: lensFacingFront, - ); - } - - /// Selector for default back facing camera. - static CameraSelector getDefaultBackCamera({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - }) { - return CameraSelector( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - lensFacing: lensFacingBack, - ); - } - - /// Lens direction of this selector. - final int? lensFacing; - - /// Filters available cameras based on provided [CameraInfo]s. - Future> filter(List cameraInfos) { - return _api.filterFromInstance(this, cameraInfos); - } -} - -/// Host API implementation of [CameraSelector]. -class CameraSelectorHostApiImpl extends CameraSelectorHostApi { - /// Constructs a [CameraSelectorHostApiImpl]. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an `InstanceManager` is being created. - CameraSelectorHostApiImpl( - {this.binaryMessenger, InstanceManager? instanceManager}) - : super(binaryMessenger: binaryMessenger) { - this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - } - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default BinaryMessenger will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - late final InstanceManager instanceManager; - - /// Creates a [CameraSelector] with the lens direction provided if specified. - void createFromInstance(CameraSelector instance, int? lensFacing) { - int? identifier = instanceManager.getIdentifier(instance); - identifier ??= instanceManager.addDartCreatedInstance(instance, - onCopy: (CameraSelector original) { - return CameraSelector.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - lensFacing: original.lensFacing); - }); - - create(identifier, lensFacing); - } - - /// Filters a list of [CameraInfo]s based on the [CameraSelector]. - Future> filterFromInstance( - CameraSelector instance, - List cameraInfos, - ) async { - int? identifier = instanceManager.getIdentifier(instance); - identifier ??= instanceManager.addDartCreatedInstance(instance, - onCopy: (CameraSelector original) { - return CameraSelector.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - lensFacing: original.lensFacing); - }); - - final List cameraInfoIds = cameraInfos - .map((CameraInfo info) => instanceManager.getIdentifier(info)!) - .toList(); - final List filteredCameraInfoIds = - await filter(identifier, cameraInfoIds); - if (filteredCameraInfoIds.isEmpty) { - return []; - } - return filteredCameraInfoIds - .map((int? id) => - instanceManager.getInstanceWithWeakReference(id!)!) - .toList(); - } -} - -/// Flutter API implementation of [CameraSelector]. -class CameraSelectorFlutterApiImpl implements CameraSelectorFlutterApi { - /// Constructs a [CameraSelectorFlutterApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - CameraSelectorFlutterApiImpl({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - }) : _binaryMessenger = binaryMessenger, - _instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - - /// Receives binary data across the Flutter platform barrier. - final BinaryMessenger? _binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager _instanceManager; - - @override - void create(int identifier, int? lensFacing) { - _instanceManager.addHostCreatedInstance( - CameraSelector.detached( - binaryMessenger: _binaryMessenger, - instanceManager: _instanceManager, - lensFacing: lensFacing), - identifier, - onCopy: (CameraSelector original) { - return CameraSelector.detached( - binaryMessenger: _binaryMessenger, - instanceManager: _instanceManager, - lensFacing: original.lensFacing); - }, - ); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/camera_state.dart b/packages/camera/camera_android_camerax/lib/src/camera_state.dart deleted file mode 100644 index 1e8586a4023c..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/camera_state.dart +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart'; -import 'package:meta/meta.dart'; - -import 'camera_state_error.dart'; -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; - -/// A snapshot of the camera state. -/// -/// See https://developer.android.com/reference/androidx/camera/core/CameraState. -@immutable -class CameraState extends JavaObject { - /// Constructs a [CameraState] that is not automatically attached to a native object. - CameraState.detached( - {super.binaryMessenger, - super.instanceManager, - required this.type, - this.error}) - : super.detached(); - - /// The type of state that the camera is in. - final CameraStateType type; - - /// The error that the camera has encountered, if any. - final CameraStateError? error; - - /// Error code indicating that the camera device is already in use. - /// - /// See https://developer.android.com/reference/androidx/camera/core/CameraState#ERROR_CAMERA_IN_USE() - static const int errorCameraInUse = 1; - - /// Error code indicating that the limit number of open cameras has been - /// reached. - /// - /// See https://developer.android.com/reference/androidx/camera/core/CameraState#ERROR_MAX_CAMERAS_IN_USE() - static const int errorMaxCamerasInUse = 2; - - /// Error code indicating that the camera device has encountered a recoverable - /// error. - /// - /// See https://developer.android.com/reference/androidx/camera/core/CameraState#ERROR_OTHER_RECOVERABLE_ERROR() - static const int errorOtherRecoverableError = 3; - - /// Error code inidcating that configuring the camera has failed. - /// - /// https://developer.android.com/reference/androidx/camera/core/CameraState#ERROR_STREAM_CONFIG() - static const int errorStreamConfig = 4; - - /// Error code indicating that the camera device could not be opened due to a - /// device policy. - /// - /// See https://developer.android.com/reference/androidx/camera/core/CameraState#ERROR_CAMERA_DISABLED() - static const int errorCameraDisabled = 5; - - /// Error code indicating that the camera device was closed due to a fatal - /// error. - /// - /// See https://developer.android.com/reference/androidx/camera/core/CameraState#ERROR_CAMERA_FATAL_ERROR() - static const int errorCameraFatalError = 6; - - /// Error code indicating that the camera could not be opened because - /// "Do Not Disturb" mode is enabled on devices affected by a bug in Android 9 - /// (API level 28). - /// - /// See https://developer.android.com/reference/androidx/camera/core/CameraState#ERROR_DO_NOT_DISTURB_MODE_ENABLED() - static const int errorDoNotDisturbModeEnabled = 7; -} - -/// Flutter API implementation for [CameraState]. -/// -/// This class may handle instantiating and adding Dart instances that are -/// attached to a native instance or receiving callback methods from an -/// overridden native class. -@protected -class CameraStateFlutterApiImpl implements CameraStateFlutterApi { - /// Constructs a [CameraStateFlutterApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - CameraStateFlutterApiImpl({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - }) : _binaryMessenger = binaryMessenger, - _instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - - /// Receives binary data across the Flutter platform barrier. - final BinaryMessenger? _binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager _instanceManager; - - @override - void create( - int identifier, - CameraStateTypeData type, - int? errorIdentifier, - ) { - _instanceManager.addHostCreatedInstance( - CameraState.detached( - type: type.value, - error: errorIdentifier == null - ? null - : _instanceManager.getInstanceWithWeakReference( - errorIdentifier, - ), - binaryMessenger: _binaryMessenger, - instanceManager: _instanceManager, - ), - identifier, - onCopy: (CameraState original) => CameraState.detached( - type: original.type, - error: original.error, - binaryMessenger: _binaryMessenger, - instanceManager: _instanceManager, - ), - ); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/camera_state_error.dart b/packages/camera/camera_android_camerax/lib/src/camera_state_error.dart deleted file mode 100644 index fedb85c9e8ad..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/camera_state_error.dart +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart'; -import 'package:meta/meta.dart'; - -import 'camera_state.dart'; -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; - -/// The error that a camera has encountered. -/// -/// See https://developer.android.com/reference/androidx/camera/core/CameraState.StateError. -@immutable -class CameraStateError extends JavaObject { - /// Constructs a [CameraStateError] that is not automatically attached to a native object. - CameraStateError.detached( - {super.binaryMessenger, super.instanceManager, required this.code}) - : super.detached(); - - /// The code of this error. - /// - /// Will map to one of the [CameraState] error codes that map to the CameraX - /// CameraState codes: - /// https://developer.android.com/reference/androidx/camera/core/CameraState#constants_1. - final int code; - - /// Gets a description of this error corresponding to its [code]. - /// - /// This is not directly provided by the CameraX library, but is determined - /// based on the description of the [code]. - /// - /// Provided for developers to use for error handling. - String getDescription() { - String description = ''; - switch (code) { - case CameraState.errorCameraInUse: - description = - 'The camera was already in use, possibly by a higher-priority camera client.'; - case CameraState.errorMaxCamerasInUse: - description = - 'The limit number of open cameras has been reached, and more cameras cannot be opened until other instances are closed.'; - case CameraState.errorOtherRecoverableError: - description = - 'The camera device has encountered a recoverable error. CameraX will attempt to recover from the error.'; - case CameraState.errorStreamConfig: - description = 'Configuring the camera has failed.'; - case CameraState.errorCameraDisabled: - description = - 'The camera device could not be opened due to a device policy. Thia may be caused by a client from a background process attempting to open the camera.'; - case CameraState.errorCameraFatalError: - description = - 'The camera was closed due to a fatal error. This may require the Android device be shut down and restarted to restore camera function or may indicate a persistent camera hardware problem.'; - case CameraState.errorDoNotDisturbModeEnabled: - description = - 'The camera could not be opened because "Do Not Disturb" mode is enabled. Please disable this mode, and try opening the camera again.'; - default: - description = - 'There was an unspecified issue with the current camera state.'; - } - - return '$code : $description'; - } -} - -/// Flutter API implementation for [CameraStateError]. -/// -/// This class may handle instantiating and adding Dart instances that are -/// attached to a native instance or receiving callback methods from an -/// overridden native class. -@protected -class CameraStateErrorFlutterApiImpl implements CameraStateErrorFlutterApi { - /// Constructs a [CameraStateErrorFlutterApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. If left null, it - /// will default to the global instance defined in [JavaObject]. - CameraStateErrorFlutterApiImpl({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - }) : _binaryMessenger = binaryMessenger, - _instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - - /// Receives binary data across the Flutter platform barrier. - final BinaryMessenger? _binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager _instanceManager; - - @override - void create( - int identifier, - int code, - ) { - _instanceManager.addHostCreatedInstance( - CameraStateError.detached( - code: code, - binaryMessenger: _binaryMessenger, - instanceManager: _instanceManager, - ), - identifier, - onCopy: (CameraStateError original) => CameraStateError.detached( - code: original.code, - binaryMessenger: _binaryMessenger, - instanceManager: _instanceManager, - ), - ); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/camerax_library.dart b/packages/camera/camera_android_camerax/lib/src/camerax_library.dart new file mode 100644 index 000000000000..bf1f4d2dd5dd --- /dev/null +++ b/packages/camera/camera_android_camerax/lib/src/camerax_library.dart @@ -0,0 +1,206 @@ +// Copyright 2013 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +import 'camerax_library.g.dart' as camerax; + +export 'camerax_library.g.dart' hide CameraInfo, LiveData, Observer; + +/// Handles adding support for generics to the API wrapper. +/// +/// APIs wrapped with the pigeon ProxyAPI system doesn't support generics, so +/// this handles using subclasses to add support. +void setUpGenerics({ + BinaryMessenger? pigeonBinaryMessenger, + camerax.PigeonInstanceManager? pigeonInstanceManager, +}) { + camerax.LiveData.pigeon_setUpMessageHandlers( + pigeon_newInstance: (camerax.LiveDataSupportedType type) { + switch (type) { + case camerax.LiveDataSupportedType.cameraState: + return LiveData.detached( + type: type, + pigeon_binaryMessenger: pigeonBinaryMessenger, + pigeon_instanceManager: pigeonInstanceManager, + ); + case camerax.LiveDataSupportedType.zoomState: + return LiveData.detached( + type: type, + pigeon_binaryMessenger: pigeonBinaryMessenger, + pigeon_instanceManager: pigeonInstanceManager, + ); + } + }, + ); + + camerax.CameraInfo.pigeon_setUpMessageHandlers( + pigeon_newInstance: ( + int sensorRotationDegrees, + camerax.ExposureState exposureState, + ) { + return CameraInfo.detached( + sensorRotationDegrees: sensorRotationDegrees, + exposureState: exposureState, + pigeon_binaryMessenger: pigeonBinaryMessenger, + pigeon_instanceManager: pigeonInstanceManager, + ); + }, + ); +} + +/// Handle onto the raw buffer managed by screen compositor. +/// +/// See https://developer.android.com/reference/android/view/Surface.html. +class Surface { + /// Rotation constant to signify the natural orientation. + /// + /// See https://developer.android.com/reference/android/view/Surface.html#ROTATION_0. + static const int rotation0 = 0; + + /// Rotation constant to signify a 90 degrees rotation. + /// + /// See https://developer.android.com/reference/android/view/Surface.html#ROTATION_90. + static const int rotation90 = 1; + + /// Rotation constant to signify a 180 degrees rotation. + /// + /// See https://developer.android.com/reference/android/view/Surface.html#ROTATION_180. + static const int rotation180 = 2; + + /// Rotation constant to signify a 270 degrees rotation. + /// + /// See https://developer.android.com/reference/android/view/Surface.html#ROTATION_270. + static const int rotation270 = 3; +} + +/// An interface for retrieving camera information. +/// +/// See https://developer.android.com/reference/androidx/camera/core/CameraInfo. +class CameraInfo extends camerax.CameraInfo { + /// Constructs [CameraInfo] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + CameraInfo.detached({ + required super.sensorRotationDegrees, + required super.exposureState, + // ignore: non_constant_identifier_names + super.pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + super.pigeon_instanceManager, + }) : super.pigeon_detached(); + + @override + Future> getCameraState() async { + return (await super.getCameraState()) as LiveData; + } + + @override + Future> getZoomState() async { + return (await super.getZoomState()) as LiveData; + } + + @override + // ignore: non_constant_identifier_names + CameraInfo pigeon_copy() { + return CameraInfo.detached( + sensorRotationDegrees: sensorRotationDegrees, + exposureState: exposureState, + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } +} + +/// LiveData is a data holder class that can be observed within a given +/// lifecycle. +/// +/// This is a wrapper around the native class to better support the generic +/// type. Java has type erasure. +/// +/// See https://developer.android.com/reference/androidx/lifecycle/LiveData. +class LiveData extends camerax.LiveData { + /// Constructs [LiveData] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + LiveData.detached({ + required super.type, + // ignore: non_constant_identifier_names + super.pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + super.pigeon_instanceManager, + }) : super.pigeon_detached(); + + @override + Future observe(covariant Observer observer) { + return super.observe(observer); + } + + @override + Future getValue() async { + return (await super.getValue()) as T?; + } + + @override + // ignore: non_constant_identifier_names + LiveData pigeon_copy() { + return LiveData.detached( + type: type, + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } +} + +/// A simple callback that can receive from LiveData. +/// +/// See https://developer.android.com/reference/androidx/lifecycle/Observer. +class Observer extends camerax.Observer { + /// Constructs an [Observer]. + Observer({ + required void Function(Observer instance, T value) onChanged, + // ignore: non_constant_identifier_names + super.pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + super.pigeon_instanceManager, + }) : _genericOnChanged = onChanged, + super( + onChanged: (camerax.Observer instance, Object value) { + onChanged(instance as Observer, value as T); + }, + ); + + /// Constructs [Observer] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + Observer.detached({ + required void Function(Observer instance, T value) onChanged, + // ignore: non_constant_identifier_names + super.pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + super.pigeon_instanceManager, + }) : _genericOnChanged = onChanged, + super.pigeon_detached( + onChanged: (camerax.Observer instance, Object value) { + onChanged(instance as Observer, value as T); + }, + ); + + final void Function(Observer instance, T value) _genericOnChanged; + + @override + // ignore: non_constant_identifier_names + Observer pigeon_copy() { + return Observer.detached( + onChanged: _genericOnChanged, + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } +} diff --git a/packages/camera/camera_android_camerax/lib/src/camerax_library.g.dart b/packages/camera/camera_android_camerax/lib/src/camerax_library.g.dart index e830a288ce9e..d641289808e3 100644 --- a/packages/camera/camera_android_camerax/lib/src/camerax_library.g.dart +++ b/packages/camera/camera_android_camerax/lib/src/camerax_library.g.dart @@ -1,43 +1,574 @@ // Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// Autogenerated from Pigeon (v9.2.5), do not edit directly. +// Autogenerated from Pigeon (v25.2.0), do not edit directly. // See also: https://pub.dev/packages/pigeon -// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import, no_leading_underscores_for_local_identifiers import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; -import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; +import 'package:flutter/foundation.dart' + show ReadBuffer, WriteBuffer, immutable, protected; import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart' show WidgetsFlutterBinding; + +PlatformException _createConnectionError(String channelName) { + return PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel: "$channelName".', + ); +} + +List wrapResponse( + {Object? result, PlatformException? error, bool empty = false}) { + if (empty) { + return []; + } + if (error == null) { + return [result]; + } + return [error.code, error.message, error.details]; +} + +/// An immutable object that serves as the base class for all ProxyApis and +/// can provide functional copies of itself. +/// +/// All implementers are expected to be [immutable] as defined by the annotation +/// and override [pigeon_copy] returning an instance of itself. +@immutable +abstract class PigeonInternalProxyApiBaseClass { + /// Construct a [PigeonInternalProxyApiBaseClass]. + PigeonInternalProxyApiBaseClass({ + this.pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) : pigeon_instanceManager = + pigeon_instanceManager ?? PigeonInstanceManager.instance; + + /// Sends and receives binary data across the Flutter platform barrier. + /// + /// If it is null, the default BinaryMessenger will be used, which routes to + /// the host platform. + @protected + final BinaryMessenger? pigeon_binaryMessenger; + + /// Maintains instances stored to communicate with native language objects. + final PigeonInstanceManager pigeon_instanceManager; + + /// Instantiates and returns a functionally identical object to oneself. + /// + /// Outside of tests, this method should only ever be called by + /// [PigeonInstanceManager]. + /// + /// Subclasses should always override their parent's implementation of this + /// method. + @protected + PigeonInternalProxyApiBaseClass pigeon_copy(); +} + +/// Maintains instances used to communicate with the native objects they +/// represent. +/// +/// Added instances are stored as weak references and their copies are stored +/// as strong references to maintain access to their variables and callback +/// methods. Both are stored with the same identifier. +/// +/// When a weak referenced instance becomes inaccessible, +/// [onWeakReferenceRemoved] is called with its associated identifier. +/// +/// If an instance is retrieved and has the possibility to be used, +/// (e.g. calling [getInstanceWithWeakReference]) a copy of the strong reference +/// is added as a weak reference with the same identifier. This prevents a +/// scenario where the weak referenced instance was released and then later +/// returned by the host platform. +class PigeonInstanceManager { + /// Constructs a [PigeonInstanceManager]. + PigeonInstanceManager({required void Function(int) onWeakReferenceRemoved}) { + this.onWeakReferenceRemoved = (int identifier) { + _weakInstances.remove(identifier); + onWeakReferenceRemoved(identifier); + }; + _finalizer = Finalizer(this.onWeakReferenceRemoved); + } + + // Identifiers are locked to a specific range to avoid collisions with objects + // created simultaneously by the host platform. + // Host uses identifiers >= 2^16 and Dart is expected to use values n where, + // 0 <= n < 2^16. + static const int _maxDartCreatedIdentifier = 65536; + + /// The default [PigeonInstanceManager] used by ProxyApis. + /// + /// On creation, this manager makes a call to clear the native + /// InstanceManager. This is to prevent identifier conflicts after a host + /// restart. + static final PigeonInstanceManager instance = _initInstance(); + + // Expando is used because it doesn't prevent its keys from becoming + // inaccessible. This allows the manager to efficiently retrieve an identifier + // of an instance without holding a strong reference to that instance. + // + // It also doesn't use `==` to search for identifiers, which would lead to an + // infinite loop when comparing an object to its copy. (i.e. which was caused + // by calling instanceManager.getIdentifier() inside of `==` while this was a + // HashMap). + final Expando _identifiers = Expando(); + final Map> + _weakInstances = >{}; + final Map _strongInstances = + {}; + late final Finalizer _finalizer; + int _nextIdentifier = 0; + + /// Called when a weak referenced instance is removed by [removeWeakReference] + /// or becomes inaccessible. + late final void Function(int) onWeakReferenceRemoved; + + static PigeonInstanceManager _initInstance() { + WidgetsFlutterBinding.ensureInitialized(); + final _PigeonInternalInstanceManagerApi api = + _PigeonInternalInstanceManagerApi(); + // Clears the native `PigeonInstanceManager` on the initial use of the Dart one. + api.clear(); + final PigeonInstanceManager instanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (int identifier) { + api.removeStrongReference(identifier); + }, + ); + _PigeonInternalInstanceManagerApi.setUpMessageHandlers( + instanceManager: instanceManager); + CameraSize.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + ResolutionInfo.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + CameraIntegerRange.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + VideoRecordEvent.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + VideoRecordEventStart.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + VideoRecordEventFinalize.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + MeteringPoint.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + Observer.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + CameraInfo.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + CameraSelector.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + ProcessCameraProvider.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + UseCase.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + Camera.pigeon_setUpMessageHandlers(pigeon_instanceManager: instanceManager); + SystemServicesManager.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + CameraPermissionsError.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + DeviceOrientationManager.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + Preview.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + VideoCapture.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + VideoOutput.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + Recorder.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + VideoRecordEventListener.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + PendingRecording.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + Recording.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + ImageCapture.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + ResolutionStrategy.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + ResolutionSelector.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + AspectRatioStrategy.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + CameraState.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + ExposureState.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + ZoomState.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + ImageAnalysis.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + Analyzer.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + CameraStateStateError.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + LiveData.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + ImageProxy.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + PlaneProxy.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + QualitySelector.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + FallbackStrategy.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + CameraControl.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + FocusMeteringActionBuilder.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + FocusMeteringAction.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + FocusMeteringResult.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + CaptureRequest.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + CaptureRequestKey.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + CaptureRequestOptions.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + Camera2CameraControl.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + ResolutionFilter.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + CameraCharacteristicsKey.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + CameraCharacteristics.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + Camera2CameraInfo.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + MeteringPointFactory.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + DisplayOrientedMeteringPointFactory.pigeon_setUpMessageHandlers( + pigeon_instanceManager: instanceManager); + return instanceManager; + } + + /// Adds a new instance that was instantiated by Dart. + /// + /// In other words, Dart wants to add a new instance that will represent + /// an object that will be instantiated on the host platform. + /// + /// Throws assertion error if the instance has already been added. + /// + /// Returns the randomly generated id of the [instance] added. + int addDartCreatedInstance(PigeonInternalProxyApiBaseClass instance) { + final int identifier = _nextUniqueIdentifier(); + _addInstanceWithIdentifier(instance, identifier); + return identifier; + } + + /// Removes the instance, if present, and call [onWeakReferenceRemoved] with + /// its identifier. + /// + /// Returns the identifier associated with the removed instance. Otherwise, + /// `null` if the instance was not found in this manager. + /// + /// This does not remove the strong referenced instance associated with + /// [instance]. This can be done with [remove]. + int? removeWeakReference(PigeonInternalProxyApiBaseClass instance) { + final int? identifier = getIdentifier(instance); + if (identifier == null) { + return null; + } + + _identifiers[instance] = null; + _finalizer.detach(instance); + onWeakReferenceRemoved(identifier); + + return identifier; + } + + /// Removes [identifier] and its associated strongly referenced instance, if + /// present, from the manager. + /// + /// Returns the strong referenced instance associated with [identifier] before + /// it was removed. Returns `null` if [identifier] was not associated with + /// any strong reference. + /// + /// This does not remove the weak referenced instance associated with + /// [identifier]. This can be done with [removeWeakReference]. + T? remove(int identifier) { + return _strongInstances.remove(identifier) as T?; + } + + /// Retrieves the instance associated with identifier. + /// + /// The value returned is chosen from the following order: + /// + /// 1. A weakly referenced instance associated with identifier. + /// 2. If the only instance associated with identifier is a strongly + /// referenced instance, a copy of the instance is added as a weak reference + /// with the same identifier. Returning the newly created copy. + /// 3. If no instance is associated with identifier, returns null. + /// + /// This method also expects the host `InstanceManager` to have a strong + /// reference to the instance the identifier is associated with. + T? getInstanceWithWeakReference( + int identifier) { + final PigeonInternalProxyApiBaseClass? weakInstance = + _weakInstances[identifier]?.target; + + if (weakInstance == null) { + final PigeonInternalProxyApiBaseClass? strongInstance = + _strongInstances[identifier]; + if (strongInstance != null) { + final PigeonInternalProxyApiBaseClass copy = + strongInstance.pigeon_copy(); + _identifiers[copy] = identifier; + _weakInstances[identifier] = + WeakReference(copy); + _finalizer.attach(copy, identifier, detach: copy); + return copy as T; + } + return strongInstance as T?; + } + + return weakInstance as T; + } + + /// Retrieves the identifier associated with instance. + int? getIdentifier(PigeonInternalProxyApiBaseClass instance) { + return _identifiers[instance]; + } + + /// Adds a new instance that was instantiated by the host platform. + /// + /// In other words, the host platform wants to add a new instance that + /// represents an object on the host platform. Stored with [identifier]. + /// + /// Throws assertion error if the instance or its identifier has already been + /// added. + /// + /// Returns unique identifier of the [instance] added. + void addHostCreatedInstance( + PigeonInternalProxyApiBaseClass instance, int identifier) { + _addInstanceWithIdentifier(instance, identifier); + } + + void _addInstanceWithIdentifier( + PigeonInternalProxyApiBaseClass instance, int identifier) { + assert(!containsIdentifier(identifier)); + assert(getIdentifier(instance) == null); + assert(identifier >= 0); + + _identifiers[instance] = identifier; + _weakInstances[identifier] = + WeakReference(instance); + _finalizer.attach(instance, identifier, detach: instance); + + final PigeonInternalProxyApiBaseClass copy = instance.pigeon_copy(); + _identifiers[copy] = identifier; + _strongInstances[identifier] = copy; + } + + /// Whether this manager contains the given [identifier]. + bool containsIdentifier(int identifier) { + return _weakInstances.containsKey(identifier) || + _strongInstances.containsKey(identifier); + } + + int _nextUniqueIdentifier() { + late int identifier; + do { + identifier = _nextIdentifier; + _nextIdentifier = (_nextIdentifier + 1) % _maxDartCreatedIdentifier; + } while (containsIdentifier(identifier)); + return identifier; + } +} + +/// Generated API for managing the Dart and native `PigeonInstanceManager`s. +class _PigeonInternalInstanceManagerApi { + /// Constructor for [_PigeonInternalInstanceManagerApi]. + _PigeonInternalInstanceManagerApi({BinaryMessenger? binaryMessenger}) + : pigeonVar_binaryMessenger = binaryMessenger; + + final BinaryMessenger? pigeonVar_binaryMessenger; + + static const MessageCodec pigeonChannelCodec = _PigeonCodec(); + + static void setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? binaryMessenger, + PigeonInstanceManager? instanceManager, + }) { + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.PigeonInternalInstanceManager.removeStrongReference', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.PigeonInternalInstanceManager.removeStrongReference was null.'); + final List args = (message as List?)!; + final int? arg_identifier = (args[0] as int?); + assert(arg_identifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.PigeonInternalInstanceManager.removeStrongReference was null, expected non-null int.'); + try { + (instanceManager ?? PigeonInstanceManager.instance) + .remove(arg_identifier!); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } + + Future removeStrongReference(int identifier) async { + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.PigeonInternalInstanceManager.removeStrongReference'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([identifier]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + /// Clear the native `PigeonInstanceManager`. + /// + /// This is typically called after a hot restart. + Future clear() async { + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.PigeonInternalInstanceManager.clear'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } +} + +class _PigeonInternalProxyApiBaseCodec extends _PigeonCodec { + const _PigeonInternalProxyApiBaseCodec(this.instanceManager); + final PigeonInstanceManager instanceManager; + @override + void writeValue(WriteBuffer buffer, Object? value) { + if (value is PigeonInternalProxyApiBaseClass) { + buffer.putUint8(128); + writeValue(buffer, instanceManager.getIdentifier(value)); + } else { + super.writeValue(buffer, value); + } + } + + @override + Object? readValueOfType(int type, ReadBuffer buffer) { + switch (type) { + case 128: + return instanceManager + .getInstanceWithWeakReference(readValue(buffer)! as int); + default: + return super.readValueOfType(type, buffer); + } + } +} + +/// Generally classifies the overall set of the camera device functionality. +/// +/// See https://developer.android.com/reference/android/hardware/camera2/CameraMetadata#INFO_SUPPORTED_HARDWARE_LEVEL_3. +enum InfoSupportedHardwareLevel { + /// This camera device is capable of YUV reprocessing and RAW data capture, in + /// addition to FULL-level capabilities. + level3, + + /// This camera device is backed by an external camera connected to this + /// Android device. + external, + + /// This camera device is capable of supporting advanced imaging applications. + full, + + /// This camera device is running in backward compatibility mode. + legacy, + + /// This camera device does not have enough capabilities to qualify as a FULL + /// device or better. + limited, +} + +/// The aspect ratio of the use case. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/AspectRatio. +enum AspectRatio { + /// 16:9 standard aspect ratio. + ratio16To9, + + /// 4:3 standard aspect ratio. + ratio4To3, + + /// The aspect ratio representing no preference for aspect ratio. + ratioDefault, + + /// The value is not recognized by the wrapper. + unknown, +} /// The states the camera can be in. /// /// See https://developer.android.com/reference/androidx/camera/core/CameraState.Type. enum CameraStateType { + /// Represents a state where the camera device is closed. closed, + + /// Represents a state where the camera device is currently closing. closing, + + /// Represents a state where the camera device is open. open, + + /// Represents a state where the camera device is currently opening. opening, + + /// Represents a state where the camera is waiting for a signal to attempt to + /// open the camera device. pendingOpen, + + /// This value is not recognized by this wrapper. + unknown, } /// The types (T) properly wrapped to be used as a LiveData. -/// -/// If you need to add another type to support a type S to use a LiveData in -/// this plugin, ensure the following is done on the Dart side: -/// -/// * In `camera_android_camerax/lib/src/live_data.dart`, add new cases for S in -/// `_LiveDataHostApiImpl#getValueFromInstances` to get the current value of -/// type S from a LiveData instance and in `LiveDataFlutterApiImpl#create` -/// to create the expected type of LiveData when requested. -/// -/// On the native side, ensure the following is done: -/// -/// * Make sure `LiveDataHostApiImpl#getValue` is updated to properly return -/// identifiers for instances of type S. -/// * Update `ObserverFlutterApiWrapper#onChanged` to properly handle receiving -/// calls with instances of type S if a LiveData instance is observed. enum LiveDataSupportedType { cameraState, zoomState, @@ -50,3640 +581,8243 @@ enum LiveDataSupportedType { /// /// See https://developer.android.com/reference/androidx/camera/video/Quality. enum VideoQuality { + /// Standard Definition (SD) 480p video quality. SD, + + /// High Definition (HD) 720p video quality. HD, + + /// Full High Definition (FHD) 1080p video quality. FHD, + + /// Ultra High Definition (UHD) 2160p video quality. UHD, + + /// The lowest video quality supported by the video frame producer. lowest, + + /// The highest video quality supported by the video frame producer. highest, } -/// Fallback rules for selecting video resolution. +/// A flag used for indicating metering mode regions. /// -/// See https://developer.android.com/reference/androidx/camera/video/FallbackStrategy. -enum VideoResolutionFallbackRule { - higherQualityOrLowerThan, - higherQualityThan, - lowerQualityOrHigherThan, - lowerQualityThan, +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/FocusMeteringAction#FLAG_AF(). +enum MeteringMode { + /// A flag used in metering mode indicating the AE (Auto Exposure) region is + /// enabled. + ae, + + /// A flag used in metering mode indicating the AF (Auto Focus) region is + /// enabled. + af, + + /// A flag used in metering mode indicating the AWB (Auto White Balance) + /// region is enabled. + awb, } -/// Video recording status. +/// Direction of lens of a camera. /// -/// See https://developer.android.com/reference/androidx/camera/video/VideoRecordEvent. -enum VideoRecordEvent { - start, - finalize, +/// See https://developer.android.com/reference/androidx/camera/core/CameraSelector#LENS_FACING_BACK(). +enum LensFacing { + /// A camera on the device facing the same direction as the device's screen. + front, + + /// A camera on the device facing the opposite direction as the device's + /// screen. + back, + + /// An external camera that has no fixed facing relative to the device's + /// screen. + external, + + /// A camera on the devices that its lens facing is resolved. + unknown, } -/// The types of capture request options this plugin currently supports. +/// FlashModes for image capture. /// -/// If you need to add another option to support, ensure the following is done -/// on the Dart side: -/// -/// * In `camera_android_camerax/lib/src/capture_request_options.dart`, add new cases for this -/// option in `_CaptureRequestOptionsHostApiImpl#createFromInstances` -/// to create the expected Map entry of option key index and value to send to -/// the native side. +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageCapture#FLASH_MODE_AUTO(). +enum CameraXFlashMode { + /// Auto flash. + /// + /// The flash will be used according to the camera system's determination when + /// taking a picture. + auto, + + /// No flash. + /// + /// The flash will never be used when taking a picture. + off, + + /// Always flash. + /// + /// The flash will always be used when taking a picture. + on, +} + +/// Fallback rule for choosing an alternate size when the specified bound size +/// is unavailable. /// -/// On the native side, ensure the following is done: +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/resolutionselector/ResolutionStrategy. +enum ResolutionStrategyFallbackRule { + /// When the specified bound size is unavailable, CameraX falls back to the + /// closest higher resolution size. + closestHigher, + + /// When the specified bound size is unavailable, CameraX falls back to select + /// the closest higher resolution size. + closestHigherThenLower, + + /// When the specified bound size is unavailable, CameraX falls back to the + /// closest lower resolution size. + closestLower, + + /// When the specified bound size is unavailable, CameraX falls back to select + /// the closest lower resolution size. + /// + /// If CameraX still cannot find any available resolution, it will fallback to + /// select other higher resolutions. + closestLowerThenHigher, + + /// CameraX doesn't select an alternate size when the specified bound size is + /// unavailable. + none, + + /// The value is not recognized by the wrapper. + unknown, +} + +/// Fallback rule for choosing the aspect ratio when the preferred aspect ratio +/// is not available. /// -/// * Update `CaptureRequestOptionsHostApiImpl#create` to set the correct -/// `CaptureRequest` key with a valid value type for this option. +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/resolutionselector/AspectRatioStrategy#FALLBACK_RULE_AUTO(). +enum AspectRatioStrategyFallbackRule { + /// CameraX automatically chooses the next best aspect ratio which contains + /// the closest field of view (FOV) of the camera sensor, from the remaining + /// options. + auto, + + /// CameraX doesn't fall back to select sizes of any other aspect ratio when + /// this fallback rule is used. + none, + + /// The value is not recognized by the wrapper. + unknown, +} + +/// Code for a `CameraState` error. /// -/// See https://developer.android.com/reference/android/hardware/camera2/CaptureRequest -/// for the sorts of capture request options that can be supported via CameraX's -/// interoperability with Camera2. -enum CaptureRequestKeySupportedType { - controlAeLock, +/// https://developer.android.com/reference/androidx/camera/core/CameraState#ERROR_CAMERA_DISABLED() +enum CameraStateErrorCode { + /// An error indicating that the camera device could not be opened due to a + /// device policy. + cameraDisabled, + + /// An error indicating that the camera device was closed due to a fatal + /// error. + cameraFatalError, + + /// An error indicating that the camera device is already in use. + cameraInUse, + + /// An error indicating that the camera could not be opened because "Do Not + /// Disturb" mode is enabled on devices affected by a bug in Android 9 (API + /// level 28). + doNotDisturbModeEnabled, + + /// An error indicating that the limit number of open cameras has been + /// reached, and more cameras cannot be opened until other instances are + /// closed. + maxCamerasInUse, + + /// An error indicating that the camera device has encountered a recoverable + /// error. + otherRecoverableError, + + /// An error indicating that configuring the camera has failed. + streamConfig, + + /// The value is not recognized by this wrapper. + unknown, } -class ResolutionInfo { - ResolutionInfo({ +class _PigeonCodec extends StandardMessageCodec { + const _PigeonCodec(); + @override + void writeValue(WriteBuffer buffer, Object? value) { + if (value is int) { + buffer.putUint8(4); + buffer.putInt64(value); + } else if (value is InfoSupportedHardwareLevel) { + buffer.putUint8(129); + writeValue(buffer, value.index); + } else if (value is AspectRatio) { + buffer.putUint8(130); + writeValue(buffer, value.index); + } else if (value is CameraStateType) { + buffer.putUint8(131); + writeValue(buffer, value.index); + } else if (value is LiveDataSupportedType) { + buffer.putUint8(132); + writeValue(buffer, value.index); + } else if (value is VideoQuality) { + buffer.putUint8(133); + writeValue(buffer, value.index); + } else if (value is MeteringMode) { + buffer.putUint8(134); + writeValue(buffer, value.index); + } else if (value is LensFacing) { + buffer.putUint8(135); + writeValue(buffer, value.index); + } else if (value is CameraXFlashMode) { + buffer.putUint8(136); + writeValue(buffer, value.index); + } else if (value is ResolutionStrategyFallbackRule) { + buffer.putUint8(137); + writeValue(buffer, value.index); + } else if (value is AspectRatioStrategyFallbackRule) { + buffer.putUint8(138); + writeValue(buffer, value.index); + } else if (value is CameraStateErrorCode) { + buffer.putUint8(139); + writeValue(buffer, value.index); + } else { + super.writeValue(buffer, value); + } + } + + @override + Object? readValueOfType(int type, ReadBuffer buffer) { + switch (type) { + case 129: + final int? value = readValue(buffer) as int?; + return value == null ? null : InfoSupportedHardwareLevel.values[value]; + case 130: + final int? value = readValue(buffer) as int?; + return value == null ? null : AspectRatio.values[value]; + case 131: + final int? value = readValue(buffer) as int?; + return value == null ? null : CameraStateType.values[value]; + case 132: + final int? value = readValue(buffer) as int?; + return value == null ? null : LiveDataSupportedType.values[value]; + case 133: + final int? value = readValue(buffer) as int?; + return value == null ? null : VideoQuality.values[value]; + case 134: + final int? value = readValue(buffer) as int?; + return value == null ? null : MeteringMode.values[value]; + case 135: + final int? value = readValue(buffer) as int?; + return value == null ? null : LensFacing.values[value]; + case 136: + final int? value = readValue(buffer) as int?; + return value == null ? null : CameraXFlashMode.values[value]; + case 137: + final int? value = readValue(buffer) as int?; + return value == null + ? null + : ResolutionStrategyFallbackRule.values[value]; + case 138: + final int? value = readValue(buffer) as int?; + return value == null + ? null + : AspectRatioStrategyFallbackRule.values[value]; + case 139: + final int? value = readValue(buffer) as int?; + return value == null ? null : CameraStateErrorCode.values[value]; + default: + return super.readValueOfType(type, buffer); + } + } +} + +/// Immutable class for describing width and height dimensions in pixels. +/// +/// See https://developer.android.com/reference/android/util/Size.html. +class CameraSize extends PigeonInternalProxyApiBaseClass { + CameraSize({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, required this.width, required this.height, - }); - - int width; + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecCameraSize; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.CameraSize.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([pigeonVar_instanceIdentifier, width, height]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + } - int height; + /// Constructs [CameraSize] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + CameraSize.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.width, + required this.height, + }); - Object encode() { - return [ - width, - height, - ]; + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecCameraSize = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + /// The width of the size (in pixels). + final int width; + + /// The height of the size (in pixels). + final int height; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + CameraSize Function( + int width, + int height, + )? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.CameraSize.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraSize.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraSize.pigeon_newInstance was null, expected non-null int.'); + final int? arg_width = (args[1] as int?); + assert(arg_width != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraSize.pigeon_newInstance was null, expected non-null int.'); + final int? arg_height = (args[2] as int?); + assert(arg_height != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraSize.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call(arg_width!, arg_height!) ?? + CameraSize.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + width: arg_width!, + height: arg_height!, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } } - static ResolutionInfo decode(Object result) { - result as List; - return ResolutionInfo( - width: result[0]! as int, - height: result[1]! as int, + @override + CameraSize pigeon_copy() { + return CameraSize.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + width: width, + height: height, ); } } -class CameraPermissionsErrorData { - CameraPermissionsErrorData({ - required this.errorCode, - required this.description, +/// A `ResolutionInfo` allows the application to know the resolution information +/// of a specific use case. +/// +/// See https://developer.android.com/reference/androidx/camera/core/ResolutionInfo. +class ResolutionInfo extends PigeonInternalProxyApiBaseClass { + /// Constructs [ResolutionInfo] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + ResolutionInfo.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.resolution, }); - String errorCode; + /// Returns the output resolution used for the use case. + final CameraSize resolution; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + ResolutionInfo Function(CameraSize resolution)? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.ResolutionInfo.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ResolutionInfo.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ResolutionInfo.pigeon_newInstance was null, expected non-null int.'); + final CameraSize? arg_resolution = (args[1] as CameraSize?); + assert(arg_resolution != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ResolutionInfo.pigeon_newInstance was null, expected non-null CameraSize.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call(arg_resolution!) ?? + ResolutionInfo.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + resolution: arg_resolution!, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } + + @override + ResolutionInfo pigeon_copy() { + return ResolutionInfo.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + resolution: resolution, + ); + } +} + +/// Immutable class for describing the range of two integer values. +/// +/// This is the equivalent to `android.util.Range`. +/// +/// See https://developer.android.com/reference/android/util/Range.html. +class CameraIntegerRange extends PigeonInternalProxyApiBaseClass { + CameraIntegerRange({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.lower, + required this.upper, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecCameraIntegerRange; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.CameraIntegerRange.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([pigeonVar_instanceIdentifier, lower, upper]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + } - String description; + /// Constructs [CameraIntegerRange] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + CameraIntegerRange.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.lower, + required this.upper, + }); - Object encode() { - return [ - errorCode, - description, - ]; + late final _PigeonInternalProxyApiBaseCodec + _pigeonVar_codecCameraIntegerRange = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + /// The lower endpoint. + final int lower; + + /// The upper endpoint. + final int upper; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + CameraIntegerRange Function( + int lower, + int upper, + )? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.CameraIntegerRange.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraIntegerRange.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraIntegerRange.pigeon_newInstance was null, expected non-null int.'); + final int? arg_lower = (args[1] as int?); + assert(arg_lower != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraIntegerRange.pigeon_newInstance was null, expected non-null int.'); + final int? arg_upper = (args[2] as int?); + assert(arg_upper != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraIntegerRange.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call(arg_lower!, arg_upper!) ?? + CameraIntegerRange.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + lower: arg_lower!, + upper: arg_upper!, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } } - static CameraPermissionsErrorData decode(Object result) { - result as List; - return CameraPermissionsErrorData( - errorCode: result[0]! as String, - description: result[1]! as String, + @override + CameraIntegerRange pigeon_copy() { + return CameraIntegerRange.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + lower: lower, + upper: upper, ); } } -class CameraStateTypeData { - CameraStateTypeData({ - required this.value, +/// VideoRecordEvent is used to report video recording events and status. +/// +/// See https://developer.android.com/reference/androidx/camera/video/VideoRecordEvent. +class VideoRecordEvent extends PigeonInternalProxyApiBaseClass { + /// Constructs [VideoRecordEvent] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + VideoRecordEvent.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, }); - CameraStateType value; - - Object encode() { - return [ - value.index, - ]; + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + VideoRecordEvent Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.VideoRecordEvent.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.VideoRecordEvent.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.VideoRecordEvent.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + VideoRecordEvent.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } } - static CameraStateTypeData decode(Object result) { - result as List; - return CameraStateTypeData( - value: CameraStateType.values[result[0]! as int], + @override + VideoRecordEvent pigeon_copy() { + return VideoRecordEvent.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, ); } } -class LiveDataSupportedTypeData { - LiveDataSupportedTypeData({ - required this.value, - }); +/// Indicates the start of recording. +/// +/// See https://developer.android.com/reference/androidx/camera/video/VideoRecordEvent.Start. +class VideoRecordEventStart extends VideoRecordEvent { + /// Constructs [VideoRecordEventStart] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + VideoRecordEventStart.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }) : super.pigeon_detached(); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + VideoRecordEventStart Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.VideoRecordEventStart.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.VideoRecordEventStart.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.VideoRecordEventStart.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + VideoRecordEventStart.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } - LiveDataSupportedType value; + @override + VideoRecordEventStart pigeon_copy() { + return VideoRecordEventStart.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } +} - Object encode() { - return [ - value.index, - ]; +/// Indicates the finalization of recording. +/// +/// See https://developer.android.com/reference/androidx/camera/video/VideoRecordEvent.Finalize. +class VideoRecordEventFinalize extends VideoRecordEvent { + /// Constructs [VideoRecordEventFinalize] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + VideoRecordEventFinalize.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }) : super.pigeon_detached(); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + VideoRecordEventFinalize Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.VideoRecordEventFinalize.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.VideoRecordEventFinalize.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.VideoRecordEventFinalize.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + VideoRecordEventFinalize.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } } - static LiveDataSupportedTypeData decode(Object result) { - result as List; - return LiveDataSupportedTypeData( - value: LiveDataSupportedType.values[result[0]! as int], + @override + VideoRecordEventFinalize pigeon_copy() { + return VideoRecordEventFinalize.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, ); } } -class ExposureCompensationRange { - ExposureCompensationRange({ - required this.minCompensation, - required this.maxCompensation, +/// A MeteringPoint is used to specify a region which can then be converted to +/// sensor coordinate system for focus and metering purpose. +/// +/// See https://developer.android.com/reference/androidx/camera/core/MeteringPoint. +class MeteringPoint extends PigeonInternalProxyApiBaseClass { + /// Constructs [MeteringPoint] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + MeteringPoint.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, }); - int minCompensation; - - int maxCompensation; - - Object encode() { - return [ - minCompensation, - maxCompensation, - ]; + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecMeteringPoint = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + MeteringPoint Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.MeteringPoint.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.MeteringPoint.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.MeteringPoint.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + MeteringPoint.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } } - static ExposureCompensationRange decode(Object result) { - result as List; - return ExposureCompensationRange( - minCompensation: result[0]! as int, - maxCompensation: result[1]! as int, + /// Size of the MeteringPoint width and height (ranging from 0 to 1). + /// + /// It is the percentage of the sensor width/height (or crop region + /// width/height if crop region is set). + Future getSize() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecMeteringPoint; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.MeteringPoint.getSize'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as double?)!; + } } -} -/// Convenience class for sending lists of [Quality]s. -class VideoQualityData { - VideoQualityData({ - required this.quality, - }); - - VideoQuality quality; - - Object encode() { - return [ - quality.index, - ]; + @override + MeteringPoint pigeon_copy() { + return MeteringPoint.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); } +} - static VideoQualityData decode(Object result) { - result as List; - return VideoQualityData( - quality: VideoQuality.values[result[0]! as int], +/// A simple callback that can receive from LiveData. +/// +/// See https://developer.android.com/reference/androidx/lifecycle/Observer. +class Observer extends PigeonInternalProxyApiBaseClass { + Observer({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.onChanged, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecObserver; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Observer.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([pigeonVar_instanceIdentifier]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); } -} -class VideoRecordEventData { - VideoRecordEventData({ - required this.value, + /// Constructs [Observer] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + Observer.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.onChanged, }); - VideoRecordEvent value; + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecObserver = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); - Object encode() { - return [ - value.index, - ]; + /// Called when the data is changed to value. + /// + /// For the associated Native object to be automatically garbage collected, + /// it is required that the implementation of this `Function` doesn't have a + /// strong reference to the encapsulating class instance. When this `Function` + /// references a non-local variable, it is strongly recommended to access it + /// with a `WeakReference`: + /// + /// ```dart + /// final WeakReference weakMyVariable = WeakReference(myVariable); + /// final Observer instance = Observer( + /// onChanged: (Observer pigeon_instance, ...) { + /// print(weakMyVariable?.target); + /// }, + /// ); + /// ``` + /// + /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to + /// release the associated Native object manually. + final void Function( + Observer pigeon_instance, + Object value, + ) onChanged; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + void Function( + Observer pigeon_instance, + Object value, + )? onChanged, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + 'dev.flutter.pigeon.camera_android_camerax.Observer.onChanged', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.Observer.onChanged was null.'); + final List args = (message as List?)!; + final Observer? arg_pigeon_instance = (args[0] as Observer?); + assert(arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.Observer.onChanged was null, expected non-null Observer.'); + final Object? arg_value = (args[1] as Object?); + assert(arg_value != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.Observer.onChanged was null, expected non-null Object.'); + try { + (onChanged ?? arg_pigeon_instance!.onChanged) + .call(arg_pigeon_instance!, arg_value!); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } } - static VideoRecordEventData decode(Object result) { - result as List; - return VideoRecordEventData( - value: VideoRecordEvent.values[result[0]! as int], + @override + Observer pigeon_copy() { + return Observer.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + onChanged: onChanged, ); } } -/// Convenience class for building [FocusMeteringAction]s with multiple metering -/// points. -class MeteringPointInfo { - MeteringPointInfo({ - required this.meteringPointId, - this.meteringMode, - }); - - /// InstanceManager ID for a [MeteringPoint]. - int meteringPointId; - - /// The metering mode of the [MeteringPoint] whose ID is [meteringPointId]. +/// An interface for retrieving camera information. +/// +/// See https://developer.android.com/reference/androidx/camera/core/CameraInfo. +class CameraInfo extends PigeonInternalProxyApiBaseClass { + /// Constructs [CameraInfo] without creating the associated native object. /// - /// Metering mode should be one of the [FocusMeteringAction] constants. - int? meteringMode; + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + CameraInfo.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.sensorRotationDegrees, + required this.exposureState, + }); - Object encode() { - return [ - meteringPointId, - meteringMode, - ]; + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecCameraInfo = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + /// Returns the sensor rotation in degrees, relative to the device's "natural" + /// (default) orientation. + final int sensorRotationDegrees; + + /// Returns a ExposureState. + final ExposureState exposureState; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + CameraInfo Function( + int sensorRotationDegrees, + ExposureState exposureState, + )? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.CameraInfo.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraInfo.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraInfo.pigeon_newInstance was null, expected non-null int.'); + final int? arg_sensorRotationDegrees = (args[1] as int?); + assert(arg_sensorRotationDegrees != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraInfo.pigeon_newInstance was null, expected non-null int.'); + final ExposureState? arg_exposureState = (args[2] as ExposureState?); + assert(arg_exposureState != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraInfo.pigeon_newInstance was null, expected non-null ExposureState.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call( + arg_sensorRotationDegrees!, arg_exposureState!) ?? + CameraInfo.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + sensorRotationDegrees: arg_sensorRotationDegrees!, + exposureState: arg_exposureState!, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } } - static MeteringPointInfo decode(Object result) { - result as List; - return MeteringPointInfo( - meteringPointId: result[0]! as int, - meteringMode: result[1] as int?, + /// A LiveData of the camera's state. + Future getCameraState() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecCameraInfo; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.CameraInfo.getCameraState'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else if (pigeonVar_replyList[0] == null) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as LiveData?)!; + } } -} -class InstanceManagerHostApi { - /// Constructor for [InstanceManagerHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - InstanceManagerHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - - static const MessageCodec codec = StandardMessageCodec(); - - /// Clear the native `InstanceManager`. - /// - /// This is typically only used after a hot restart. - Future clear() async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.InstanceManagerHostApi.clear', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; - if (replyList == null) { + /// A LiveData of ZoomState. + Future getZoomState() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecCameraInfo; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.CameraInfo.getZoomState'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList.length > 1) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', ); } else { - return; + return (pigeonVar_replyList[0] as LiveData?)!; } } + + @override + CameraInfo pigeon_copy() { + return CameraInfo.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + sensorRotationDegrees: sensorRotationDegrees, + exposureState: exposureState, + ); + } } -class JavaObjectHostApi { - /// Constructor for [JavaObjectHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - JavaObjectHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; +/// A set of requirements and priorities used to select a camera or return a +/// filtered set of cameras. +/// +/// See https://developer.android.com/reference/androidx/camera/core/CameraSelector. +class CameraSelector extends PigeonInternalProxyApiBaseClass { + CameraSelector({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + LensFacing? requireLensFacing, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecCameraSelector; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.CameraSelector.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([pigeonVar_instanceIdentifier, requireLensFacing]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + } + + /// Constructs [CameraSelector] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + CameraSelector.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); - static const MessageCodec codec = StandardMessageCodec(); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecCameraSelector = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + /// A static `CameraSelector` that selects the default back facing camera. + static final CameraSelector defaultBackCamera = pigeonVar_defaultBackCamera(); + + /// A static `CameraSelector` that selects the default front facing camera. + static final CameraSelector defaultFrontCamera = + pigeonVar_defaultFrontCamera(); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + CameraSelector Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.CameraSelector.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraSelector.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraSelector.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + CameraSelector.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } - Future dispose(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.JavaObjectHostApi.dispose', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { + static CameraSelector pigeonVar_defaultBackCamera() { + final CameraSelector pigeonVar_instance = CameraSelector.pigeon_detached(); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance); + final BinaryMessenger pigeonVar_binaryMessenger = + ServicesBinding.instance.defaultBinaryMessenger; + final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance + .addDartCreatedInstance(pigeonVar_instance); + () async { + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.CameraSelector.defaultBackCamera'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([pigeonVar_instanceIdentifier]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + return pigeonVar_instance; + } + + static CameraSelector pigeonVar_defaultFrontCamera() { + final CameraSelector pigeonVar_instance = CameraSelector.pigeon_detached(); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance); + final BinaryMessenger pigeonVar_binaryMessenger = + ServicesBinding.instance.defaultBinaryMessenger; + final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance + .addDartCreatedInstance(pigeonVar_instance); + () async { + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.CameraSelector.defaultFrontCamera'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([pigeonVar_instanceIdentifier]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + return pigeonVar_instance; + } + + /// Filters the input `CameraInfo`s using the `CameraFilter`s assigned to the + /// selector. + Future> filter(List cameraInfos) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecCameraSelector; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.CameraSelector.filter'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, cameraInfos]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList.length > 1) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', ); } else { - return; + return (pigeonVar_replyList[0] as List?)!.cast(); } } -} -abstract class JavaObjectFlutterApi { - static const MessageCodec codec = StandardMessageCodec(); + @override + CameraSelector pigeon_copy() { + return CameraSelector.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } +} - void dispose(int identifier); +/// A singleton which can be used to bind the lifecycle of cameras to any +/// `LifecycleOwner` within an application's process. +/// +/// See https://developer.android.com/reference/androidx/camera/lifecycle/ProcessCameraProvider. +class ProcessCameraProvider extends PigeonInternalProxyApiBaseClass { + /// Constructs [ProcessCameraProvider] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + ProcessCameraProvider.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); - static void setup(JavaObjectFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { + late final _PigeonInternalProxyApiBaseCodec + _pigeonVar_codecProcessCameraProvider = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + ProcessCameraProvider Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.JavaObjectFlutterApi.dispose', codec, + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.pigeon_newInstance', + pigeonChannelCodec, binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); } else { - channel.setMessageHandler((Object? message) async { + pigeonVar_channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.JavaObjectFlutterApi.dispose was null.'); + 'Argument for dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.pigeon_newInstance was null.'); final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.JavaObjectFlutterApi.dispose was null, expected non-null int.'); - api.dispose(arg_identifier!); - return; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + ProcessCameraProvider.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } }); } } } -} -class CameraInfoHostApi { - /// Constructor for [CameraInfoHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - CameraInfoHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - - static const MessageCodec codec = StandardMessageCodec(); - - Future getSensorRotationDegrees(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraInfoHostApi.getSensorRotationDegrees', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { + /// Retrieves the ProcessCameraProvider associated with the current process. + static Future getInstance({ + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.getInstance'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send(null); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as int?)!; + return (pigeonVar_replyList[0] as ProcessCameraProvider?)!; } } - Future getCameraState(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraInfoHostApi.getCameraState', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { + /// The `CameraInfo` instances of the available cameras. + Future> getAvailableCameraInfos() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecProcessCameraProvider; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.getAvailableCameraInfos'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as int?)!; + return (pigeonVar_replyList[0] as List?)!.cast(); } } - Future getExposureState(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraInfoHostApi.getExposureState', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { + /// Binds the collection of `UseCase` to a `LifecycleOwner`. + Future bindToLifecycle( + CameraSelector cameraSelector, + List useCases, + ) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecProcessCameraProvider; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.bindToLifecycle'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, cameraSelector, useCases]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as int?)!; + return (pigeonVar_replyList[0] as Camera?)!; } } - Future getZoomState(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraInfoHostApi.getZoomState', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { + /// Returns true if the `UseCase` is bound to a lifecycle. + Future isBound(UseCase useCase) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecProcessCameraProvider; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.isBound'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, useCase]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as int?)!; + return (pigeonVar_replyList[0] as bool?)!; + } + } + + /// Unbinds all specified use cases from the lifecycle provider. + Future unbind(List useCases) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecProcessCameraProvider; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.unbind'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, useCases]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + } + + /// Unbinds all use cases from the lifecycle provider and removes them from + /// CameraX. + Future unbindAll() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecProcessCameraProvider; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.unbindAll'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; } } -} -abstract class CameraInfoFlutterApi { - static const MessageCodec codec = StandardMessageCodec(); + @override + ProcessCameraProvider pigeon_copy() { + return ProcessCameraProvider.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } +} - void create(int identifier); +/// The use case which all other use cases are built on top of. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/UseCase. +class UseCase extends PigeonInternalProxyApiBaseClass { + /// Constructs [UseCase] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + UseCase.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); - static void setup(CameraInfoFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + UseCase Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraInfoFlutterApi.create', codec, + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.UseCase.pigeon_newInstance', + pigeonChannelCodec, binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); } else { - channel.setMessageHandler((Object? message) async { + pigeonVar_channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.CameraInfoFlutterApi.create was null.'); + 'Argument for dev.flutter.pigeon.camera_android_camerax.UseCase.pigeon_newInstance was null.'); final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.CameraInfoFlutterApi.create was null, expected non-null int.'); - api.create(arg_identifier!); - return; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.UseCase.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + UseCase.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } }); } } } -} -class CameraSelectorHostApi { - /// Constructor for [CameraSelectorHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - CameraSelectorHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; + @override + UseCase pigeon_copy() { + return UseCase.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } +} - static const MessageCodec codec = StandardMessageCodec(); +/// The camera interface is used to control the flow of data to use cases, +/// control the camera via the `CameraControl`, and publish the state of the +/// camera via CameraInfo. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/Camera. +class Camera extends PigeonInternalProxyApiBaseClass { + /// Constructs [Camera] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + Camera.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.cameraControl, + }); - Future create(int arg_identifier, int? arg_lensFacing) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraSelectorHostApi.create', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_identifier, arg_lensFacing]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecCamera = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + /// The `CameraControl` for the Camera. + final CameraControl cameraControl; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + Camera Function(CameraControl cameraControl)? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.Camera.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.Camera.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.Camera.pigeon_newInstance was null, expected non-null int.'); + final CameraControl? arg_cameraControl = (args[1] as CameraControl?); + assert(arg_cameraControl != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.Camera.pigeon_newInstance was null, expected non-null CameraControl.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call(arg_cameraControl!) ?? + Camera.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + cameraControl: arg_cameraControl!, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } } } - Future> filter( - int arg_identifier, List arg_cameraInfoIds) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraSelectorHostApi.filter', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_identifier, arg_cameraInfoIds]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { + /// Returns information about this camera. + Future getCameraInfo() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecCamera; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Camera.getCameraInfo'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as List?)!.cast(); + return (pigeonVar_replyList[0] as CameraInfo?)!; } } + + @override + Camera pigeon_copy() { + return Camera.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + cameraControl: cameraControl, + ); + } } -abstract class CameraSelectorFlutterApi { - static const MessageCodec codec = StandardMessageCodec(); +/// Convenience class for accessing system resources. +class SystemServicesManager extends PigeonInternalProxyApiBaseClass { + SystemServicesManager({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.onCameraError, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecSystemServicesManager; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.SystemServicesManager.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([pigeonVar_instanceIdentifier]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + } + + /// Constructs [SystemServicesManager] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + SystemServicesManager.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.onCameraError, + }); - void create(int identifier, int? lensFacing); + late final _PigeonInternalProxyApiBaseCodec + _pigeonVar_codecSystemServicesManager = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); - static void setup(CameraSelectorFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { + /// Callback method. + /// + /// For the associated Native object to be automatically garbage collected, + /// it is required that the implementation of this `Function` doesn't have a + /// strong reference to the encapsulating class instance. When this `Function` + /// references a non-local variable, it is strongly recommended to access it + /// with a `WeakReference`: + /// + /// ```dart + /// final WeakReference weakMyVariable = WeakReference(myVariable); + /// final SystemServicesManager instance = SystemServicesManager( + /// onCameraError: (SystemServicesManager pigeon_instance, ...) { + /// print(weakMyVariable?.target); + /// }, + /// ); + /// ``` + /// + /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to + /// release the associated Native object manually. + final void Function( + SystemServicesManager pigeon_instance, + String errorDescription, + ) onCameraError; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + void Function( + SystemServicesManager pigeon_instance, + String errorDescription, + )? onCameraError, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraSelectorFlutterApi.create', codec, + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.SystemServicesManager.onCameraError', + pigeonChannelCodec, binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); } else { - channel.setMessageHandler((Object? message) async { + pigeonVar_channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.CameraSelectorFlutterApi.create was null.'); + 'Argument for dev.flutter.pigeon.camera_android_camerax.SystemServicesManager.onCameraError was null.'); final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.CameraSelectorFlutterApi.create was null, expected non-null int.'); - final int? arg_lensFacing = (args[1] as int?); - api.create(arg_identifier!, arg_lensFacing); - return; + final SystemServicesManager? arg_pigeon_instance = + (args[0] as SystemServicesManager?); + assert(arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.SystemServicesManager.onCameraError was null, expected non-null SystemServicesManager.'); + final String? arg_errorDescription = (args[1] as String?); + assert(arg_errorDescription != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.SystemServicesManager.onCameraError was null, expected non-null String.'); + try { + (onCameraError ?? arg_pigeon_instance!.onCameraError) + .call(arg_pigeon_instance!, arg_errorDescription!); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } }); } } } -} -class ProcessCameraProviderHostApi { - /// Constructor for [ProcessCameraProviderHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - ProcessCameraProviderHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - - static const MessageCodec codec = StandardMessageCodec(); - - Future getInstance() async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ProcessCameraProviderHostApi.getInstance', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', + Future requestCameraPermissions( + bool enableAudio) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecSystemServicesManager; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.SystemServicesManager.requestCameraPermissions'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, enableAudio]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList.length > 1) { + } else { + return (pigeonVar_replyList[0] as CameraPermissionsError?); + } + } + + /// Returns a path to be used to create a temp file in the current cache + /// directory. + Future getTempFilePath( + String prefix, + String suffix, + ) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecSystemServicesManager; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.SystemServicesManager.getTempFilePath'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, prefix, suffix]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as int?)!; + return (pigeonVar_replyList[0] as String?)!; } } - Future> getAvailableCameraInfos(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ProcessCameraProviderHostApi.getAvailableCameraInfos', - codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', + @override + SystemServicesManager pigeon_copy() { + return SystemServicesManager.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + onCameraError: onCameraError, + ); + } +} + +/// Contains data when an attempt to retrieve camera permissions fails. +class CameraPermissionsError extends PigeonInternalProxyApiBaseClass { + /// Constructs [CameraPermissionsError] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + CameraPermissionsError.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.errorCode, + required this.description, + }); + + final String errorCode; + + final String description; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + CameraPermissionsError Function( + String errorCode, + String description, + )? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.CameraPermissionsError.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraPermissionsError.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraPermissionsError.pigeon_newInstance was null, expected non-null int.'); + final String? arg_errorCode = (args[1] as String?); + assert(arg_errorCode != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraPermissionsError.pigeon_newInstance was null, expected non-null String.'); + final String? arg_description = (args[2] as String?); + assert(arg_description != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraPermissionsError.pigeon_newInstance was null, expected non-null String.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call(arg_errorCode!, arg_description!) ?? + CameraPermissionsError.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + errorCode: arg_errorCode!, + description: arg_description!, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } + + @override + CameraPermissionsError pigeon_copy() { + return CameraPermissionsError.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + errorCode: errorCode, + description: description, + ); + } +} + +/// Support class to help to determine the media orientation based on the +/// orientation of the device. +class DeviceOrientationManager extends PigeonInternalProxyApiBaseClass { + DeviceOrientationManager({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.onDeviceOrientationChanged, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecDeviceOrientationManager; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([pigeonVar_instanceIdentifier]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + } + + /// Constructs [DeviceOrientationManager] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + DeviceOrientationManager.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.onDeviceOrientationChanged, + }); + + late final _PigeonInternalProxyApiBaseCodec + _pigeonVar_codecDeviceOrientationManager = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + /// Callback method. + /// + /// For the associated Native object to be automatically garbage collected, + /// it is required that the implementation of this `Function` doesn't have a + /// strong reference to the encapsulating class instance. When this `Function` + /// references a non-local variable, it is strongly recommended to access it + /// with a `WeakReference`: + /// + /// ```dart + /// final WeakReference weakMyVariable = WeakReference(myVariable); + /// final DeviceOrientationManager instance = DeviceOrientationManager( + /// onDeviceOrientationChanged: (DeviceOrientationManager pigeon_instance, ...) { + /// print(weakMyVariable?.target); + /// }, + /// ); + /// ``` + /// + /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to + /// release the associated Native object manually. + final void Function( + DeviceOrientationManager pigeon_instance, + String orientation, + ) onDeviceOrientationChanged; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + void Function( + DeviceOrientationManager pigeon_instance, + String orientation, + )? onDeviceOrientationChanged, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.onDeviceOrientationChanged', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.onDeviceOrientationChanged was null.'); + final List args = (message as List?)!; + final DeviceOrientationManager? arg_pigeon_instance = + (args[0] as DeviceOrientationManager?); + assert(arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.onDeviceOrientationChanged was null, expected non-null DeviceOrientationManager.'); + final String? arg_orientation = (args[1] as String?); + assert(arg_orientation != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.onDeviceOrientationChanged was null, expected non-null String.'); + try { + (onDeviceOrientationChanged ?? + arg_pigeon_instance!.onDeviceOrientationChanged) + .call(arg_pigeon_instance!, arg_orientation!); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } + + Future startListeningForDeviceOrientationChange() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecDeviceOrientationManager; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.startListeningForDeviceOrientationChange'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { - return (replyList[0] as List?)!.cast(); + return; } } - Future bindToLifecycle(int arg_identifier, - int arg_cameraSelectorIdentifier, List arg_useCaseIds) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ProcessCameraProviderHostApi.bindToLifecycle', - codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send([ - arg_identifier, - arg_cameraSelectorIdentifier, - arg_useCaseIds - ]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', + Future stopListeningForDeviceOrientationChange() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecDeviceOrientationManager; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.stopListeningForDeviceOrientationChange'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { - return (replyList[0] as int?)!; + return; } } - Future isBound(int arg_identifier, int arg_useCaseIdentifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ProcessCameraProviderHostApi.isBound', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier, arg_useCaseIdentifier]) - as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { + Future getDefaultDisplayRotation() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecDeviceOrientationManager; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.getDefaultDisplayRotation'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as bool?)!; + return (pigeonVar_replyList[0] as int?)!; } } - Future unbind(int arg_identifier, List arg_useCaseIds) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ProcessCameraProviderHostApi.unbind', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_identifier, arg_useCaseIds]) as List?; - if (replyList == null) { + Future getUiOrientation() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecDeviceOrientationManager; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.getUiOrientation'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList.length > 1) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', ); } else { - return; + return (pigeonVar_replyList[0] as String?)!; } } - Future unbindAll(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ProcessCameraProviderHostApi.unbindAll', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } + @override + DeviceOrientationManager pigeon_copy() { + return DeviceOrientationManager.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + onDeviceOrientationChanged: onDeviceOrientationChanged, + ); } } -abstract class ProcessCameraProviderFlutterApi { - static const MessageCodec codec = StandardMessageCodec(); - - void create(int identifier); +/// A use case that provides a camera preview stream for displaying on-screen. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/Preview. +class Preview extends UseCase { + Preview({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + this.resolutionSelector, + int? targetRotation, + }) : super.pigeon_detached() { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecPreview; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Preview.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([ + pigeonVar_instanceIdentifier, + resolutionSelector, + targetRotation + ]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + } - static void setup(ProcessCameraProviderFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { + /// Constructs [Preview] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + Preview.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + this.resolutionSelector, + }) : super.pigeon_detached(); + + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecPreview = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + final ResolutionSelector? resolutionSelector; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + Preview Function(ResolutionSelector? resolutionSelector)? + pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ProcessCameraProviderFlutterApi.create', codec, + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.Preview.pigeon_newInstance', + pigeonChannelCodec, binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); } else { - channel.setMessageHandler((Object? message) async { + pigeonVar_channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.ProcessCameraProviderFlutterApi.create was null.'); + 'Argument for dev.flutter.pigeon.camera_android_camerax.Preview.pigeon_newInstance was null.'); final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ProcessCameraProviderFlutterApi.create was null, expected non-null int.'); - api.create(arg_identifier!); - return; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.Preview.pigeon_newInstance was null, expected non-null int.'); + final ResolutionSelector? arg_resolutionSelector = + (args[1] as ResolutionSelector?); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call(arg_resolutionSelector) ?? + Preview.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + resolutionSelector: arg_resolutionSelector, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } }); } } } -} -class CameraHostApi { - /// Constructor for [CameraHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - CameraHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - - static const MessageCodec codec = StandardMessageCodec(); - - Future getCameraInfo(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraHostApi.getCameraInfo', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { + /// Sets a SurfaceProvider to provide a Surface for Preview. + /// + /// This is a convenience function that + /// 1. Creates a `SurfaceProvider` using the `SurfaceProducer` provided by the + /// Flutter engine. + /// 2. Sets this method with the created `SurfaceProvider`. + /// 3. Returns the texture id of the `TextureEntry` that provided the + /// `SurfaceProducer`. + Future setSurfaceProvider( + SystemServicesManager systemServicesManager) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecPreview; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Preview.setSurfaceProvider'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, systemServicesManager]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as int?)!; + return (pigeonVar_replyList[0] as int?)!; } } - Future getCameraControl(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraHostApi.getCameraControl', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', + /// Releases the `SurfaceProducer` created in `setSurfaceProvider` if one was + /// created. + Future releaseSurfaceProvider() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecPreview; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Preview.releaseSurfaceProvider'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { - return (replyList[0] as int?)!; - } - } -} - -abstract class CameraFlutterApi { - static const MessageCodec codec = StandardMessageCodec(); - - void create(int identifier); - - static void setup(CameraFlutterApi? api, {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraFlutterApi.create', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); - } else { - channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.CameraFlutterApi.create was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.CameraFlutterApi.create was null, expected non-null int.'); - api.create(arg_identifier!); - return; - }); - } + return; } } -} -class _SystemServicesHostApiCodec extends StandardMessageCodec { - const _SystemServicesHostApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is CameraPermissionsErrorData) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); + /// Gets selected resolution information of the `Preview`. + Future getResolutionInfo() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecPreview; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Preview.getResolutionInfo'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); } else { - super.writeValue(buffer, value); - } - } - - @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return CameraPermissionsErrorData.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); + return (pigeonVar_replyList[0] as ResolutionInfo?); } } -} - -class SystemServicesHostApi { - /// Constructor for [SystemServicesHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - SystemServicesHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - static const MessageCodec codec = _SystemServicesHostApiCodec(); - - Future requestCameraPermissions( - bool arg_enableAudio) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.SystemServicesHostApi.requestCameraPermissions', - codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_enableAudio]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + /// Sets the target rotation. + Future setTargetRotation(int rotation) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecPreview; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Preview.setTargetRotation'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, rotation]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { - return (replyList[0] as CameraPermissionsErrorData?); + return; } } - Future getTempFilePath(String arg_prefix, String arg_suffix) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.SystemServicesHostApi.getTempFilePath', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_prefix, arg_suffix]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { + /// Returns whether or not the preview's surface producer handles correctly + /// rotating the camera preview automatically. + Future surfaceProducerHandlesCropAndRotation() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecPreview; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Preview.surfaceProducerHandlesCropAndRotation'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as String?)!; + return (pigeonVar_replyList[0] as bool?)!; } } -} -abstract class SystemServicesFlutterApi { - static const MessageCodec codec = StandardMessageCodec(); + @override + Preview pigeon_copy() { + return Preview.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + resolutionSelector: resolutionSelector, + ); + } +} - void onCameraError(String errorDescription); +/// A use case that provides camera stream suitable for video application. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/video/VideoCapture. +class VideoCapture extends UseCase { + /// Create a `VideoCapture` associated with the given `VideoOutput`. + VideoCapture.withOutput({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required VideoOutput videoOutput, + }) : super.pigeon_detached() { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecVideoCapture; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.VideoCapture.withOutput'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([pigeonVar_instanceIdentifier, videoOutput]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + } - static void setup(SystemServicesFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { + /// Constructs [VideoCapture] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + VideoCapture.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }) : super.pigeon_detached(); + + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecVideoCapture = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + VideoCapture Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.SystemServicesFlutterApi.onCameraError', codec, + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.VideoCapture.pigeon_newInstance', + pigeonChannelCodec, binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); } else { - channel.setMessageHandler((Object? message) async { + pigeonVar_channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.SystemServicesFlutterApi.onCameraError was null.'); + 'Argument for dev.flutter.pigeon.camera_android_camerax.VideoCapture.pigeon_newInstance was null.'); final List args = (message as List?)!; - final String? arg_errorDescription = (args[0] as String?); - assert(arg_errorDescription != null, - 'Argument for dev.flutter.pigeon.SystemServicesFlutterApi.onCameraError was null, expected non-null String.'); - api.onCameraError(arg_errorDescription!); - return; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.VideoCapture.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + VideoCapture.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } }); } } } -} - -class DeviceOrientationManagerHostApi { - /// Constructor for [DeviceOrientationManagerHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - DeviceOrientationManagerHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - static const MessageCodec codec = StandardMessageCodec(); - - Future startListeningForDeviceOrientationChange( - bool arg_isFrontFacing, int arg_sensorOrientation) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.DeviceOrientationManagerHostApi.startListeningForDeviceOrientationChange', - codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_isFrontFacing, arg_sensorOrientation]) - as List?; - if (replyList == null) { + /// Gets the VideoOutput associated with this VideoCapture. + Future getOutput() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecVideoCapture; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.VideoCapture.getOutput'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList.length > 1) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', ); } else { - return; + return (pigeonVar_replyList[0] as VideoOutput?)!; } } - Future stopListeningForDeviceOrientationChange() async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.DeviceOrientationManagerHostApi.stopListeningForDeviceOrientationChange', - codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + /// Sets the desired rotation of the output video. + Future setTargetRotation(int rotation) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecVideoCapture; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.VideoCapture.setTargetRotation'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, rotation]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { return; } } - Future getDefaultDisplayRotation() async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.DeviceOrientationManagerHostApi.getDefaultDisplayRotation', - codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', - ); - } else { - return (replyList[0] as int?)!; - } - } - - Future getUiOrientation() async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.DeviceOrientationManagerHostApi.getUiOrientation', - codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', - ); - } else { - return (replyList[0] as String?)!; - } + @override + VideoCapture pigeon_copy() { + return VideoCapture.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); } } -abstract class DeviceOrientationManagerFlutterApi { - static const MessageCodec codec = StandardMessageCodec(); - - void onDeviceOrientationChanged(String orientation); +/// A class that will produce video data from a Surface. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/video/VideoOutput. +class VideoOutput extends PigeonInternalProxyApiBaseClass { + /// Constructs [VideoOutput] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + VideoOutput.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); - static void setup(DeviceOrientationManagerFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + VideoOutput Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.DeviceOrientationManagerFlutterApi.onDeviceOrientationChanged', - codec, + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.VideoOutput.pigeon_newInstance', + pigeonChannelCodec, binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); } else { - channel.setMessageHandler((Object? message) async { + pigeonVar_channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.DeviceOrientationManagerFlutterApi.onDeviceOrientationChanged was null.'); + 'Argument for dev.flutter.pigeon.camera_android_camerax.VideoOutput.pigeon_newInstance was null.'); final List args = (message as List?)!; - final String? arg_orientation = (args[0] as String?); - assert(arg_orientation != null, - 'Argument for dev.flutter.pigeon.DeviceOrientationManagerFlutterApi.onDeviceOrientationChanged was null, expected non-null String.'); - api.onDeviceOrientationChanged(arg_orientation!); - return; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.VideoOutput.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + VideoOutput.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } }); } } } -} - -class _PreviewHostApiCodec extends StandardMessageCodec { - const _PreviewHostApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is ResolutionInfo) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); - } else { - super.writeValue(buffer, value); - } - } @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return ResolutionInfo.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } + VideoOutput pigeon_copy() { + return VideoOutput.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); } } -class PreviewHostApi { - /// Constructor for [PreviewHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - PreviewHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; +/// An implementation of `VideoOutput` for starting video recordings that are +/// saved to a File, ParcelFileDescriptor, or MediaStore. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/video/Recorder. +class Recorder extends PigeonInternalProxyApiBaseClass implements VideoOutput { + Recorder({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + int? aspectRatio, + int? targetVideoEncodingBitRate, + QualitySelector? qualitySelector, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecRecorder; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Recorder.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + aspectRatio, + targetVideoEncodingBitRate, + qualitySelector + ]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + } - static const MessageCodec codec = _PreviewHostApiCodec(); + /// Constructs [Recorder] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + Recorder.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); - Future create(int arg_identifier, int? arg_rotation, - int? arg_resolutionSelectorId) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.PreviewHostApi.create', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send( - [arg_identifier, arg_rotation, arg_resolutionSelectorId]) - as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecRecorder = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + Recorder Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.Recorder.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.Recorder.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.Recorder.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + Recorder.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } } } - Future setSurfaceProvider(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.PreviewHostApi.setSurfaceProvider', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { + /// Gets the aspect ratio of this Recorder. + Future getAspectRatio() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecRecorder; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Recorder.getAspectRatio'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as int?)!; - } - } - - Future releaseFlutterSurfaceTexture() async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.PreviewHostApi.releaseFlutterSurfaceTexture', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; + return (pigeonVar_replyList[0] as int?)!; } } - Future getResolutionInfo(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.PreviewHostApi.getResolutionInfo', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { + /// Gets the target video encoding bitrate of this Recorder. + Future getTargetVideoEncodingBitRate() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecRecorder; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Recorder.getTargetVideoEncodingBitRate'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as ResolutionInfo?)!; + return (pigeonVar_replyList[0] as int?)!; } } - Future setTargetRotation(int arg_identifier, int arg_rotation) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.PreviewHostApi.setTargetRotation', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_identifier, arg_rotation]) as List?; - if (replyList == null) { + /// The quality selector of this Recorder. + Future getQualitySelector() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecRecorder; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Recorder.getQualitySelector'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList.length > 1) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', ); } else { - return; + return (pigeonVar_replyList[0] as QualitySelector?)!; } } - Future surfaceProducerHandlesCropAndRotation() async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.PreviewHostApi.surfaceProducerHandlesCropAndRotation', - codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { + /// Prepares a recording that will be saved to a File. + Future prepareRecording(String path) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecRecorder; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Recorder.prepareRecording'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, path]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as bool?)!; + return (pigeonVar_replyList[0] as PendingRecording?)!; } } + + @override + Recorder pigeon_copy() { + return Recorder.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } } -class VideoCaptureHostApi { - /// Constructor for [VideoCaptureHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - VideoCaptureHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; +/// Listens for `VideoRecordEvent`s from a `PendingRecording`. +class VideoRecordEventListener extends PigeonInternalProxyApiBaseClass { + VideoRecordEventListener({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.onEvent, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecVideoRecordEventListener; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.VideoRecordEventListener.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([pigeonVar_instanceIdentifier]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + } + + /// Constructs [VideoRecordEventListener] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + VideoRecordEventListener.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.onEvent, + }); - static const MessageCodec codec = StandardMessageCodec(); + late final _PigeonInternalProxyApiBaseCodec + _pigeonVar_codecVideoRecordEventListener = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); - Future withOutput(int arg_videoOutputId) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.VideoCaptureHostApi.withOutput', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_videoOutputId]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', - ); - } else { - return (replyList[0] as int?)!; + /// Callback method. + /// + /// For the associated Native object to be automatically garbage collected, + /// it is required that the implementation of this `Function` doesn't have a + /// strong reference to the encapsulating class instance. When this `Function` + /// references a non-local variable, it is strongly recommended to access it + /// with a `WeakReference`: + /// + /// ```dart + /// final WeakReference weakMyVariable = WeakReference(myVariable); + /// final VideoRecordEventListener instance = VideoRecordEventListener( + /// onEvent: (VideoRecordEventListener pigeon_instance, ...) { + /// print(weakMyVariable?.target); + /// }, + /// ); + /// ``` + /// + /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to + /// release the associated Native object manually. + final void Function( + VideoRecordEventListener pigeon_instance, + VideoRecordEvent event, + ) onEvent; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + void Function( + VideoRecordEventListener pigeon_instance, + VideoRecordEvent event, + )? onEvent, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.VideoRecordEventListener.onEvent', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.VideoRecordEventListener.onEvent was null.'); + final List args = (message as List?)!; + final VideoRecordEventListener? arg_pigeon_instance = + (args[0] as VideoRecordEventListener?); + assert(arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.VideoRecordEventListener.onEvent was null, expected non-null VideoRecordEventListener.'); + final VideoRecordEvent? arg_event = (args[1] as VideoRecordEvent?); + assert(arg_event != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.VideoRecordEventListener.onEvent was null, expected non-null VideoRecordEvent.'); + try { + (onEvent ?? arg_pigeon_instance!.onEvent) + .call(arg_pigeon_instance!, arg_event!); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } + + @override + VideoRecordEventListener pigeon_copy() { + return VideoRecordEventListener.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + onEvent: onEvent, + ); + } +} + +/// A recording that can be started at a future time. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/video/PendingRecording. +class PendingRecording extends PigeonInternalProxyApiBaseClass { + /// Constructs [PendingRecording] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + PendingRecording.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); + + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecPendingRecording = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + PendingRecording Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.PendingRecording.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.PendingRecording.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.PendingRecording.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + PendingRecording.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } } } - Future getOutput(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.VideoCaptureHostApi.getOutput', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { + /// Starts the recording, making it an active recording. + Future start(VideoRecordEventListener listener) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecPendingRecording; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.PendingRecording.start'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, listener]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as int?)!; + return (pigeonVar_replyList[0] as Recording?)!; } } - Future setTargetRotation(int arg_identifier, int arg_rotation) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.VideoCaptureHostApi.setTargetRotation', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_identifier, arg_rotation]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } + @override + PendingRecording pigeon_copy() { + return PendingRecording.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); } } -abstract class VideoCaptureFlutterApi { - static const MessageCodec codec = StandardMessageCodec(); - - void create(int identifier); +/// Provides controls for the currently active recording. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/video/Recording. +class Recording extends PigeonInternalProxyApiBaseClass { + /// Constructs [Recording] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + Recording.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); - static void setup(VideoCaptureFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecRecording = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + Recording Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.VideoCaptureFlutterApi.create', codec, + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.Recording.pigeon_newInstance', + pigeonChannelCodec, binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); } else { - channel.setMessageHandler((Object? message) async { + pigeonVar_channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.VideoCaptureFlutterApi.create was null.'); + 'Argument for dev.flutter.pigeon.camera_android_camerax.Recording.pigeon_newInstance was null.'); final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.VideoCaptureFlutterApi.create was null, expected non-null int.'); - api.create(arg_identifier!); - return; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.Recording.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + Recording.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } }); } } } -} - -class RecorderHostApi { - /// Constructor for [RecorderHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - RecorderHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - static const MessageCodec codec = StandardMessageCodec(); - - Future create(int arg_identifier, int? arg_aspectRatio, - int? arg_bitRate, int? arg_qualitySelectorId) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.RecorderHostApi.create', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send([ - arg_identifier, - arg_aspectRatio, - arg_bitRate, - arg_qualitySelectorId - ]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + /// Close this recording. + Future close() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecRecording; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Recording.close'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { return; } } - Future getAspectRatio(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.RecorderHostApi.getAspectRatio', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', + /// Pauses the current recording if active. + Future pause() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecRecording; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Recording.pause'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { - return (replyList[0] as int?)!; + return; } } - Future getTargetVideoEncodingBitRate(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.RecorderHostApi.getTargetVideoEncodingBitRate', - codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', + /// Resumes the current recording if paused. + Future resume() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecRecording; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Recording.resume'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { - return (replyList[0] as int?)!; + return; } } - Future prepareRecording(int arg_identifier, String arg_path) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.RecorderHostApi.prepareRecording', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_identifier, arg_path]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', + /// Stops the recording, as if calling `close`. + /// + /// This method is equivalent to calling `close`. + Future stop() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecRecording; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Recording.stop'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { - return (replyList[0] as int?)!; + return; } } -} -abstract class RecorderFlutterApi { - static const MessageCodec codec = StandardMessageCodec(); + @override + Recording pigeon_copy() { + return Recording.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } +} - void create(int identifier, int? aspectRatio, int? bitRate); +/// A use case for taking a picture. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageCapture. +class ImageCapture extends UseCase { + ImageCapture({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + this.resolutionSelector, + int? targetRotation, + CameraXFlashMode? flashMode, + }) : super.pigeon_detached() { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecImageCapture; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ImageCapture.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([ + pigeonVar_instanceIdentifier, + resolutionSelector, + targetRotation, + flashMode + ]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + } - static void setup(RecorderFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { + /// Constructs [ImageCapture] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + ImageCapture.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + this.resolutionSelector, + }) : super.pigeon_detached(); + + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecImageCapture = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + final ResolutionSelector? resolutionSelector; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + ImageCapture Function(ResolutionSelector? resolutionSelector)? + pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.RecorderFlutterApi.create', codec, + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.ImageCapture.pigeon_newInstance', + pigeonChannelCodec, binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); } else { - channel.setMessageHandler((Object? message) async { + pigeonVar_channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.RecorderFlutterApi.create was null.'); + 'Argument for dev.flutter.pigeon.camera_android_camerax.ImageCapture.pigeon_newInstance was null.'); final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.RecorderFlutterApi.create was null, expected non-null int.'); - final int? arg_aspectRatio = (args[1] as int?); - final int? arg_bitRate = (args[2] as int?); - api.create(arg_identifier!, arg_aspectRatio, arg_bitRate); - return; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ImageCapture.pigeon_newInstance was null, expected non-null int.'); + final ResolutionSelector? arg_resolutionSelector = + (args[1] as ResolutionSelector?); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call(arg_resolutionSelector) ?? + ImageCapture.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + resolutionSelector: arg_resolutionSelector, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } }); } } } -} - -class PendingRecordingHostApi { - /// Constructor for [PendingRecordingHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - PendingRecordingHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - static const MessageCodec codec = StandardMessageCodec(); - - Future start(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.PendingRecordingHostApi.start', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', + /// Set the flash mode. + Future setFlashMode(CameraXFlashMode flashMode) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecImageCapture; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ImageCapture.setFlashMode'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, flashMode]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList.length > 1) { + } else { + return; + } + } + + /// Captures a new still image for in memory access. + Future takePicture() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecImageCapture; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ImageCapture.takePicture'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as int?)!; + return (pigeonVar_replyList[0] as String?)!; } } -} -class _PendingRecordingFlutterApiCodec extends StandardMessageCodec { - const _PendingRecordingFlutterApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is VideoRecordEventData) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); + /// Sets the desired rotation of the output image. + Future setTargetRotation(int rotation) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecImageCapture; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ImageCapture.setTargetRotation'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, rotation]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); } else { - super.writeValue(buffer, value); + return; } } @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return VideoRecordEventData.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } + ImageCapture pigeon_copy() { + return ImageCapture.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + resolutionSelector: resolutionSelector, + ); } } -abstract class PendingRecordingFlutterApi { - static const MessageCodec codec = _PendingRecordingFlutterApiCodec(); - - void create(int identifier); - - void onVideoRecordingEvent(VideoRecordEventData event); - - static void setup(PendingRecordingFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.PendingRecordingFlutterApi.create', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); +/// The resolution strategy defines the resolution selection sequence to select +/// the best size. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/resolutionselector/ResolutionStrategy. +class ResolutionStrategy extends PigeonInternalProxyApiBaseClass { + ResolutionStrategy({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required CameraSize boundSize, + required ResolutionStrategyFallbackRule fallbackRule, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecResolutionStrategy; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([pigeonVar_instanceIdentifier, boundSize, fallbackRule]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); } else { - channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.PendingRecordingFlutterApi.create was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.PendingRecordingFlutterApi.create was null, expected non-null int.'); - api.create(arg_identifier!); - return; - }); + return; } - } + }(); + } + + /// Constructs [ResolutionStrategy] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + ResolutionStrategy.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); + + late final _PigeonInternalProxyApiBaseCodec + _pigeonVar_codecResolutionStrategy = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + /// A resolution strategy chooses the highest available resolution. + static final ResolutionStrategy highestAvailableStrategy = + pigeonVar_highestAvailableStrategy(); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + ResolutionStrategy Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.PendingRecordingFlutterApi.onVideoRecordingEvent', - codec, + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.pigeon_newInstance', + pigeonChannelCodec, binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); } else { - channel.setMessageHandler((Object? message) async { + pigeonVar_channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.PendingRecordingFlutterApi.onVideoRecordingEvent was null.'); + 'Argument for dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.pigeon_newInstance was null.'); final List args = (message as List?)!; - final VideoRecordEventData? arg_event = - (args[0] as VideoRecordEventData?); - assert(arg_event != null, - 'Argument for dev.flutter.pigeon.PendingRecordingFlutterApi.onVideoRecordingEvent was null, expected non-null VideoRecordEventData.'); - api.onVideoRecordingEvent(arg_event!); - return; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + ResolutionStrategy.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } }); } } } -} - -class RecordingHostApi { - /// Constructor for [RecordingHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - RecordingHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - - static const MessageCodec codec = StandardMessageCodec(); - Future close(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.RecordingHostApi.close', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + static ResolutionStrategy pigeonVar_highestAvailableStrategy() { + final ResolutionStrategy pigeonVar_instance = + ResolutionStrategy.pigeon_detached(); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance); + final BinaryMessenger pigeonVar_binaryMessenger = + ServicesBinding.instance.defaultBinaryMessenger; + final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance + .addDartCreatedInstance(pigeonVar_instance); + () async { + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.highestAvailableStrategy'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([pigeonVar_instanceIdentifier]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + return pigeonVar_instance; + } + + /// The specified bound size. + Future getBoundSize() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecResolutionStrategy; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.getBoundSize'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { - return; + return (pigeonVar_replyList[0] as CameraSize?); } } - Future pause(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.RecordingHostApi.pause', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { + /// The fallback rule for choosing an alternate size when the specified bound + /// size is unavailable. + Future getFallbackRule() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecResolutionStrategy; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.getFallbackRule'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList.length > 1) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', ); } else { - return; + return (pigeonVar_replyList[0] as ResolutionStrategyFallbackRule?)!; } } - Future resume(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.RecordingHostApi.resume', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; + @override + ResolutionStrategy pigeon_copy() { + return ResolutionStrategy.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } +} + +/// A set of requirements and priorities used to select a resolution for the +/// `UseCase`. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/resolutionselector/ResolutionSelector. +class ResolutionSelector extends PigeonInternalProxyApiBaseClass { + ResolutionSelector({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + this.resolutionFilter, + this.resolutionStrategy, + AspectRatioStrategy? aspectRatioStrategy, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecResolutionSelector; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ResolutionSelector.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([ + pigeonVar_instanceIdentifier, + resolutionFilter, + resolutionStrategy, + aspectRatioStrategy + ]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + } + + /// Constructs [ResolutionSelector] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + ResolutionSelector.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + this.resolutionFilter, + this.resolutionStrategy, + }); + + late final _PigeonInternalProxyApiBaseCodec + _pigeonVar_codecResolutionSelector = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + /// The resolution filter to output the final desired sizes list. + final ResolutionFilter? resolutionFilter; + + /// The resolution selection strategy for the `UseCase`. + final ResolutionStrategy? resolutionStrategy; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + ResolutionSelector Function( + ResolutionFilter? resolutionFilter, + ResolutionStrategy? resolutionStrategy, + )? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.ResolutionSelector.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ResolutionSelector.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ResolutionSelector.pigeon_newInstance was null, expected non-null int.'); + final ResolutionFilter? arg_resolutionFilter = + (args[1] as ResolutionFilter?); + final ResolutionStrategy? arg_resolutionStrategy = + (args[2] as ResolutionStrategy?); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call( + arg_resolutionFilter, arg_resolutionStrategy) ?? + ResolutionSelector.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + resolutionFilter: arg_resolutionFilter, + resolutionStrategy: arg_resolutionStrategy, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } } } - Future stop(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.RecordingHostApi.stop', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { + /// Returns the specified `AspectRatioStrategy`, or + /// `AspectRatioStrategy.ratio_4_3FallbackAutoStrategy` if none is specified + /// when creating the ResolutionSelector. + Future getAspectRatioStrategy() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecResolutionSelector; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ResolutionSelector.getAspectRatioStrategy'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList.length > 1) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', ); } else { - return; + return (pigeonVar_replyList[0] as AspectRatioStrategy?)!; } } + + @override + ResolutionSelector pigeon_copy() { + return ResolutionSelector.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + resolutionFilter: resolutionFilter, + resolutionStrategy: resolutionStrategy, + ); + } } -abstract class RecordingFlutterApi { - static const MessageCodec codec = StandardMessageCodec(); +/// The aspect ratio strategy defines the sequence of aspect ratios that are +/// used to select the best size for a particular image. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/resolutionselector/AspectRatioStrategy. +class AspectRatioStrategy extends PigeonInternalProxyApiBaseClass { + /// Creates a new AspectRatioStrategy instance, configured with the specified + /// preferred aspect ratio and fallback rule. + AspectRatioStrategy({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required AspectRatio preferredAspectRatio, + required AspectRatioStrategyFallbackRule fallbackRule, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecAspectRatioStrategy; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([ + pigeonVar_instanceIdentifier, + preferredAspectRatio, + fallbackRule + ]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + } - void create(int identifier); + /// Constructs [AspectRatioStrategy] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + AspectRatioStrategy.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); - static void setup(RecordingFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { + late final _PigeonInternalProxyApiBaseCodec + _pigeonVar_codecAspectRatioStrategy = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + /// The pre-defined aspect ratio strategy that selects sizes with RATIO_16_9 + /// in priority. + static final AspectRatioStrategy ratio_16_9FallbackAutoStrategy = + pigeonVar_ratio_16_9FallbackAutoStrategy(); + + /// The pre-defined default aspect ratio strategy that selects sizes with + /// RATIO_4_3 in priority. + static final AspectRatioStrategy ratio_4_3FallbackAutoStrategy = + pigeonVar_ratio_4_3FallbackAutoStrategy(); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + AspectRatioStrategy Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.RecordingFlutterApi.create', codec, + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.pigeon_newInstance', + pigeonChannelCodec, binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); } else { - channel.setMessageHandler((Object? message) async { + pigeonVar_channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.RecordingFlutterApi.create was null.'); + 'Argument for dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.pigeon_newInstance was null.'); final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.RecordingFlutterApi.create was null, expected non-null int.'); - api.create(arg_identifier!); - return; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + AspectRatioStrategy.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } }); } } } -} - -class ImageCaptureHostApi { - /// Constructor for [ImageCaptureHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - ImageCaptureHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - - static const MessageCodec codec = StandardMessageCodec(); - - Future create(int arg_identifier, int? arg_targetRotation, - int? arg_flashMode, int? arg_resolutionSelectorId) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ImageCaptureHostApi.create', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send([ - arg_identifier, - arg_targetRotation, - arg_flashMode, - arg_resolutionSelectorId - ]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } - } - Future setFlashMode(int arg_identifier, int arg_flashMode) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ImageCaptureHostApi.setFlashMode', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_identifier, arg_flashMode]) as List?; - if (replyList == null) { + static AspectRatioStrategy pigeonVar_ratio_16_9FallbackAutoStrategy() { + final AspectRatioStrategy pigeonVar_instance = + AspectRatioStrategy.pigeon_detached(); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance); + final BinaryMessenger pigeonVar_binaryMessenger = + ServicesBinding.instance.defaultBinaryMessenger; + final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance + .addDartCreatedInstance(pigeonVar_instance); + () async { + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.ratio_16_9FallbackAutoStrategy'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([pigeonVar_instanceIdentifier]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + return pigeonVar_instance; + } + + static AspectRatioStrategy pigeonVar_ratio_4_3FallbackAutoStrategy() { + final AspectRatioStrategy pigeonVar_instance = + AspectRatioStrategy.pigeon_detached(); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance); + final BinaryMessenger pigeonVar_binaryMessenger = + ServicesBinding.instance.defaultBinaryMessenger; + final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance + .addDartCreatedInstance(pigeonVar_instance); + () async { + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.ratio_4_3FallbackAutoStrategy'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([pigeonVar_instanceIdentifier]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + return pigeonVar_instance; + } + + /// The specified fallback rule for choosing the aspect ratio when the + /// preferred aspect ratio is not available. + Future getFallbackRule() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecAspectRatioStrategy; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.getFallbackRule'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList.length > 1) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', ); } else { - return; + return (pigeonVar_replyList[0] as AspectRatioStrategyFallbackRule?)!; } } - Future takePicture(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ImageCaptureHostApi.takePicture', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { + /// The specified preferred aspect ratio. + Future getPreferredAspectRatio() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecAspectRatioStrategy; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.getPreferredAspectRatio'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as String?)!; + return (pigeonVar_replyList[0] as AspectRatio?)!; } } - Future setTargetRotation(int arg_identifier, int arg_rotation) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ImageCaptureHostApi.setTargetRotation', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_identifier, arg_rotation]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; + @override + AspectRatioStrategy pigeon_copy() { + return AspectRatioStrategy.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } +} + +/// Represents the different states the camera can be in. +/// +/// See https://developer.android.com/reference/androidx/camera/core/CameraState. +class CameraState extends PigeonInternalProxyApiBaseClass { + /// Constructs [CameraState] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + CameraState.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.type, + this.error, + }); + + /// The camera's state. + final CameraStateType type; + + /// Potentially returns an error the camera encountered. + final CameraStateStateError? error; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + CameraState Function( + CameraStateType type, + CameraStateStateError? error, + )? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.CameraState.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraState.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraState.pigeon_newInstance was null, expected non-null int.'); + final CameraStateType? arg_type = (args[1] as CameraStateType?); + assert(arg_type != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraState.pigeon_newInstance was null, expected non-null CameraStateType.'); + final CameraStateStateError? arg_error = + (args[2] as CameraStateStateError?); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call(arg_type!, arg_error) ?? + CameraState.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + type: arg_type!, + error: arg_error, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } } } + + @override + CameraState pigeon_copy() { + return CameraState.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + type: type, + error: error, + ); + } } -class _ResolutionStrategyHostApiCodec extends StandardMessageCodec { - const _ResolutionStrategyHostApiCodec(); +/// An interface which contains the camera exposure related information. +/// +/// See https://developer.android.com/reference/androidx/camera/core/ExposureState. +class ExposureState extends PigeonInternalProxyApiBaseClass { + /// Constructs [ExposureState] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + ExposureState.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.exposureCompensationRange, + required this.exposureCompensationStep, + }); + + /// Get the maximum and minimum exposure compensation values for + /// `CameraControl.setExposureCompensationIndex`. + final CameraIntegerRange exposureCompensationRange; + + /// Get the smallest step by which the exposure compensation can be changed. + final double exposureCompensationStep; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + ExposureState Function( + CameraIntegerRange exposureCompensationRange, + double exposureCompensationStep, + )? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.ExposureState.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ExposureState.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ExposureState.pigeon_newInstance was null, expected non-null int.'); + final CameraIntegerRange? arg_exposureCompensationRange = + (args[1] as CameraIntegerRange?); + assert(arg_exposureCompensationRange != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ExposureState.pigeon_newInstance was null, expected non-null CameraIntegerRange.'); + final double? arg_exposureCompensationStep = (args[2] as double?); + assert(arg_exposureCompensationStep != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ExposureState.pigeon_newInstance was null, expected non-null double.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call(arg_exposureCompensationRange!, + arg_exposureCompensationStep!) ?? + ExposureState.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + exposureCompensationRange: arg_exposureCompensationRange!, + exposureCompensationStep: arg_exposureCompensationStep!, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } + @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is ResolutionInfo) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); - } else { - super.writeValue(buffer, value); + ExposureState pigeon_copy() { + return ExposureState.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + exposureCompensationRange: exposureCompensationRange, + exposureCompensationStep: exposureCompensationStep, + ); + } +} + +/// An interface which contains the zoom related information from a camera. +/// +/// See https://developer.android.com/reference/androidx/camera/core/ZoomState. +class ZoomState extends PigeonInternalProxyApiBaseClass { + /// Constructs [ZoomState] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + ZoomState.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.minZoomRatio, + required this.maxZoomRatio, + }); + + /// The minimum zoom ratio. + final double minZoomRatio; + + /// The maximum zoom ratio. + final double maxZoomRatio; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + ZoomState Function( + double minZoomRatio, + double maxZoomRatio, + )? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.ZoomState.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ZoomState.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ZoomState.pigeon_newInstance was null, expected non-null int.'); + final double? arg_minZoomRatio = (args[1] as double?); + assert(arg_minZoomRatio != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ZoomState.pigeon_newInstance was null, expected non-null double.'); + final double? arg_maxZoomRatio = (args[2] as double?); + assert(arg_maxZoomRatio != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ZoomState.pigeon_newInstance was null, expected non-null double.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call(arg_minZoomRatio!, arg_maxZoomRatio!) ?? + ZoomState.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + minZoomRatio: arg_minZoomRatio!, + maxZoomRatio: arg_maxZoomRatio!, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } } } @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return ResolutionInfo.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } + ZoomState pigeon_copy() { + return ZoomState.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + minZoomRatio: minZoomRatio, + maxZoomRatio: maxZoomRatio, + ); } } -class ResolutionStrategyHostApi { - /// Constructor for [ResolutionStrategyHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - ResolutionStrategyHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; +/// A use case providing CPU accessible images for an app to perform image +/// analysis on. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageAnalysis. +class ImageAnalysis extends UseCase { + ImageAnalysis({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + this.resolutionSelector, + int? targetRotation, + }) : super.pigeon_detached() { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecImageAnalysis; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([ + pigeonVar_instanceIdentifier, + resolutionSelector, + targetRotation + ]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + } - static const MessageCodec codec = _ResolutionStrategyHostApiCodec(); + /// Constructs [ImageAnalysis] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + ImageAnalysis.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + this.resolutionSelector, + }) : super.pigeon_detached(); + + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecImageAnalysis = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + final ResolutionSelector? resolutionSelector; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + ImageAnalysis Function(ResolutionSelector? resolutionSelector)? + pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.pigeon_newInstance was null, expected non-null int.'); + final ResolutionSelector? arg_resolutionSelector = + (args[1] as ResolutionSelector?); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call(arg_resolutionSelector) ?? + ImageAnalysis.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + resolutionSelector: arg_resolutionSelector, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } - Future create(int arg_identifier, ResolutionInfo? arg_boundSize, - int? arg_fallbackRule) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ResolutionStrategyHostApi.create', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_identifier, arg_boundSize, arg_fallbackRule]) - as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + /// Sets an analyzer to receive and analyze images. + Future setAnalyzer(Analyzer analyzer) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecImageAnalysis; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.setAnalyzer'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, analyzer]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { return; } } -} -class ResolutionSelectorHostApi { - /// Constructor for [ResolutionSelectorHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - ResolutionSelectorHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - - static const MessageCodec codec = StandardMessageCodec(); - - Future create( - int arg_identifier, - int? arg_resolutionStrategyIdentifier, - int? arg_resolutionSelectorIdentifier, - int? arg_aspectRatioStrategyIdentifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ResolutionSelectorHostApi.create', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send([ - arg_identifier, - arg_resolutionStrategyIdentifier, - arg_resolutionSelectorIdentifier, - arg_aspectRatioStrategyIdentifier - ]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + /// Removes a previously set analyzer. + Future clearAnalyzer() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecImageAnalysis; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.clearAnalyzer'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { return; } } -} - -class AspectRatioStrategyHostApi { - /// Constructor for [AspectRatioStrategyHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - AspectRatioStrategyHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - static const MessageCodec codec = StandardMessageCodec(); - - Future create(int arg_identifier, int arg_preferredAspectRatio, - int arg_fallbackRule) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.AspectRatioStrategyHostApi.create', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send([ - arg_identifier, - arg_preferredAspectRatio, - arg_fallbackRule - ]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + /// Sets the target rotation. + Future setTargetRotation(int rotation) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecImageAnalysis; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.setTargetRotation'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, rotation]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { return; } } -} -class _CameraStateFlutterApiCodec extends StandardMessageCodec { - const _CameraStateFlutterApiCodec(); @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is CameraStateTypeData) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); - } else { - super.writeValue(buffer, value); - } + ImageAnalysis pigeon_copy() { + return ImageAnalysis.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + resolutionSelector: resolutionSelector, + ); } +} - @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return CameraStateTypeData.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } +/// Interface for analyzing images. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageAnalysis.Analyzer. +class Analyzer extends PigeonInternalProxyApiBaseClass { + Analyzer({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.analyze, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecAnalyzer; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Analyzer.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([pigeonVar_instanceIdentifier]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); } -} -abstract class CameraStateFlutterApi { - static const MessageCodec codec = _CameraStateFlutterApiCodec(); + /// Constructs [Analyzer] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + Analyzer.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.analyze, + }); - void create(int identifier, CameraStateTypeData type, int? errorIdentifier); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecAnalyzer = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); - static void setup(CameraStateFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { + /// Analyzes an image to produce a result. + /// + /// For the associated Native object to be automatically garbage collected, + /// it is required that the implementation of this `Function` doesn't have a + /// strong reference to the encapsulating class instance. When this `Function` + /// references a non-local variable, it is strongly recommended to access it + /// with a `WeakReference`: + /// + /// ```dart + /// final WeakReference weakMyVariable = WeakReference(myVariable); + /// final Analyzer instance = Analyzer( + /// analyze: (Analyzer pigeon_instance, ...) { + /// print(weakMyVariable?.target); + /// }, + /// ); + /// ``` + /// + /// Alternatively, [PigeonInstanceManager.removeWeakReference] can be used to + /// release the associated Native object manually. + final void Function( + Analyzer pigeon_instance, + ImageProxy image, + ) analyze; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + void Function( + Analyzer pigeon_instance, + ImageProxy image, + )? analyze, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraStateFlutterApi.create', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + 'dev.flutter.pigeon.camera_android_camerax.Analyzer.analyze', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); } else { - channel.setMessageHandler((Object? message) async { + pigeonVar_channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.CameraStateFlutterApi.create was null.'); + 'Argument for dev.flutter.pigeon.camera_android_camerax.Analyzer.analyze was null.'); final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.CameraStateFlutterApi.create was null, expected non-null int.'); - final CameraStateTypeData? arg_type = - (args[1] as CameraStateTypeData?); - assert(arg_type != null, - 'Argument for dev.flutter.pigeon.CameraStateFlutterApi.create was null, expected non-null CameraStateTypeData.'); - final int? arg_errorIdentifier = (args[2] as int?); - api.create(arg_identifier!, arg_type!, arg_errorIdentifier); - return; + final Analyzer? arg_pigeon_instance = (args[0] as Analyzer?); + assert(arg_pigeon_instance != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.Analyzer.analyze was null, expected non-null Analyzer.'); + final ImageProxy? arg_image = (args[1] as ImageProxy?); + assert(arg_image != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.Analyzer.analyze was null, expected non-null ImageProxy.'); + try { + (analyze ?? arg_pigeon_instance!.analyze) + .call(arg_pigeon_instance!, arg_image!); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } }); } } } -} - -class _ExposureStateFlutterApiCodec extends StandardMessageCodec { - const _ExposureStateFlutterApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is ExposureCompensationRange) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); - } else { - super.writeValue(buffer, value); - } - } @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return ExposureCompensationRange.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } + Analyzer pigeon_copy() { + return Analyzer.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + analyze: analyze, + ); } } -abstract class ExposureStateFlutterApi { - static const MessageCodec codec = _ExposureStateFlutterApiCodec(); - - void create( - int identifier, - ExposureCompensationRange exposureCompensationRange, - double exposureCompensationStep); +/// Error that the camera has encountered. +/// +/// See https://developer.android.com/reference/androidx/camera/core/CameraState.StateError. +class CameraStateStateError extends PigeonInternalProxyApiBaseClass { + /// Constructs [CameraStateStateError] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + CameraStateStateError.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.code, + }); - static void setup(ExposureStateFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { + /// The code of this error. + final CameraStateErrorCode code; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + CameraStateStateError Function(CameraStateErrorCode code)? + pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ExposureStateFlutterApi.create', codec, + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.CameraStateStateError.pigeon_newInstance', + pigeonChannelCodec, binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); } else { - channel.setMessageHandler((Object? message) async { + pigeonVar_channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.ExposureStateFlutterApi.create was null.'); + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraStateStateError.pigeon_newInstance was null.'); final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ExposureStateFlutterApi.create was null, expected non-null int.'); - final ExposureCompensationRange? arg_exposureCompensationRange = - (args[1] as ExposureCompensationRange?); - assert(arg_exposureCompensationRange != null, - 'Argument for dev.flutter.pigeon.ExposureStateFlutterApi.create was null, expected non-null ExposureCompensationRange.'); - final double? arg_exposureCompensationStep = (args[2] as double?); - assert(arg_exposureCompensationStep != null, - 'Argument for dev.flutter.pigeon.ExposureStateFlutterApi.create was null, expected non-null double.'); - api.create(arg_identifier!, arg_exposureCompensationRange!, - arg_exposureCompensationStep!); - return; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraStateStateError.pigeon_newInstance was null, expected non-null int.'); + final CameraStateErrorCode? arg_code = + (args[1] as CameraStateErrorCode?); + assert(arg_code != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraStateStateError.pigeon_newInstance was null, expected non-null CameraStateErrorCode.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call(arg_code!) ?? + CameraStateStateError.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + code: arg_code!, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } }); } } } -} -abstract class ZoomStateFlutterApi { - static const MessageCodec codec = StandardMessageCodec(); + @override + CameraStateStateError pigeon_copy() { + return CameraStateStateError.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + code: code, + ); + } +} - void create(int identifier, double minZoomRatio, double maxZoomRatio); +/// LiveData is a data holder class that can be observed within a given +/// lifecycle. +/// +/// This is a wrapper around the native class to better support the generic +/// type. Java has type erasure; +/// +/// See https://developer.android.com/reference/androidx/lifecycle/LiveData. +class LiveData extends PigeonInternalProxyApiBaseClass { + /// Constructs [LiveData] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + LiveData.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.type, + }); - static void setup(ZoomStateFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecLiveData = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + /// The generic type used by this instance. + final LiveDataSupportedType type; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + LiveData Function(LiveDataSupportedType type)? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ZoomStateFlutterApi.create', codec, + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.LiveData.pigeon_newInstance', + pigeonChannelCodec, binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); } else { - channel.setMessageHandler((Object? message) async { + pigeonVar_channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.ZoomStateFlutterApi.create was null.'); + 'Argument for dev.flutter.pigeon.camera_android_camerax.LiveData.pigeon_newInstance was null.'); final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ZoomStateFlutterApi.create was null, expected non-null int.'); - final double? arg_minZoomRatio = (args[1] as double?); - assert(arg_minZoomRatio != null, - 'Argument for dev.flutter.pigeon.ZoomStateFlutterApi.create was null, expected non-null double.'); - final double? arg_maxZoomRatio = (args[2] as double?); - assert(arg_maxZoomRatio != null, - 'Argument for dev.flutter.pigeon.ZoomStateFlutterApi.create was null, expected non-null double.'); - api.create(arg_identifier!, arg_minZoomRatio!, arg_maxZoomRatio!); - return; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.LiveData.pigeon_newInstance was null, expected non-null int.'); + final LiveDataSupportedType? arg_type = + (args[1] as LiveDataSupportedType?); + assert(arg_type != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.LiveData.pigeon_newInstance was null, expected non-null LiveDataSupportedType.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call(arg_type!) ?? + LiveData.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + type: arg_type!, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } }); } } } -} - -class ImageAnalysisHostApi { - /// Constructor for [ImageAnalysisHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - ImageAnalysisHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - static const MessageCodec codec = StandardMessageCodec(); - - Future create(int arg_identifier, int? arg_targetRotation, - int? arg_resolutionSelectorId) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ImageAnalysisHostApi.create', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send([ - arg_identifier, - arg_targetRotation, - arg_resolutionSelectorId - ]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + /// Adds the given observer to the observers list within the lifespan of the + /// given owner. + Future observe(Observer observer) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecLiveData; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.LiveData.observe'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, observer]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { return; } } - Future setAnalyzer( - int arg_identifier, int arg_analyzerIdentifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ImageAnalysisHostApi.setAnalyzer', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier, arg_analyzerIdentifier]) - as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + /// Removes all observers that are tied to the given `LifecycleOwner`. + Future removeObservers() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecLiveData; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.LiveData.removeObservers'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { return; } } - Future clearAnalyzer(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ImageAnalysisHostApi.clearAnalyzer', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + /// Returns the current value. + Future getValue() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecLiveData; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.LiveData.getValue'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { - return; + return pigeonVar_replyList[0]; } } - Future setTargetRotation(int arg_identifier, int arg_rotation) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ImageAnalysisHostApi.setTargetRotation', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_identifier, arg_rotation]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } + @override + LiveData pigeon_copy() { + return LiveData.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + type: type, + ); } } -class AnalyzerHostApi { - /// Constructor for [AnalyzerHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - AnalyzerHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; +/// An image proxy which has a similar interface as `android.media.Image`. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageProxy. +class ImageProxy extends PigeonInternalProxyApiBaseClass { + /// Constructs [ImageProxy] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + ImageProxy.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.format, + required this.width, + required this.height, + }); - static const MessageCodec codec = StandardMessageCodec(); + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecImageProxy = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + /// The image format. + final int format; + + /// The image width. + final int width; + + /// The image height. + final int height; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + ImageProxy Function( + int format, + int width, + int height, + )? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.ImageProxy.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ImageProxy.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ImageProxy.pigeon_newInstance was null, expected non-null int.'); + final int? arg_format = (args[1] as int?); + assert(arg_format != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ImageProxy.pigeon_newInstance was null, expected non-null int.'); + final int? arg_width = (args[2] as int?); + assert(arg_width != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ImageProxy.pigeon_newInstance was null, expected non-null int.'); + final int? arg_height = (args[3] as int?); + assert(arg_height != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ImageProxy.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call(arg_format!, arg_width!, arg_height!) ?? + ImageProxy.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + format: arg_format!, + width: arg_width!, + height: arg_height!, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } - Future create(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.AnalyzerHostApi.create', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { + /// Returns the array of planes. + Future> getPlanes() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecImageProxy; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ImageProxy.getPlanes'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList.length > 1) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } else { + return (pigeonVar_replyList[0] as List?)!.cast(); + } + } + + /// Closes the underlying `android.media.Image`. + Future close() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecImageProxy; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ImageProxy.close'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { return; } } + + @override + ImageProxy pigeon_copy() { + return ImageProxy.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + format: format, + width: width, + height: height, + ); + } +} + +/// A plane proxy which has an analogous interface as +/// `android.media.Image.Plane`. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageProxy.PlaneProxy. +class PlaneProxy extends PigeonInternalProxyApiBaseClass { + /// Constructs [PlaneProxy] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + PlaneProxy.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.buffer, + required this.pixelStride, + required this.rowStride, + }); + + /// The pixels buffer. + final Uint8List buffer; + + /// The pixel stride. + final int pixelStride; + + /// The row stride. + final int rowStride; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + PlaneProxy Function( + Uint8List buffer, + int pixelStride, + int rowStride, + )? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.PlaneProxy.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.PlaneProxy.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.PlaneProxy.pigeon_newInstance was null, expected non-null int.'); + final Uint8List? arg_buffer = (args[1] as Uint8List?); + assert(arg_buffer != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.PlaneProxy.pigeon_newInstance was null, expected non-null Uint8List.'); + final int? arg_pixelStride = (args[2] as int?); + assert(arg_pixelStride != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.PlaneProxy.pigeon_newInstance was null, expected non-null int.'); + final int? arg_rowStride = (args[3] as int?); + assert(arg_rowStride != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.PlaneProxy.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call( + arg_buffer!, arg_pixelStride!, arg_rowStride!) ?? + PlaneProxy.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + buffer: arg_buffer!, + pixelStride: arg_pixelStride!, + rowStride: arg_rowStride!, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } + + @override + PlaneProxy pigeon_copy() { + return PlaneProxy.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + buffer: buffer, + pixelStride: pixelStride, + rowStride: rowStride, + ); + } } -class ObserverHostApi { - /// Constructor for [ObserverHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - ObserverHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; +/// Defines a desired quality setting that can be used to configure components +/// with quality setting requirements such as creating a Recorder. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/video/QualitySelector. +class QualitySelector extends PigeonInternalProxyApiBaseClass { + /// Gets an instance of QualitySelector with a desired quality. + QualitySelector.from({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required VideoQuality quality, + FallbackStrategy? fallbackStrategy, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecQualitySelector; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.QualitySelector.from'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier, quality, fallbackStrategy]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + } + + /// Gets an instance of QualitySelector with ordered desired qualities. + QualitySelector.fromOrderedList({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required List qualities, + FallbackStrategy? fallbackStrategy, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecQualitySelector; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.QualitySelector.fromOrderedList'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier, qualities, fallbackStrategy]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + } - static const MessageCodec codec = StandardMessageCodec(); + /// Constructs [QualitySelector] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + QualitySelector.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); - Future create(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ObserverHostApi.create', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecQualitySelector = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + QualitySelector Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.QualitySelector.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.QualitySelector.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.QualitySelector.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + QualitySelector.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } + } + } + + /// Gets the corresponding resolution from the input quality. + static Future getResolution( + CameraInfo cameraInfo, + VideoQuality quality, { + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.QualitySelector.getResolution'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([cameraInfo, quality]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { - return; + return (pigeonVar_replyList[0] as CameraSize?); } } + + @override + QualitySelector pigeon_copy() { + return QualitySelector.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } } -abstract class ObserverFlutterApi { - static const MessageCodec codec = StandardMessageCodec(); +/// A class represents the strategy that will be adopted when the device does +/// not support all the desired Quality in QualitySelector in order to select +/// the quality as possible. +/// +/// See https://developer.android.com/reference/androidx/camera/video/FallbackStrategy. +class FallbackStrategy extends PigeonInternalProxyApiBaseClass { + /// Returns a fallback strategy that will choose the quality that is closest + /// to and higher than the input quality. + FallbackStrategy.higherQualityOrLowerThan({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required VideoQuality quality, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecFallbackStrategy; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.higherQualityOrLowerThan'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([pigeonVar_instanceIdentifier, quality]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + } + + /// Returns a fallback strategy that will choose the quality that is closest + /// to and higher than the input quality. + FallbackStrategy.higherQualityThan({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required VideoQuality quality, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecFallbackStrategy; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.higherQualityThan'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([pigeonVar_instanceIdentifier, quality]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + } + + /// Returns a fallback strategy that will choose the quality that is closest + /// to and lower than the input quality. + FallbackStrategy.lowerQualityOrHigherThan({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required VideoQuality quality, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecFallbackStrategy; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.lowerQualityOrHigherThan'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([pigeonVar_instanceIdentifier, quality]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + } + + /// Returns a fallback strategy that will choose the quality that is closest + /// to and lower than the input quality. + FallbackStrategy.lowerQualityThan({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required VideoQuality quality, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecFallbackStrategy; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.lowerQualityThan'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([pigeonVar_instanceIdentifier, quality]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + } - void onChanged(int identifier, int valueIdentifier); + /// Constructs [FallbackStrategy] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + FallbackStrategy.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); - static void setup(ObserverFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecFallbackStrategy = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + FallbackStrategy Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ObserverFlutterApi.onChanged', codec, + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.pigeon_newInstance', + pigeonChannelCodec, binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); } else { - channel.setMessageHandler((Object? message) async { + pigeonVar_channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.ObserverFlutterApi.onChanged was null.'); + 'Argument for dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.pigeon_newInstance was null.'); final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ObserverFlutterApi.onChanged was null, expected non-null int.'); - final int? arg_valueIdentifier = (args[1] as int?); - assert(arg_valueIdentifier != null, - 'Argument for dev.flutter.pigeon.ObserverFlutterApi.onChanged was null, expected non-null int.'); - api.onChanged(arg_identifier!, arg_valueIdentifier!); - return; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + FallbackStrategy.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } }); } } } + + @override + FallbackStrategy pigeon_copy() { + return FallbackStrategy.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } } -abstract class CameraStateErrorFlutterApi { - static const MessageCodec codec = StandardMessageCodec(); - - void create(int identifier, int code); +/// The CameraControl provides various asynchronous operations like zoom, focus +/// and metering which affects output of all UseCases currently bound to that +/// camera. +/// +/// See https://developer.android.com/reference/androidx/camera/core/CameraControl. +class CameraControl extends PigeonInternalProxyApiBaseClass { + /// Constructs [CameraControl] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + CameraControl.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); - static void setup(CameraStateErrorFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecCameraControl = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + CameraControl Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraStateErrorFlutterApi.create', codec, + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.CameraControl.pigeon_newInstance', + pigeonChannelCodec, binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); } else { - channel.setMessageHandler((Object? message) async { + pigeonVar_channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.CameraStateErrorFlutterApi.create was null.'); + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraControl.pigeon_newInstance was null.'); final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.CameraStateErrorFlutterApi.create was null, expected non-null int.'); - final int? arg_code = (args[1] as int?); - assert(arg_code != null, - 'Argument for dev.flutter.pigeon.CameraStateErrorFlutterApi.create was null, expected non-null int.'); - api.create(arg_identifier!, arg_code!); - return; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraControl.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + CameraControl.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } }); } } } -} -class _LiveDataHostApiCodec extends StandardMessageCodec { - const _LiveDataHostApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is LiveDataSupportedTypeData) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); + /// Enable the torch or disable the torch. + Future enableTorch(bool torch) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecCameraControl; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.CameraControl.enableTorch'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, torch]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); } else { - super.writeValue(buffer, value); - } - } - - @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return LiveDataSupportedTypeData.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); + return; } } -} - -class LiveDataHostApi { - /// Constructor for [LiveDataHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - LiveDataHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - - static const MessageCodec codec = _LiveDataHostApiCodec(); - Future observe(int arg_identifier, int arg_observerIdentifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.LiveDataHostApi.observe', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier, arg_observerIdentifier]) - as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + /// Sets current zoom by ratio. + Future setZoomRatio(double ratio) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecCameraControl; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.CameraControl.setZoomRatio'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, ratio]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { return; } } - Future removeObservers(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.LiveDataHostApi.removeObservers', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + /// Starts a focus and metering action configured by the + /// `FocusMeteringAction`. + Future startFocusAndMetering( + FocusMeteringAction action) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecCameraControl; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.CameraControl.startFocusAndMetering'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, action]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { - return; + return (pigeonVar_replyList[0] as FocusMeteringResult?); } } - Future getValue( - int arg_identifier, LiveDataSupportedTypeData arg_type) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.LiveDataHostApi.getValue', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_identifier, arg_type]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + /// Cancels current FocusMeteringAction and clears AF/AE/AWB regions. + Future cancelFocusAndMetering() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecCameraControl; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.CameraControl.cancelFocusAndMetering'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { - return (replyList[0] as int?); + return; } } -} -class _LiveDataFlutterApiCodec extends StandardMessageCodec { - const _LiveDataFlutterApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is LiveDataSupportedTypeData) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); + /// Set the exposure compensation value for the camera. + Future setExposureCompensationIndex(int index) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecCameraControl; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.CameraControl.setExposureCompensationIndex'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, index]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); } else { - super.writeValue(buffer, value); + return (pigeonVar_replyList[0] as int?); } } @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return LiveDataSupportedTypeData.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } + CameraControl pigeon_copy() { + return CameraControl.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); } } -abstract class LiveDataFlutterApi { - static const MessageCodec codec = _LiveDataFlutterApiCodec(); - - void create(int identifier, LiveDataSupportedTypeData type); - - static void setup(LiveDataFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.LiveDataFlutterApi.create', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); +/// The builder used to create the `FocusMeteringAction`. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/FocusMeteringAction.Builder. +class FocusMeteringActionBuilder extends PigeonInternalProxyApiBaseClass { + /// Creates a Builder from a `MeteringPoint` with default mode FLAG_AF | + /// FLAG_AE | FLAG_AWB. + FocusMeteringActionBuilder({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required MeteringPoint point, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecFocusMeteringActionBuilder; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([pigeonVar_instanceIdentifier, point]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); } else { - channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.LiveDataFlutterApi.create was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.LiveDataFlutterApi.create was null, expected non-null int.'); - final LiveDataSupportedTypeData? arg_type = - (args[1] as LiveDataSupportedTypeData?); - assert(arg_type != null, - 'Argument for dev.flutter.pigeon.LiveDataFlutterApi.create was null, expected non-null LiveDataSupportedTypeData.'); - api.create(arg_identifier!, arg_type!); - return; - }); + return; } - } + }(); + } + + /// Creates a Builder from a `MeteringPoint` and `MeteringMode`. + FocusMeteringActionBuilder.withMode({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required MeteringPoint point, + required MeteringMode mode, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecFocusMeteringActionBuilder; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.withMode'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([pigeonVar_instanceIdentifier, point, mode]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); } -} - -abstract class AnalyzerFlutterApi { - static const MessageCodec codec = StandardMessageCodec(); - void create(int identifier); - - void analyze(int identifier, int imageProxyIdentifier); + /// Constructs [FocusMeteringActionBuilder] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + FocusMeteringActionBuilder.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); - static void setup(AnalyzerFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.AnalyzerFlutterApi.create', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); - } else { - channel.setMessageHandler((Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.AnalyzerFlutterApi.create was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.AnalyzerFlutterApi.create was null, expected non-null int.'); - api.create(arg_identifier!); - return; - }); - } - } + late final _PigeonInternalProxyApiBaseCodec + _pigeonVar_codecFocusMeteringActionBuilder = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + FocusMeteringActionBuilder Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.AnalyzerFlutterApi.analyze', codec, + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.pigeon_newInstance', + pigeonChannelCodec, binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); } else { - channel.setMessageHandler((Object? message) async { + pigeonVar_channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.AnalyzerFlutterApi.analyze was null.'); + 'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.pigeon_newInstance was null.'); final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.AnalyzerFlutterApi.analyze was null, expected non-null int.'); - final int? arg_imageProxyIdentifier = (args[1] as int?); - assert(arg_imageProxyIdentifier != null, - 'Argument for dev.flutter.pigeon.AnalyzerFlutterApi.analyze was null, expected non-null int.'); - api.analyze(arg_identifier!, arg_imageProxyIdentifier!); - return; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + FocusMeteringActionBuilder.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } }); } } } -} - -class ImageProxyHostApi { - /// Constructor for [ImageProxyHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - ImageProxyHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - - static const MessageCodec codec = StandardMessageCodec(); - Future> getPlanes(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ImageProxyHostApi.getPlanes', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', + /// Adds another MeteringPoint with default metering mode. + Future addPoint(MeteringPoint point) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecFocusMeteringActionBuilder; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.addPoint'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, point]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + } else { + return; + } + } + + /// Adds another MeteringPoint with specified meteringMode. + Future addPointWithMode( + MeteringPoint point, + MeteringMode mode, + ) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecFocusMeteringActionBuilder; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.addPointWithMode'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, point, mode]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', + } else { + return; + } + } + + /// Disables the auto-cancel. + Future disableAutoCancel() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecFocusMeteringActionBuilder; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.disableAutoCancel'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { - return (replyList[0] as List?)!.cast(); + return; } } - Future close(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ImageProxyHostApi.close', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { + /// Builds the `FocusMeteringAction` instance. + Future build() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecFocusMeteringActionBuilder; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.build'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList.length > 1) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', ); } else { - return; + return (pigeonVar_replyList[0] as FocusMeteringAction?)!; } } -} -abstract class ImageProxyFlutterApi { - static const MessageCodec codec = StandardMessageCodec(); + @override + FocusMeteringActionBuilder pigeon_copy() { + return FocusMeteringActionBuilder.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } +} - void create(int identifier, int format, int height, int width); +/// A configuration used to trigger a focus and/or metering action. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/FocusMeteringAction. +class FocusMeteringAction extends PigeonInternalProxyApiBaseClass { + /// Constructs [FocusMeteringAction] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + FocusMeteringAction.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.meteringPointsAe, + required this.meteringPointsAf, + required this.meteringPointsAwb, + required this.isAutoCancelEnabled, + }); - static void setup(ImageProxyFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { + /// All MeteringPoints used for AE regions. + final List meteringPointsAe; + + /// All MeteringPoints used for AF regions. + final List meteringPointsAf; + + /// All MeteringPoints used for AWB regions. + final List meteringPointsAwb; + + /// If auto-cancel is enabled or not. + final bool isAutoCancelEnabled; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + FocusMeteringAction Function( + List meteringPointsAe, + List meteringPointsAf, + List meteringPointsAwb, + bool isAutoCancelEnabled, + )? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ImageProxyFlutterApi.create', codec, + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.FocusMeteringAction.pigeon_newInstance', + pigeonChannelCodec, binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); } else { - channel.setMessageHandler((Object? message) async { + pigeonVar_channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.ImageProxyFlutterApi.create was null.'); + 'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringAction.pigeon_newInstance was null.'); final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ImageProxyFlutterApi.create was null, expected non-null int.'); - final int? arg_format = (args[1] as int?); - assert(arg_format != null, - 'Argument for dev.flutter.pigeon.ImageProxyFlutterApi.create was null, expected non-null int.'); - final int? arg_height = (args[2] as int?); - assert(arg_height != null, - 'Argument for dev.flutter.pigeon.ImageProxyFlutterApi.create was null, expected non-null int.'); - final int? arg_width = (args[3] as int?); - assert(arg_width != null, - 'Argument for dev.flutter.pigeon.ImageProxyFlutterApi.create was null, expected non-null int.'); - api.create(arg_identifier!, arg_format!, arg_height!, arg_width!); - return; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringAction.pigeon_newInstance was null, expected non-null int.'); + final List? arg_meteringPointsAe = + (args[1] as List?)?.cast(); + assert(arg_meteringPointsAe != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringAction.pigeon_newInstance was null, expected non-null List.'); + final List? arg_meteringPointsAf = + (args[2] as List?)?.cast(); + assert(arg_meteringPointsAf != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringAction.pigeon_newInstance was null, expected non-null List.'); + final List? arg_meteringPointsAwb = + (args[3] as List?)?.cast(); + assert(arg_meteringPointsAwb != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringAction.pigeon_newInstance was null, expected non-null List.'); + final bool? arg_isAutoCancelEnabled = (args[4] as bool?); + assert(arg_isAutoCancelEnabled != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringAction.pigeon_newInstance was null, expected non-null bool.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call( + arg_meteringPointsAe!, + arg_meteringPointsAf!, + arg_meteringPointsAwb!, + arg_isAutoCancelEnabled!) ?? + FocusMeteringAction.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + meteringPointsAe: arg_meteringPointsAe!, + meteringPointsAf: arg_meteringPointsAf!, + meteringPointsAwb: arg_meteringPointsAwb!, + isAutoCancelEnabled: arg_isAutoCancelEnabled!, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } }); } } } -} -abstract class PlaneProxyFlutterApi { - static const MessageCodec codec = StandardMessageCodec(); + @override + FocusMeteringAction pigeon_copy() { + return FocusMeteringAction.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + meteringPointsAe: meteringPointsAe, + meteringPointsAf: meteringPointsAf, + meteringPointsAwb: meteringPointsAwb, + isAutoCancelEnabled: isAutoCancelEnabled, + ); + } +} - void create(int identifier, Uint8List buffer, int pixelStride, int rowStride); +/// Result of the `CameraControl.startFocusAndMetering`. +/// +/// See https://developer.android.com/reference/androidx/camera/core/FocusMeteringResult. +class FocusMeteringResult extends PigeonInternalProxyApiBaseClass { + /// Constructs [FocusMeteringResult] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + FocusMeteringResult.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required this.isFocusSuccessful, + }); - static void setup(PlaneProxyFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { + /// If auto focus is successful. + final bool isFocusSuccessful; + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + FocusMeteringResult Function(bool isFocusSuccessful)? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.PlaneProxyFlutterApi.create', codec, + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.FocusMeteringResult.pigeon_newInstance', + pigeonChannelCodec, binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); } else { - channel.setMessageHandler((Object? message) async { + pigeonVar_channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.PlaneProxyFlutterApi.create was null.'); + 'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringResult.pigeon_newInstance was null.'); final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.PlaneProxyFlutterApi.create was null, expected non-null int.'); - final Uint8List? arg_buffer = (args[1] as Uint8List?); - assert(arg_buffer != null, - 'Argument for dev.flutter.pigeon.PlaneProxyFlutterApi.create was null, expected non-null Uint8List.'); - final int? arg_pixelStride = (args[2] as int?); - assert(arg_pixelStride != null, - 'Argument for dev.flutter.pigeon.PlaneProxyFlutterApi.create was null, expected non-null int.'); - final int? arg_rowStride = (args[3] as int?); - assert(arg_rowStride != null, - 'Argument for dev.flutter.pigeon.PlaneProxyFlutterApi.create was null, expected non-null int.'); - api.create( - arg_identifier!, arg_buffer!, arg_pixelStride!, arg_rowStride!); - return; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringResult.pigeon_newInstance was null, expected non-null int.'); + final bool? arg_isFocusSuccessful = (args[1] as bool?); + assert(arg_isFocusSuccessful != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.FocusMeteringResult.pigeon_newInstance was null, expected non-null bool.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call(arg_isFocusSuccessful!) ?? + FocusMeteringResult.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + isFocusSuccessful: arg_isFocusSuccessful!, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } }); } } } -} - -class _QualitySelectorHostApiCodec extends StandardMessageCodec { - const _QualitySelectorHostApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is ResolutionInfo) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); - } else if (value is VideoQualityData) { - buffer.putUint8(129); - writeValue(buffer, value.encode()); - } else { - super.writeValue(buffer, value); - } - } @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return ResolutionInfo.decode(readValue(buffer)!); - case 129: - return VideoQualityData.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } + FocusMeteringResult pigeon_copy() { + return FocusMeteringResult.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + isFocusSuccessful: isFocusSuccessful, + ); } } -class QualitySelectorHostApi { - /// Constructor for [QualitySelectorHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - QualitySelectorHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - - static const MessageCodec codec = _QualitySelectorHostApiCodec(); +/// An immutable package of settings and outputs needed to capture a single +/// image from the camera device. +/// +/// See https://developer.android.com/reference/android/hardware/camera2/CaptureRequest. +class CaptureRequest extends PigeonInternalProxyApiBaseClass { + /// Constructs [CaptureRequest] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + CaptureRequest.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); - Future create( - int arg_identifier, - List arg_videoQualityDataList, - int? arg_fallbackStrategyId) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.QualitySelectorHostApi.create', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send([ - arg_identifier, - arg_videoQualityDataList, - arg_fallbackStrategyId - ]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; + /// Whether auto-exposure (AE) is currently locked to its latest calculated + /// values. + /// + /// Value is boolean. + /// + /// This key is available on all devices. + static final CaptureRequestKey controlAELock = pigeonVar_controlAELock(); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + CaptureRequest Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.CaptureRequest.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CaptureRequest.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CaptureRequest.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + CaptureRequest.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } } } - Future getResolution( - int arg_cameraInfoId, VideoQuality arg_quality) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.QualitySelectorHostApi.getResolution', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_cameraInfoId, arg_quality.index]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', - ); - } else { - return (replyList[0] as ResolutionInfo?)!; - } + static CaptureRequestKey pigeonVar_controlAELock() { + final CaptureRequestKey pigeonVar_instance = + CaptureRequestKey.pigeon_detached(); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance); + final BinaryMessenger pigeonVar_binaryMessenger = + ServicesBinding.instance.defaultBinaryMessenger; + final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance + .addDartCreatedInstance(pigeonVar_instance); + () async { + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.CaptureRequest.controlAELock'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([pigeonVar_instanceIdentifier]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + return pigeonVar_instance; } -} -class FallbackStrategyHostApi { - /// Constructor for [FallbackStrategyHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - FallbackStrategyHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - - static const MessageCodec codec = StandardMessageCodec(); - - Future create(int arg_identifier, VideoQuality arg_quality, - VideoResolutionFallbackRule arg_fallbackRule) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FallbackStrategyHostApi.create', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send([ - arg_identifier, - arg_quality.index, - arg_fallbackRule.index - ]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } + @override + CaptureRequest pigeon_copy() { + return CaptureRequest.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); } } -class CameraControlHostApi { - /// Constructor for [CameraControlHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - CameraControlHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - - static const MessageCodec codec = StandardMessageCodec(); +/// A Key is used to do capture request field lookups with CaptureRequest.get or +/// to set fields with `CaptureRequest.Builder.set`. +/// +/// See https://developer.android.com/reference/android/hardware/camera2/CaptureRequest.Key.html. +class CaptureRequestKey extends PigeonInternalProxyApiBaseClass { + /// Constructs [CaptureRequestKey] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + CaptureRequestKey.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); - Future enableTorch(int arg_identifier, bool arg_torch) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraControlHostApi.enableTorch', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_identifier, arg_torch]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + CaptureRequestKey Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.CaptureRequestKey.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CaptureRequestKey.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CaptureRequestKey.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + CaptureRequestKey.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } } } - Future setZoomRatio(int arg_identifier, double arg_ratio) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraControlHostApi.setZoomRatio', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_identifier, arg_ratio]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } + @override + CaptureRequestKey pigeon_copy() { + return CaptureRequestKey.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); } +} - Future startFocusAndMetering( - int arg_identifier, int arg_focusMeteringActionId) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraControlHostApi.startFocusAndMetering', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier, arg_focusMeteringActionId]) - as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return (replyList[0] as int?); - } +/// A bundle of Camera2 capture request options. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/camera2/interop/CaptureRequestOptions. +class CaptureRequestOptions extends PigeonInternalProxyApiBaseClass { + CaptureRequestOptions({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required Map options, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecCaptureRequestOptions; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.CaptureRequestOptions.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([pigeonVar_instanceIdentifier, options]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); } - Future cancelFocusAndMetering(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraControlHostApi.cancelFocusAndMetering', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; + /// Constructs [CaptureRequestOptions] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + CaptureRequestOptions.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); + + late final _PigeonInternalProxyApiBaseCodec + _pigeonVar_codecCaptureRequestOptions = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + CaptureRequestOptions Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.CaptureRequestOptions.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CaptureRequestOptions.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CaptureRequestOptions.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + CaptureRequestOptions.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } } } - Future setExposureCompensationIndex( - int arg_identifier, int arg_index) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraControlHostApi.setExposureCompensationIndex', - codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_identifier, arg_index]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + /// Returns a value for the given CaptureRequestKey or null if it hasn't been + /// set. + Future getCaptureRequestOption(CaptureRequestKey key) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecCaptureRequestOptions; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.CaptureRequestOptions.getCaptureRequestOption'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, key]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); } else { - return (replyList[0] as int?); + return pigeonVar_replyList[0]; } } + + @override + CaptureRequestOptions pigeon_copy() { + return CaptureRequestOptions.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } } -abstract class CameraControlFlutterApi { - static const MessageCodec codec = StandardMessageCodec(); +/// An class that provides ability to interoperate with the +/// 1android.hardware.camera21 APIs. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/camera2/interop/Camera2CameraControl. +class Camera2CameraControl extends PigeonInternalProxyApiBaseClass { + /// Gets the `Camera2CameraControl` from a `CameraControl`. + Camera2CameraControl.from({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required CameraControl cameraControl, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecCamera2CameraControl; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Camera2CameraControl.from'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([pigeonVar_instanceIdentifier, cameraControl]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + } - void create(int identifier); + /// Constructs [Camera2CameraControl] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + Camera2CameraControl.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); - static void setup(CameraControlFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { + late final _PigeonInternalProxyApiBaseCodec + _pigeonVar_codecCamera2CameraControl = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + Camera2CameraControl Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraControlFlutterApi.create', codec, + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.Camera2CameraControl.pigeon_newInstance', + pigeonChannelCodec, binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); } else { - channel.setMessageHandler((Object? message) async { + pigeonVar_channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.CameraControlFlutterApi.create was null.'); + 'Argument for dev.flutter.pigeon.camera_android_camerax.Camera2CameraControl.pigeon_newInstance was null.'); final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.CameraControlFlutterApi.create was null, expected non-null int.'); - api.create(arg_identifier!); - return; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.Camera2CameraControl.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + Camera2CameraControl.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } }); } } } -} -class _FocusMeteringActionHostApiCodec extends StandardMessageCodec { - const _FocusMeteringActionHostApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is MeteringPointInfo) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); + /// Adds a `CaptureRequestOptions` updates the session with the options it + /// contains. + Future addCaptureRequestOptions(CaptureRequestOptions bundle) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecCamera2CameraControl; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Camera2CameraControl.addCaptureRequestOptions'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, bundle]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); } else { - super.writeValue(buffer, value); + return; } } @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return MeteringPointInfo.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } + Camera2CameraControl pigeon_copy() { + return Camera2CameraControl.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); } } -class FocusMeteringActionHostApi { - /// Constructor for [FocusMeteringActionHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - FocusMeteringActionHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; +/// Applications can filter out unsuitable sizes and sort the resolution list in +/// the preferred order by implementing the resolution filter interface. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/resolutionselector/ResolutionFilter. +class ResolutionFilter extends PigeonInternalProxyApiBaseClass { + ResolutionFilter.createWithOnePreferredSize({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required CameraSize preferredSize, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecResolutionFilter; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.ResolutionFilter.createWithOnePreferredSize'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([pigeonVar_instanceIdentifier, preferredSize]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + } - static const MessageCodec codec = _FocusMeteringActionHostApiCodec(); + /// Constructs [ResolutionFilter] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + ResolutionFilter.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); - Future create( - int arg_identifier, - List arg_meteringPointInfos, - bool? arg_disableAutoCancel) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FocusMeteringActionHostApi.create', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send([ - arg_identifier, - arg_meteringPointInfos, - arg_disableAutoCancel - ]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; + late final _PigeonInternalProxyApiBaseCodec _pigeonVar_codecResolutionFilter = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + ResolutionFilter Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.ResolutionFilter.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ResolutionFilter.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.ResolutionFilter.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + ResolutionFilter.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } } } -} - -class FocusMeteringResultHostApi { - /// Constructor for [FocusMeteringResultHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - FocusMeteringResultHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - static const MessageCodec codec = StandardMessageCodec(); - - Future isFocusSuccessful(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FocusMeteringResultHostApi.isFocusSuccessful', - codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', - ); - } else { - return (replyList[0] as bool?)!; - } + @override + ResolutionFilter pigeon_copy() { + return ResolutionFilter.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); } } -abstract class FocusMeteringResultFlutterApi { - static const MessageCodec codec = StandardMessageCodec(); - - void create(int identifier); +/// A Key is used to do camera characteristics field lookups with +/// `CameraCharacteristics.get`. +/// +/// See https://developer.android.com/reference/android/hardware/camera2/CameraCharacteristics.Key.html. +class CameraCharacteristicsKey extends PigeonInternalProxyApiBaseClass { + /// Constructs [CameraCharacteristicsKey] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + CameraCharacteristicsKey.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); - static void setup(FocusMeteringResultFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + CameraCharacteristicsKey Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FocusMeteringResultFlutterApi.create', codec, + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.CameraCharacteristicsKey.pigeon_newInstance', + pigeonChannelCodec, binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); } else { - channel.setMessageHandler((Object? message) async { + pigeonVar_channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.FocusMeteringResultFlutterApi.create was null.'); + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraCharacteristicsKey.pigeon_newInstance was null.'); final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.FocusMeteringResultFlutterApi.create was null, expected non-null int.'); - api.create(arg_identifier!); - return; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraCharacteristicsKey.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + CameraCharacteristicsKey.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } }); } } } -} -class MeteringPointHostApi { - /// Constructor for [MeteringPointHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - MeteringPointHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; + @override + CameraCharacteristicsKey pigeon_copy() { + return CameraCharacteristicsKey.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } +} - static const MessageCodec codec = StandardMessageCodec(); +/// The properties describing a `CameraDevice`. +/// +/// See https://developer.android.com/reference/android/hardware/camera2/CameraCharacteristics. +class CameraCharacteristics extends PigeonInternalProxyApiBaseClass { + /// Constructs [CameraCharacteristics] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + CameraCharacteristics.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); - Future create(int arg_identifier, double arg_x, double arg_y, - double? arg_size, int arg_cameraInfoId) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.MeteringPointHostApi.create', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send( - [arg_identifier, arg_x, arg_y, arg_size, arg_cameraInfoId]) - as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } - } + /// Generally classifies the overall set of the camera device functionality. + /// + /// Value is `InfoSupportedHardwareLevel`. + /// + /// This key is available on all devices. + static final CameraCharacteristicsKey infoSupportedHardwareLevel = + pigeonVar_infoSupportedHardwareLevel(); - Future getDefaultPointSize() async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.MeteringPointHostApi.getDefaultPointSize', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send(null) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', - ); - } else { - return (replyList[0] as double?)!; + /// Clockwise angle through which the output image needs to be rotated to be + /// upright on the device screen in its native orientation.. + /// + /// Value is int. + /// + /// This key is available on all devices. + static final CameraCharacteristicsKey sensorOrientation = + pigeonVar_sensorOrientation(); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + CameraCharacteristics Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.CameraCharacteristics.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraCharacteristics.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraCharacteristics.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + CameraCharacteristics.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } } } -} -class _CaptureRequestOptionsHostApiCodec extends StandardMessageCodec { - const _CaptureRequestOptionsHostApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is CameraPermissionsErrorData) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); - } else if (value is CameraStateTypeData) { - buffer.putUint8(129); - writeValue(buffer, value.encode()); - } else if (value is ExposureCompensationRange) { - buffer.putUint8(130); - writeValue(buffer, value.encode()); - } else if (value is LiveDataSupportedTypeData) { - buffer.putUint8(131); - writeValue(buffer, value.encode()); - } else if (value is MeteringPointInfo) { - buffer.putUint8(132); - writeValue(buffer, value.encode()); - } else if (value is ResolutionInfo) { - buffer.putUint8(133); - writeValue(buffer, value.encode()); - } else if (value is VideoQualityData) { - buffer.putUint8(134); - writeValue(buffer, value.encode()); - } else if (value is VideoRecordEventData) { - buffer.putUint8(135); - writeValue(buffer, value.encode()); - } else { - super.writeValue(buffer, value); - } + static CameraCharacteristicsKey pigeonVar_infoSupportedHardwareLevel() { + final CameraCharacteristicsKey pigeonVar_instance = + CameraCharacteristicsKey.pigeon_detached(); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance); + final BinaryMessenger pigeonVar_binaryMessenger = + ServicesBinding.instance.defaultBinaryMessenger; + final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance + .addDartCreatedInstance(pigeonVar_instance); + () async { + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.CameraCharacteristics.infoSupportedHardwareLevel'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([pigeonVar_instanceIdentifier]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + return pigeonVar_instance; + } + + static CameraCharacteristicsKey pigeonVar_sensorOrientation() { + final CameraCharacteristicsKey pigeonVar_instance = + CameraCharacteristicsKey.pigeon_detached(); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec(PigeonInstanceManager.instance); + final BinaryMessenger pigeonVar_binaryMessenger = + ServicesBinding.instance.defaultBinaryMessenger; + final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance + .addDartCreatedInstance(pigeonVar_instance); + () async { + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.CameraCharacteristics.sensorOrientation'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([pigeonVar_instanceIdentifier]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + return pigeonVar_instance; } @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return CameraPermissionsErrorData.decode(readValue(buffer)!); - case 129: - return CameraStateTypeData.decode(readValue(buffer)!); - case 130: - return ExposureCompensationRange.decode(readValue(buffer)!); - case 131: - return LiveDataSupportedTypeData.decode(readValue(buffer)!); - case 132: - return MeteringPointInfo.decode(readValue(buffer)!); - case 133: - return ResolutionInfo.decode(readValue(buffer)!); - case 134: - return VideoQualityData.decode(readValue(buffer)!); - case 135: - return VideoRecordEventData.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } + CameraCharacteristics pigeon_copy() { + return CameraCharacteristics.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); } } -class CaptureRequestOptionsHostApi { - /// Constructor for [CaptureRequestOptionsHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - CaptureRequestOptionsHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - - static const MessageCodec codec = - _CaptureRequestOptionsHostApiCodec(); - - Future create( - int arg_identifier, Map arg_options) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CaptureRequestOptionsHostApi.create', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_identifier, arg_options]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } +/// An interface for retrieving Camera2-related camera information. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/camera2/interop/Camera2CameraInfo. +class Camera2CameraInfo extends PigeonInternalProxyApiBaseClass { + /// Gets the `Camera2CameraInfo` from a `CameraInfo`. + Camera2CameraInfo.from({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required CameraInfo cameraInfo, + }) { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecCamera2CameraInfo; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Camera2CameraInfo.from'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([pigeonVar_instanceIdentifier, cameraInfo]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); } -} - -class Camera2CameraControlHostApi { - /// Constructor for [Camera2CameraControlHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - Camera2CameraControlHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - static const MessageCodec codec = StandardMessageCodec(); + /// Constructs [Camera2CameraInfo] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + Camera2CameraInfo.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); - Future create( - int arg_identifier, int arg_cameraControlIdentifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.Camera2CameraControlHostApi.create', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_identifier, arg_cameraControlIdentifier]) - as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; + late final _PigeonInternalProxyApiBaseCodec + _pigeonVar_codecCamera2CameraInfo = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + Camera2CameraInfo Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.Camera2CameraInfo.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.Camera2CameraInfo.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.Camera2CameraInfo.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + Camera2CameraInfo.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } } } - Future addCaptureRequestOptions( - int arg_identifier, int arg_captureRequestOptionsIdentifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.Camera2CameraControlHostApi.addCaptureRequestOptions', - codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel.send( - [arg_identifier, arg_captureRequestOptionsIdentifier]) - as List?; - if (replyList == null) { + /// Gets the string camera ID. + Future getCameraId() async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecCamera2CameraInfo; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Camera2CameraInfo.getCameraId'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList.length > 1) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', ); } else { - return; + return (pigeonVar_replyList[0] as String?)!; } } -} -class _ResolutionFilterHostApiCodec extends StandardMessageCodec { - const _ResolutionFilterHostApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is ResolutionInfo) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); + /// Gets a camera characteristic value. + Future getCameraCharacteristic(CameraCharacteristicsKey key) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecCamera2CameraInfo; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.Camera2CameraInfo.getCameraCharacteristic'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, key]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); } else { - super.writeValue(buffer, value); + return pigeonVar_replyList[0]; } } @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return ResolutionInfo.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } - } -} - -class ResolutionFilterHostApi { - /// Constructor for [ResolutionFilterHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - ResolutionFilterHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - - static const MessageCodec codec = _ResolutionFilterHostApiCodec(); - - Future createWithOnePreferredSize( - int arg_identifier, ResolutionInfo arg_preferredResolution) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ResolutionFilterHostApi.createWithOnePreferredSize', - codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier, arg_preferredResolution]) - as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } + Camera2CameraInfo pigeon_copy() { + return Camera2CameraInfo.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); } } -class Camera2CameraInfoHostApi { - /// Constructor for [Camera2CameraInfoHostApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - Camera2CameraInfoHostApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - - static const MessageCodec codec = StandardMessageCodec(); +/// A factory to create a MeteringPoint. +/// +/// See https://developer.android.com/reference/androidx/camera/core/MeteringPointFactory. +class MeteringPointFactory extends PigeonInternalProxyApiBaseClass { + /// Constructs [MeteringPointFactory] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + MeteringPointFactory.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }); - Future createFrom(int arg_cameraInfoIdentifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.Camera2CameraInfoHostApi.createFrom', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = await channel - .send([arg_cameraInfoIdentifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', - ); - } else { - return (replyList[0] as int?)!; + late final _PigeonInternalProxyApiBaseCodec + _pigeonVar_codecMeteringPointFactory = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + MeteringPointFactory Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; + { + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.MeteringPointFactory.pigeon_newInstance', + pigeonChannelCodec, + binaryMessenger: binaryMessenger); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); + } else { + pigeonVar_channel.setMessageHandler((Object? message) async { + assert(message != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.MeteringPointFactory.pigeon_newInstance was null.'); + final List args = (message as List?)!; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.MeteringPointFactory.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + MeteringPointFactory.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } + }); + } } } - Future getSupportedHardwareLevel(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.Camera2CameraInfoHostApi.getSupportedHardwareLevel', - codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { + /// Creates a MeteringPoint by x, y. + Future createPoint( + double x, + double y, + ) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecMeteringPointFactory; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.MeteringPointFactory.createPoint'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, x, y]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as int?)!; + return (pigeonVar_replyList[0] as MeteringPoint?)!; } } - Future getCameraId(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.Camera2CameraInfoHostApi.getCameraId', codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { + /// Creates a MeteringPoint by x, y, size. + Future createPointWithSize( + double x, + double y, + double size, + ) async { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecMeteringPointFactory; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.MeteringPointFactory.createPointWithSize'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = + pigeonVar_channel.send([this, x, y, size]); + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], ); - } else if (replyList[0] == null) { + } else if (pigeonVar_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { - return (replyList[0] as String?)!; + return (pigeonVar_replyList[0] as MeteringPoint?)!; } } - Future getSensorOrientation(int arg_identifier) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.Camera2CameraInfoHostApi.getSensorOrientation', - codec, - binaryMessenger: _binaryMessenger); - final List? replyList = - await channel.send([arg_identifier]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', - ); - } else { - return (replyList[0] as int?)!; - } + @override + MeteringPointFactory pigeon_copy() { + return MeteringPointFactory.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); } } -abstract class Camera2CameraInfoFlutterApi { - static const MessageCodec codec = StandardMessageCodec(); - - void create(int identifier); +/// A MeteringPointFactory that can convert a View (x, y) into a MeteringPoint +/// which can then be used to construct a FocusMeteringAction to start a focus +/// and metering action. +/// +/// See https://developer.android.com/reference/androidx/camera/core/DisplayOrientedMeteringPointFactory. +class DisplayOrientedMeteringPointFactory extends MeteringPointFactory { + /// Creates a DisplayOrientedMeteringPointFactory for converting View (x, y) + /// into a MeteringPoint based on the current display's rotation and + /// CameraInfo. + DisplayOrientedMeteringPointFactory({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + required CameraInfo cameraInfo, + required double width, + required double height, + }) : super.pigeon_detached() { + final int pigeonVar_instanceIdentifier = + pigeon_instanceManager.addDartCreatedInstance(this); + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _pigeonVar_codecDisplayOrientedMeteringPointFactory; + final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; + const String pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.DisplayOrientedMeteringPointFactory.pigeon_defaultConstructor'; + final BasicMessageChannel pigeonVar_channel = + BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier, cameraInfo, width, height]); + () async { + final List? pigeonVar_replyList = + await pigeonVar_sendFuture as List?; + if (pigeonVar_replyList == null) { + throw _createConnectionError(pigeonVar_channelName); + } else if (pigeonVar_replyList.length > 1) { + throw PlatformException( + code: pigeonVar_replyList[0]! as String, + message: pigeonVar_replyList[1] as String?, + details: pigeonVar_replyList[2], + ); + } else { + return; + } + }(); + } - static void setup(Camera2CameraInfoFlutterApi? api, - {BinaryMessenger? binaryMessenger}) { + /// Constructs [DisplayOrientedMeteringPointFactory] without creating the associated native object. + /// + /// This should only be used by subclasses created by this library or to + /// create copies for an [PigeonInstanceManager]. + @protected + DisplayOrientedMeteringPointFactory.pigeon_detached({ + super.pigeon_binaryMessenger, + super.pigeon_instanceManager, + }) : super.pigeon_detached(); + + late final _PigeonInternalProxyApiBaseCodec + _pigeonVar_codecDisplayOrientedMeteringPointFactory = + _PigeonInternalProxyApiBaseCodec(pigeon_instanceManager); + + static void pigeon_setUpMessageHandlers({ + bool pigeon_clearHandlers = false, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + DisplayOrientedMeteringPointFactory Function()? pigeon_newInstance, + }) { + final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = + _PigeonInternalProxyApiBaseCodec( + pigeon_instanceManager ?? PigeonInstanceManager.instance); + final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.Camera2CameraInfoFlutterApi.create', codec, + final BasicMessageChannel< + Object?> pigeonVar_channel = BasicMessageChannel< + Object?>( + 'dev.flutter.pigeon.camera_android_camerax.DisplayOrientedMeteringPointFactory.pigeon_newInstance', + pigeonChannelCodec, binaryMessenger: binaryMessenger); - if (api == null) { - channel.setMessageHandler(null); + if (pigeon_clearHandlers) { + pigeonVar_channel.setMessageHandler(null); } else { - channel.setMessageHandler((Object? message) async { + pigeonVar_channel.setMessageHandler((Object? message) async { assert(message != null, - 'Argument for dev.flutter.pigeon.Camera2CameraInfoFlutterApi.create was null.'); + 'Argument for dev.flutter.pigeon.camera_android_camerax.DisplayOrientedMeteringPointFactory.pigeon_newInstance was null.'); final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.Camera2CameraInfoFlutterApi.create was null, expected non-null int.'); - api.create(arg_identifier!); - return; + final int? arg_pigeon_instanceIdentifier = (args[0] as int?); + assert(arg_pigeon_instanceIdentifier != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.DisplayOrientedMeteringPointFactory.pigeon_newInstance was null, expected non-null int.'); + try { + (pigeon_instanceManager ?? PigeonInstanceManager.instance) + .addHostCreatedInstance( + pigeon_newInstance?.call() ?? + DisplayOrientedMeteringPointFactory.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ), + arg_pigeon_instanceIdentifier!, + ); + return wrapResponse(empty: true); + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException(code: 'error', message: e.toString())); + } }); } } } + + @override + DisplayOrientedMeteringPointFactory pigeon_copy() { + return DisplayOrientedMeteringPointFactory.pigeon_detached( + pigeon_binaryMessenger: pigeon_binaryMessenger, + pigeon_instanceManager: pigeon_instanceManager, + ); + } } diff --git a/packages/camera/camera_android_camerax/lib/src/camerax_proxy.dart b/packages/camera/camera_android_camerax/lib/src/camerax_proxy.dart index c5d92d29560b..055e88988862 100644 --- a/packages/camera/camera_android_camerax/lib/src/camerax_proxy.dart +++ b/packages/camera/camera_android_camerax/lib/src/camerax_proxy.dart @@ -2,369 +2,370 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import 'dart:ui' show Size; - -import 'package:flutter/services.dart' show DeviceOrientation; - -import 'analyzer.dart'; -import 'aspect_ratio_strategy.dart'; -import 'camera2_camera_control.dart'; -import 'camera2_camera_info.dart'; -import 'camera_control.dart'; -import 'camera_info.dart'; -import 'camera_selector.dart'; -import 'camera_state.dart'; -import 'camerax_library.g.dart'; -import 'capture_request_options.dart'; -import 'device_orientation_manager.dart'; -import 'fallback_strategy.dart'; -import 'focus_metering_action.dart'; -import 'image_analysis.dart'; -import 'image_capture.dart'; -import 'image_proxy.dart'; -import 'metering_point.dart'; -import 'observer.dart'; -import 'preview.dart'; -import 'process_camera_provider.dart'; -import 'quality_selector.dart'; -import 'recorder.dart'; -import 'resolution_filter.dart'; -import 'resolution_selector.dart'; -import 'resolution_strategy.dart'; -import 'system_services.dart'; -import 'video_capture.dart'; - -/// Handles `JavaObject` creation and calling their methods that require -/// testing. +import 'package:flutter/services.dart'; + +// ignore_for_file: non_constant_identifier_names + +import 'camerax_library.dart'; + +/// Handles constructing objects and calling static methods for the Android +/// Interactive Media Ads native library. /// -/// By default, each function will create `JavaObject`s attached to an -/// `InstanceManager` and call through to the appropriate method. +/// This class provides dependency injection for the implementations of the +/// platform interface classes. Improving the ease of unit testing and/or +/// overriding the underlying Android classes. +/// +/// By default each function calls the default constructor of the class it +/// intends to return. class CameraXProxy { - /// Constructs a [CameraXProxy]. + /// Constructs an [CameraXProxy]. CameraXProxy({ - this.getProcessCameraProvider = _getProcessCameraProvider, - this.createCameraSelector = _createAttachedCameraSelector, - this.createPreview = _createAttachedPreview, - this.createImageCapture = _createAttachedImageCapture, - this.createRecorder = _createAttachedRecorder, - this.createVideoCapture = _createAttachedVideoCapture, - this.createImageAnalysis = _createAttachedImageAnalysis, - this.createAnalyzer = _createAttachedAnalyzer, - this.createCameraStateObserver = _createAttachedCameraStateObserver, - this.createResolutionStrategy = _createAttachedResolutionStrategy, - this.createResolutionSelector = _createAttachedResolutionSelector, - this.createFallbackStrategy = _createAttachedFallbackStrategy, - this.createQualitySelector = _createAttachedQualitySelector, - this.requestCameraPermissions = _requestCameraPermissions, - this.startListeningForDeviceOrientationChange = - _startListeningForDeviceOrientationChange, - this.setPreviewSurfaceProvider = _setPreviewSurfaceProvider, - this.getDefaultDisplayRotation = _getDefaultDisplayRotation, - this.getCamera2CameraControl = _getCamera2CameraControl, - this.createCaptureRequestOptions = _createAttachedCaptureRequestOptions, - this.createMeteringPoint = _createAttachedMeteringPoint, - this.createFocusMeteringAction = _createAttachedFocusMeteringAction, - this.createAspectRatioStrategy = _createAttachedAspectRatioStrategy, - this.createResolutionFilterWithOnePreferredSize = - _createAttachedResolutionFilterWithOnePreferredSize, - this.getCamera2CameraInfo = _getCamera2CameraInfo, - this.getUiOrientation = _getUiOrientation, - this.getSensorOrientation = _getSensorOrientation, - this.previewSurfaceProducerHandlesCropAndRotation = - _previewSurfaceProducerHandlesCropAndRotation, + this.setUpGenericsProxy = setUpGenerics, + this.newCameraSize = CameraSize.new, + this.newCameraIntegerRange = CameraIntegerRange.new, + this.newObserver = Observer.new, + this.newCameraSelector = CameraSelector.new, + this.newSystemServicesManager = SystemServicesManager.new, + this.newDeviceOrientationManager = DeviceOrientationManager.new, + this.newPreview = Preview.new, + this.withOutputVideoCapture = VideoCapture.withOutput, + this.newRecorder = Recorder.new, + this.newVideoRecordEventListener = VideoRecordEventListener.new, + this.newImageCapture = ImageCapture.new, + this.newResolutionStrategy = ResolutionStrategy.new, + this.newResolutionSelector = ResolutionSelector.new, + this.newAspectRatioStrategy = AspectRatioStrategy.new, + this.newImageAnalysis = ImageAnalysis.new, + this.newAnalyzer = Analyzer.new, + this.fromQualitySelector = QualitySelector.from, + this.fromOrderedListQualitySelector = QualitySelector.fromOrderedList, + this.higherQualityOrLowerThanFallbackStrategy = + FallbackStrategy.higherQualityOrLowerThan, + this.higherQualityThanFallbackStrategy = FallbackStrategy.higherQualityThan, + this.lowerQualityOrHigherThanFallbackStrategy = + FallbackStrategy.lowerQualityOrHigherThan, + this.lowerQualityThanFallbackStrategy = FallbackStrategy.lowerQualityThan, + this.newFocusMeteringActionBuilder = FocusMeteringActionBuilder.new, + this.withModeFocusMeteringActionBuilder = + FocusMeteringActionBuilder.withMode, + this.newCaptureRequestOptions = CaptureRequestOptions.new, + this.fromCamera2CameraControl = Camera2CameraControl.from, + this.createWithOnePreferredSizeResolutionFilter = + ResolutionFilter.createWithOnePreferredSize, + this.fromCamera2CameraInfo = Camera2CameraInfo.from, + this.newDisplayOrientedMeteringPointFactory = + DisplayOrientedMeteringPointFactory.new, + this.getInstanceProcessCameraProvider = ProcessCameraProvider.getInstance, + this.getResolutionQualitySelector = QualitySelector.getResolution, + this.defaultBackCameraCameraSelector = _defaultBackCameraCameraSelector, + this.defaultFrontCameraCameraSelector = _defaultFrontCameraCameraSelector, + this.highestAvailableStrategyResolutionStrategy = + _highestAvailableStrategyResolutionStrategy, + this.ratio_16_9FallbackAutoStrategyAspectRatioStrategy = + _ratio_16_9FallbackAutoStrategyAspectRatioStrategy, + this.ratio_4_3FallbackAutoStrategyAspectRatioStrategy = + _ratio_4_3FallbackAutoStrategyAspectRatioStrategy, + this.controlAELockCaptureRequest = _controlAELockCaptureRequest, + this.infoSupportedHardwareLevelCameraCharacteristics = + _infoSupportedHardwareLevelCameraCharacteristics, + this.sensorOrientationCameraCharacteristics = + _sensorOrientationCameraCharacteristics, }); - /// Returns a [ProcessCameraProvider] instance. - Future Function() getProcessCameraProvider; - - /// Returns a [CameraSelector] based on the specified camera lens direction. - CameraSelector Function(int cameraSelectorLensDirection) createCameraSelector; - - /// Returns a [Preview] configured with the specified target rotation and - /// specified [ResolutionSelector]. - Preview Function( + /// Handles adding support for generic classes. + final void Function({ + BinaryMessenger? pigeonBinaryMessenger, + PigeonInstanceManager? pigeonInstanceManager, + }) setUpGenericsProxy; + + /// Constructs [CameraSize]. + final CameraSize Function({ + required int width, + required int height, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) newCameraSize; + + /// Constructs [CameraIntegerRange]. + final CameraIntegerRange Function({ + required int lower, + required int upper, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) newCameraIntegerRange; + + /// Constructs [Observer]. + final Observer Function({ + required void Function(Observer, T) onChanged, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) newObserver; + + /// Constructs [CameraSelector]. + final CameraSelector Function({ + LensFacing? requireLensFacing, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) newCameraSelector; + + /// Constructs [SystemServicesManager]. + final SystemServicesManager Function({ + required void Function(SystemServicesManager, String) onCameraError, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) newSystemServicesManager; + + /// Constructs [DeviceOrientationManager]. + final DeviceOrientationManager Function({ + required void Function(DeviceOrientationManager, String) + onDeviceOrientationChanged, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) newDeviceOrientationManager; + + /// Constructs [Preview]. + final Preview Function({ + int? targetRotation, ResolutionSelector? resolutionSelector, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) newPreview; + + /// Constructs [VideoCapture]. + final VideoCapture Function({ + required VideoOutput videoOutput, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) withOutputVideoCapture; + + /// Constructs [Recorder]. + final Recorder Function({ + int? aspectRatio, + int? targetVideoEncodingBitRate, + QualitySelector? qualitySelector, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) newRecorder; + + /// Constructs [VideoRecordEventListener]. + final VideoRecordEventListener Function({ + required void Function(VideoRecordEventListener, VideoRecordEvent) onEvent, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) newVideoRecordEventListener; + + /// Constructs [ImageCapture]. + final ImageCapture Function({ int? targetRotation, - ) createPreview; - - /// Returns an [ImageCapture] configured with specified flash mode and - /// the specified [ResolutionSelector]. - ImageCapture Function( - ResolutionSelector? resolutionSelector, int? targetRotation) - createImageCapture; - - /// Returns a [Recorder] for use in video capture configured with the - /// specified [QualitySelector]. - Recorder Function(QualitySelector? qualitySelector) createRecorder; - - /// Returns a [VideoCapture] associated with the provided [Recorder]. - Future Function(Recorder recorder) createVideoCapture; - - /// Returns an [ImageAnalysis] configured with the specified - /// [ResolutionSelector]. - ImageAnalysis Function( - ResolutionSelector? resolutionSelector, int? targetRotation) - createImageAnalysis; - - /// Returns an [Analyzer] configured with the specified callback for - /// analyzing [ImageProxy]s. - Analyzer Function(Future Function(ImageProxy imageProxy) analyze) - createAnalyzer; - - /// Returns an [Observer] of the [CameraState] with the specified callback - /// for handling changes in that state. - Observer Function(void Function(Object stateAsObject) onChanged) - createCameraStateObserver; - - /// Returns a [ResolutionStrategy] configured with the specified bounds for - /// choosing a resolution and a fallback rule if achieving a resolution within - /// those bounds is not possible. - /// - /// [highestAvailable] is used to specify whether or not the highest available - /// [ResolutionStrategy] should be returned. - ResolutionStrategy Function( - {bool highestAvailable, - Size? boundSize, - int? fallbackRule}) createResolutionStrategy; - - /// Returns a [ResolutionSelector] configured with the specified - /// [ResolutionStrategy], [ResolutionFilter], and [AspectRatioStrategy]. - ResolutionSelector Function( - ResolutionStrategy resolutionStrategy, - ResolutionFilter? resolutionFilter, - AspectRatioStrategy? aspectRatioStrategy) createResolutionSelector; - - /// Returns a [FallbackStrategy] configured with the specified [VideoQuality] - /// and [VideoResolutionFallbackRule]. - FallbackStrategy Function( - {required VideoQuality quality, - required VideoResolutionFallbackRule fallbackRule}) - createFallbackStrategy; - - /// Returns a [QualitySelector] configured with the specified [VideoQuality] - /// and [FallbackStrategy]. - QualitySelector Function( - {required VideoQuality videoQuality, - required FallbackStrategy fallbackStrategy}) createQualitySelector; - - /// Requests camera permissions. - Future Function(bool enableAudio) requestCameraPermissions; - - /// Subscribes the plugin as a listener to changes in device orientation. - void Function(bool cameraIsFrontFacing, int sensorOrientation) - startListeningForDeviceOrientationChange; - - /// Sets the surface provider of the specified [Preview] instance and returns - /// the ID corresponding to the surface it will provide. - Future Function(Preview preview) setPreviewSurfaceProvider; - - /// Returns default rotation for [UseCase]s in terms of one of the [Surface] - /// rotation constants. - Future Function() getDefaultDisplayRotation; - - /// Gets [Camera2CameraControl] instance from [cameraControl]. - Camera2CameraControl Function(CameraControl cameraControl) - getCamera2CameraControl; - - /// Creates a [CaptureRequestOptions] with specified options. - CaptureRequestOptions Function( - List<(CaptureRequestKeySupportedType, Object?)> options) - createCaptureRequestOptions; - - /// Returns a [MeteringPoint] with the specified coordinates based on - /// [cameraInfo]. - MeteringPoint Function( - double x, double y, double? size, CameraInfo cameraInfo) - createMeteringPoint; - - /// Returns a [FocusMeteringAction] based on the specified metering points - /// and their modes. - FocusMeteringAction Function(List<(MeteringPoint, int?)> meteringPointInfos, - bool? disableAutoCancel) createFocusMeteringAction; - - /// Creates an [AspectRatioStrategy] with specified aspect ratio and fallback - /// rule. - AspectRatioStrategy Function(int aspectRatio, int fallbackRule) - createAspectRatioStrategy; - - /// Creates a [ResolutionFilter] that prioritizes specified resolution. - ResolutionFilter Function(Size preferredResolution) - createResolutionFilterWithOnePreferredSize; - - /// Gets [Camera2CameraInfo] instance from [cameraInfo]. - Future Function(CameraInfo cameraInfo) - getCamera2CameraInfo; - - /// Gets current UI orientation based on device orientation and rotation. - Future Function() getUiOrientation; - - /// Gets camera sensor orientation from [camera2CameraInfo]. - Future Function(Camera2CameraInfo camera2CameraInfo) - getSensorOrientation; - - /// Returns whether or not the preview's surface producer handles correctly - /// rotating the camera preview automatically. - Future Function(Preview preview) - previewSurfaceProducerHandlesCropAndRotation; - - static Future _getProcessCameraProvider() { - return ProcessCameraProvider.getInstance(); - } - - static CameraSelector _createAttachedCameraSelector( - int cameraSelectorLensDirection) { - switch (cameraSelectorLensDirection) { - case CameraSelector.lensFacingFront: - return CameraSelector.getDefaultFrontCamera(); - case CameraSelector.lensFacingBack: - return CameraSelector.getDefaultBackCamera(); - default: - return CameraSelector(lensFacing: cameraSelectorLensDirection); - } - } - - static Preview _createAttachedPreview( - ResolutionSelector? resolutionSelector, int? targetRotation) { - return Preview( - initialTargetRotation: targetRotation, - resolutionSelector: resolutionSelector); - } - - static ImageCapture _createAttachedImageCapture( - ResolutionSelector? resolutionSelector, int? targetRotation) { - return ImageCapture( - resolutionSelector: resolutionSelector, - initialTargetRotation: targetRotation); - } - - static Recorder _createAttachedRecorder(QualitySelector? qualitySelector) { - return Recorder(qualitySelector: qualitySelector); - } - - static Future _createAttachedVideoCapture( - Recorder recorder) async { - return VideoCapture.withOutput(recorder); - } - - static ImageAnalysis _createAttachedImageAnalysis( - ResolutionSelector? resolutionSelector, int? targetRotation) { - return ImageAnalysis( - resolutionSelector: resolutionSelector, - initialTargetRotation: targetRotation); - } - - static Analyzer _createAttachedAnalyzer( - Future Function(ImageProxy imageProxy) analyze) { - return Analyzer(analyze: analyze); - } - - static Observer _createAttachedCameraStateObserver( - void Function(Object stateAsObject) onChanged) { - return Observer(onChanged: onChanged); - } - - static ResolutionStrategy _createAttachedResolutionStrategy( - {bool highestAvailable = false, Size? boundSize, int? fallbackRule}) { - if (highestAvailable) { - return ResolutionStrategy.highestAvailableStrategy(); - } - - return ResolutionStrategy( - boundSize: boundSize!, fallbackRule: fallbackRule); - } - - static ResolutionSelector _createAttachedResolutionSelector( - ResolutionStrategy resolutionStrategy, - ResolutionFilter? resolutionFilter, - AspectRatioStrategy? aspectRatioStrategy) { - return ResolutionSelector( - resolutionStrategy: resolutionStrategy, - resolutionFilter: resolutionFilter, - aspectRatioStrategy: aspectRatioStrategy); - } - - static FallbackStrategy _createAttachedFallbackStrategy( - {required VideoQuality quality, - required VideoResolutionFallbackRule fallbackRule}) { - return FallbackStrategy(quality: quality, fallbackRule: fallbackRule); - } - - static QualitySelector _createAttachedQualitySelector( - {required VideoQuality videoQuality, - required FallbackStrategy fallbackStrategy}) { - return QualitySelector.from( - quality: VideoQualityData(quality: videoQuality), - fallbackStrategy: fallbackStrategy); - } - - static Future _requestCameraPermissions(bool enableAudio) async { - await SystemServices.requestCameraPermissions(enableAudio); - } - - static void _startListeningForDeviceOrientationChange( - bool cameraIsFrontFacing, int sensorOrientation) { - DeviceOrientationManager.startListeningForDeviceOrientationChange( - cameraIsFrontFacing, sensorOrientation); - } - - static Future _setPreviewSurfaceProvider(Preview preview) async { - return preview.setSurfaceProvider(); - } - - static Future _getDefaultDisplayRotation() async { - return DeviceOrientationManager.getDefaultDisplayRotation(); - } - - static Camera2CameraControl _getCamera2CameraControl( - CameraControl cameraControl) { - return Camera2CameraControl(cameraControl: cameraControl); - } - - static CaptureRequestOptions _createAttachedCaptureRequestOptions( - List<(CaptureRequestKeySupportedType, Object?)> options) { - return CaptureRequestOptions(requestedOptions: options); - } - - static MeteringPoint _createAttachedMeteringPoint( - double x, double y, double? size, CameraInfo cameraInfo) { - return MeteringPoint(x: x, y: y, size: size, cameraInfo: cameraInfo); - } - - static FocusMeteringAction _createAttachedFocusMeteringAction( - List<(MeteringPoint, int?)> meteringPointInfos, bool? disableAutoCancel) { - return FocusMeteringAction( - meteringPointInfos: meteringPointInfos, - disableAutoCancel: disableAutoCancel); - } - - static AspectRatioStrategy _createAttachedAspectRatioStrategy( - int preferredAspectRatio, int fallbackRule) { - return AspectRatioStrategy( - preferredAspectRatio: preferredAspectRatio, fallbackRule: fallbackRule); - } - - static ResolutionFilter _createAttachedResolutionFilterWithOnePreferredSize( - Size preferredSize) { - return ResolutionFilter.onePreferredSize( - preferredResolution: preferredSize); - } - - static Future _getCamera2CameraInfo( - CameraInfo cameraInfo) async { - return Camera2CameraInfo.from(cameraInfo); - } - - static Future _getUiOrientation() async { - return DeviceOrientationManager.getUiOrientation(); - } - - static Future _getSensorOrientation( - Camera2CameraInfo camera2CameraInfo) async { - return camera2CameraInfo.getSensorOrientation(); - } - - static Future _previewSurfaceProducerHandlesCropAndRotation( - Preview preview) async { - return preview.surfaceProducerHandlesCropAndRotation(); - } + CameraXFlashMode? flashMode, + ResolutionSelector? resolutionSelector, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) newImageCapture; + + /// Constructs [ResolutionStrategy]. + final ResolutionStrategy Function({ + required CameraSize boundSize, + required ResolutionStrategyFallbackRule fallbackRule, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) newResolutionStrategy; + + /// Constructs [ResolutionSelector]. + final ResolutionSelector Function({ + AspectRatioStrategy? aspectRatioStrategy, + ResolutionStrategy? resolutionStrategy, + ResolutionFilter? resolutionFilter, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) newResolutionSelector; + + /// Constructs [AspectRatioStrategy]. + final AspectRatioStrategy Function({ + required AspectRatio preferredAspectRatio, + required AspectRatioStrategyFallbackRule fallbackRule, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) newAspectRatioStrategy; + + /// Constructs [ImageAnalysis]. + final ImageAnalysis Function({ + int? targetRotation, + ResolutionSelector? resolutionSelector, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) newImageAnalysis; + + /// Constructs [Analyzer]. + final Analyzer Function({ + required void Function(Analyzer, ImageProxy) analyze, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) newAnalyzer; + + /// Constructs [QualitySelector]. + final QualitySelector Function({ + required VideoQuality quality, + FallbackStrategy? fallbackStrategy, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) fromQualitySelector; + + /// Constructs [QualitySelector]. + final QualitySelector Function({ + required List qualities, + FallbackStrategy? fallbackStrategy, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) fromOrderedListQualitySelector; + + /// Constructs [FallbackStrategy]. + final FallbackStrategy Function({ + required VideoQuality quality, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) higherQualityOrLowerThanFallbackStrategy; + + /// Constructs [FallbackStrategy]. + final FallbackStrategy Function({ + required VideoQuality quality, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) higherQualityThanFallbackStrategy; + + /// Constructs [FallbackStrategy]. + final FallbackStrategy Function({ + required VideoQuality quality, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) lowerQualityOrHigherThanFallbackStrategy; + + /// Constructs [FallbackStrategy]. + final FallbackStrategy Function({ + required VideoQuality quality, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) lowerQualityThanFallbackStrategy; + + /// Constructs [FocusMeteringActionBuilder]. + final FocusMeteringActionBuilder Function({ + required MeteringPoint point, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) newFocusMeteringActionBuilder; + + /// Constructs [FocusMeteringActionBuilder]. + FocusMeteringActionBuilder Function({ + required MeteringPoint point, + required MeteringMode mode, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) withModeFocusMeteringActionBuilder; + + /// Constructs [CaptureRequestOptions]. + CaptureRequestOptions Function({ + required Map options, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) newCaptureRequestOptions; + + /// Constructs [Camera2CameraControl]. + Camera2CameraControl Function({ + required CameraControl cameraControl, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) fromCamera2CameraControl; + + /// Constructs [ResolutionFilter]. + final ResolutionFilter Function({ + required CameraSize preferredSize, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) createWithOnePreferredSizeResolutionFilter; + + /// Constructs [Camera2CameraInfo]. + final Camera2CameraInfo Function({ + required CameraInfo cameraInfo, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) fromCamera2CameraInfo; + + /// Constructs [DisplayOrientedMeteringPointFactory]. + DisplayOrientedMeteringPointFactory Function({ + required CameraInfo cameraInfo, + required double width, + required double height, + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) newDisplayOrientedMeteringPointFactory; + + /// Calls to [ProcessCameraProvider.getInstance]. + final Future Function({ + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) getInstanceProcessCameraProvider; + + /// Calls to [QualitySelector.getResolution]. + final Future Function( + CameraInfo, + VideoQuality, { + BinaryMessenger? pigeon_binaryMessenger, + PigeonInstanceManager? pigeon_instanceManager, + }) getResolutionQualitySelector; + + /// Calls to [CameraSelector.defaultBackCamera]. + final CameraSelector Function() defaultBackCameraCameraSelector; + + /// Calls to [CameraSelector.defaultFrontCamera]. + final CameraSelector Function() defaultFrontCameraCameraSelector; + + /// Calls to [ResolutionStrategy.highestAvailableStrategy]. + final ResolutionStrategy Function() + highestAvailableStrategyResolutionStrategy; + + /// Calls to [AspectRatioStrategy.ratio_16_9FallbackAutoStrategy]. + final AspectRatioStrategy Function() + ratio_16_9FallbackAutoStrategyAspectRatioStrategy; + + /// Calls to [AspectRatioStrategy.ratio_4_3FallbackAutoStrategy]. + final AspectRatioStrategy Function() + ratio_4_3FallbackAutoStrategyAspectRatioStrategy; + + /// Calls to [CaptureRequest.controlAELock]. + CaptureRequestKey Function() controlAELockCaptureRequest; + + /// Calls to [CameraCharacteristics.infoSupportedHardwareLevel]. + final CameraCharacteristicsKey Function() + infoSupportedHardwareLevelCameraCharacteristics; + + /// Calls to [CameraCharacteristics.sensorOrientation]. + final CameraCharacteristicsKey Function() + sensorOrientationCameraCharacteristics; + + static CameraSelector _defaultBackCameraCameraSelector() => + CameraSelector.defaultBackCamera; + + static CameraSelector _defaultFrontCameraCameraSelector() => + CameraSelector.defaultFrontCamera; + + static ResolutionStrategy _highestAvailableStrategyResolutionStrategy() => + ResolutionStrategy.highestAvailableStrategy; + + static AspectRatioStrategy + _ratio_16_9FallbackAutoStrategyAspectRatioStrategy() => + AspectRatioStrategy.ratio_16_9FallbackAutoStrategy; + + static AspectRatioStrategy + _ratio_4_3FallbackAutoStrategyAspectRatioStrategy() => + AspectRatioStrategy.ratio_4_3FallbackAutoStrategy; + + static CaptureRequestKey _controlAELockCaptureRequest() => + CaptureRequest.controlAELock; + + static CameraCharacteristicsKey + _infoSupportedHardwareLevelCameraCharacteristics() => + CameraCharacteristics.infoSupportedHardwareLevel; + + static CameraCharacteristicsKey _sensorOrientationCameraCharacteristics() => + CameraCharacteristics.sensorOrientation; } diff --git a/packages/camera/camera_android_camerax/lib/src/capture_request_options.dart b/packages/camera/camera_android_camerax/lib/src/capture_request_options.dart deleted file mode 100644 index 8c3de00845ed..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/capture_request_options.dart +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart'; -import 'package:meta/meta.dart' show immutable; - -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; - -/// A bundle of Camera2 capture request options. -/// -/// See https://developer.android.com/reference/androidx/camera/camera2/interop/CaptureRequestOptions. -@immutable -class CaptureRequestOptions extends JavaObject { - /// Creates a [CaptureRequestOptions]. - /// - /// Any value specified as null for a particular - /// [CaptureRequestKeySupportedType] key will clear the pre-existing value. - CaptureRequestOptions({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - required this.requestedOptions, - }) : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = _CaptureRequestOptionsHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - _api.createFromInstances(this, requestedOptions); - } - - /// Constructs a [CaptureRequestOptions] that is not automatically attached to a - /// native object. - CaptureRequestOptions.detached({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - required this.requestedOptions, - }) : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = _CaptureRequestOptionsHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - } - - late final _CaptureRequestOptionsHostApiImpl _api; - - /// Capture request options this instance will be used to request. - final List<(CaptureRequestKeySupportedType type, Object? value)> - requestedOptions; - - /// Error message indicating a [CaptureRequestOption] was constructed with a - /// capture request key currently unsupported by the wrapping of this class. - static String getUnsupportedCaptureRequestKeyTypeErrorMessage( - CaptureRequestKeySupportedType captureRequestKeyType) => - 'The type of capture request key passed to this method ($captureRequestKeyType) is current unspported; please see CaptureRequestKeySupportedType in pigeons/camerax_library.dart if you wish to support a new type.'; -} - -/// Host API implementation of [CaptureRequestOptions]. -class _CaptureRequestOptionsHostApiImpl extends CaptureRequestOptionsHostApi { - /// Constructs a [_CaptureRequestOptionsHostApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - _CaptureRequestOptionsHostApiImpl({ - this.binaryMessenger, - InstanceManager? instanceManager, - }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager, - super(binaryMessenger: binaryMessenger); - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default [BinaryMessenger] will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager instanceManager; - - /// Creates a [CaptureRequestOptions] instance based on the specified - /// capture request key and value pairs. - Future createFromInstances( - CaptureRequestOptions instance, - List<(CaptureRequestKeySupportedType type, Object? value)> options, - ) { - if (options.isEmpty) { - throw ArgumentError( - 'At least one capture request option must be specified.'); - } - - final Map captureRequestOptions = {}; - - // Validate values have type that matches paired key that is supported by - // this plugin (CaptureRequestKeySupportedType). - for (final (CaptureRequestKeySupportedType key, Object? value) option - in options) { - final CaptureRequestKeySupportedType key = option.$1; - final Object? value = option.$2; - if (value == null) { - captureRequestOptions[key.index] = null; - continue; - } - - final Type valueRuntimeType = value.runtimeType; - switch (key) { - case CaptureRequestKeySupportedType.controlAeLock: - if (valueRuntimeType != bool) { - throw ArgumentError( - 'A controlAeLock value must be specified as a bool, but a $valueRuntimeType was specified.'); - } - // This ignore statement is safe beause this error will be useful when - // a new CaptureRequestKeySupportedType is being added, but the logic in - // this method has not yet been updated. - // ignore: no_default_cases, unreachable_switch_default - default: - throw ArgumentError(CaptureRequestOptions - .getUnsupportedCaptureRequestKeyTypeErrorMessage(key)); - } - - captureRequestOptions[key.index] = value; - } - return create( - instanceManager.addDartCreatedInstance( - instance, - onCopy: (CaptureRequestOptions original) => - CaptureRequestOptions.detached( - requestedOptions: original.requestedOptions, - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ), - ), - captureRequestOptions, - ); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/device_orientation_manager.dart b/packages/camera/camera_android_camerax/lib/src/device_orientation_manager.dart deleted file mode 100644 index aacddc5788a0..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/device_orientation_manager.dart +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'dart:async'; - -import 'package:camera_platform_interface/camera_platform_interface.dart' - show DeviceOrientationChangedEvent; -import 'package:flutter/services.dart'; - -import 'android_camera_camerax_flutter_api_impls.dart'; -import 'camerax_library.g.dart'; - -// Ignoring lint indicating this class only contains static members -// as this class is a wrapper for various Android system services. -// ignore_for_file: avoid_classes_with_only_static_members - -/// Utility class that offers access to Android system services needed for -/// camera usage and other informational streams. -class DeviceOrientationManager { - /// Stream that emits the device orientation whenever it is changed. - /// - /// Values may start being added to the stream once - /// `startListeningForDeviceOrientationChange(...)` is called. - static final StreamController - deviceOrientationChangedStreamController = - StreamController.broadcast(); - - /// Requests that [deviceOrientationChangedStreamController] start - /// emitting values for any change in device orientation. - static void startListeningForDeviceOrientationChange( - bool isFrontFacing, int sensorOrientation, - {BinaryMessenger? binaryMessenger}) { - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - final DeviceOrientationManagerHostApi api = - DeviceOrientationManagerHostApi(binaryMessenger: binaryMessenger); - - api.startListeningForDeviceOrientationChange( - isFrontFacing, sensorOrientation); - } - - /// Stops the [deviceOrientationChangedStreamController] from emitting values - /// for changes in device orientation. - static void stopListeningForDeviceOrientationChange( - {BinaryMessenger? binaryMessenger}) { - final DeviceOrientationManagerHostApi api = - DeviceOrientationManagerHostApi(binaryMessenger: binaryMessenger); - - api.stopListeningForDeviceOrientationChange(); - } - - /// Retrieves the default rotation that CameraX uses for [UseCase]s in terms - /// of one of the [Surface] rotation constants. - /// - /// The default rotation that CameraX uses is the rotation of the default - /// display at the time of binding a particular [UseCase], but the default - /// display does not change in the plugin, so this default value is - /// display-agnostic. - /// - /// [startListeningForDeviceOrientationChange] must be called before calling - /// this method. - static Future getDefaultDisplayRotation( - {BinaryMessenger? binaryMessenger}) async { - final DeviceOrientationManagerHostApi api = - DeviceOrientationManagerHostApi(binaryMessenger: binaryMessenger); - - return api.getDefaultDisplayRotation(); - } - - /// Retrieves the current UI orientation based on the current device - /// orientation and screen rotation. - static Future getUiOrientation( - {BinaryMessenger? binaryMessenger}) async { - final DeviceOrientationManagerHostApi api = - DeviceOrientationManagerHostApi(binaryMessenger: binaryMessenger); - - return deserializeDeviceOrientation(await api.getUiOrientation()); - } - - /// Serializes [DeviceOrientation] into a [String]. - static String serializeDeviceOrientation(DeviceOrientation orientation) { - switch (orientation) { - case DeviceOrientation.landscapeLeft: - return 'LANDSCAPE_LEFT'; - case DeviceOrientation.landscapeRight: - return 'LANDSCAPE_RIGHT'; - case DeviceOrientation.portraitDown: - return 'PORTRAIT_DOWN'; - case DeviceOrientation.portraitUp: - return 'PORTRAIT_UP'; - } - } - - /// Deserializes device orientation in [String] format into a - /// [DeviceOrientation]. - static DeviceOrientation deserializeDeviceOrientation(String orientation) { - switch (orientation) { - case 'LANDSCAPE_LEFT': - return DeviceOrientation.landscapeLeft; - case 'LANDSCAPE_RIGHT': - return DeviceOrientation.landscapeRight; - case 'PORTRAIT_DOWN': - return DeviceOrientation.portraitDown; - case 'PORTRAIT_UP': - return DeviceOrientation.portraitUp; - default: - throw ArgumentError( - '"$orientation" is not a valid DeviceOrientation value'); - } - } -} - -/// Flutter API implementation of [DeviceOrientationManager]. -class DeviceOrientationManagerFlutterApiImpl - implements DeviceOrientationManagerFlutterApi { - /// Constructs an [DeviceOrientationManagerFlutterApiImpl]. - DeviceOrientationManagerFlutterApiImpl(); - - /// Callback method for any changes in device orientation. - /// - /// Will only be called if - /// `DeviceOrientationManager.startListeningForDeviceOrientationChange(...)` was called - /// to start listening for device orientation updates. - @override - void onDeviceOrientationChanged(String orientation) { - final DeviceOrientation deviceOrientation = - DeviceOrientationManager.deserializeDeviceOrientation(orientation); - DeviceOrientationManager.deviceOrientationChangedStreamController - .add(DeviceOrientationChangedEvent(deviceOrientation)); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/exposure_state.dart b/packages/camera/camera_android_camerax/lib/src/exposure_state.dart deleted file mode 100644 index 2376a5e4f6f8..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/exposure_state.dart +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart' show BinaryMessenger; -import 'package:meta/meta.dart' show immutable; - -import 'android_camera_camerax_flutter_api_impls.dart'; -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; - -/// Represents exposure related information of a camera. -/// -/// See https://developer.android.com/reference/androidx/camera/core/ExposureState. -@immutable -class ExposureState extends JavaObject { - /// Constructs a [ExposureState] that is not automatically attached to a native object. - ExposureState.detached( - {super.binaryMessenger, - super.instanceManager, - required this.exposureCompensationRange, - required this.exposureCompensationStep}) - : super.detached() { - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - } - - /// Gets the maximum and minimum exposure compensation values for the camera - /// represented by this instance. - final ExposureCompensationRange exposureCompensationRange; - - /// Gets the smallest step by which the exposure compensation can be changed for - /// the camera represented by this instance. - final double exposureCompensationStep; -} - -/// Flutter API implementation of [ExposureState]. -class ExposureStateFlutterApiImpl implements ExposureStateFlutterApi { - /// Constructs a [ExposureStateFlutterApiImpl]. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. - ExposureStateFlutterApiImpl({ - this.binaryMessenger, - InstanceManager? instanceManager, - }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default BinaryMessenger will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager instanceManager; - - @override - void create( - int identifier, - ExposureCompensationRange exposureCompensationRange, - double exposureCompensationStep) { - instanceManager.addHostCreatedInstance( - ExposureState.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - exposureCompensationRange: exposureCompensationRange, - exposureCompensationStep: exposureCompensationStep), - identifier, - onCopy: (ExposureState original) { - return ExposureState.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - exposureCompensationRange: original.exposureCompensationRange, - exposureCompensationStep: original.exposureCompensationStep); - }, - ); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/fallback_strategy.dart b/packages/camera/camera_android_camerax/lib/src/fallback_strategy.dart deleted file mode 100644 index ad2589dae724..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/fallback_strategy.dart +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart'; -import 'package:meta/meta.dart' show immutable; - -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; - -/// Strategy that will be adopted when the device in use does not support all -/// of the desired quality specified for a particular QualitySelector instance. -/// -/// See https://developer.android.com/reference/androidx/camera/video/FallbackStrategy. -@immutable -class FallbackStrategy extends JavaObject { - /// Creates a [FallbackStrategy]. - FallbackStrategy( - {BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - required this.quality, - required this.fallbackRule}) - : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = _FallbackStrategyHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - _api.createFromInstance(this, quality, fallbackRule); - } - - /// Constructs a [FallbackStrategy] that is not automatically attached to a native object. - FallbackStrategy.detached( - {super.binaryMessenger, - super.instanceManager, - required this.quality, - required this.fallbackRule}) - : super.detached(); - - late final _FallbackStrategyHostApiImpl _api; - - /// The input quality used to specify this fallback strategy relative to. - final VideoQuality quality; - - /// The fallback rule that this strategy will follow. - final VideoResolutionFallbackRule fallbackRule; -} - -/// Host API implementation of [FallbackStrategy]. -class _FallbackStrategyHostApiImpl extends FallbackStrategyHostApi { - /// Constructs a [FallbackStrategyHostApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - _FallbackStrategyHostApiImpl( - {this.binaryMessenger, InstanceManager? instanceManager}) { - this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - } - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default [BinaryMessenger] will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - late final InstanceManager instanceManager; - - /// Creates a [FallbackStrategy] instance with the specified video [quality] - /// and [fallbackRule]. - void createFromInstance(FallbackStrategy instance, VideoQuality quality, - VideoResolutionFallbackRule fallbackRule) { - final int identifier = instanceManager.addDartCreatedInstance(instance, - onCopy: (FallbackStrategy original) { - return FallbackStrategy.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - quality: original.quality, - fallbackRule: original.fallbackRule, - ); - }); - create(identifier, quality, fallbackRule); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/focus_metering_action.dart b/packages/camera/camera_android_camerax/lib/src/focus_metering_action.dart deleted file mode 100644 index 81fa6f5abf14..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/focus_metering_action.dart +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart' show BinaryMessenger; -import 'package:meta/meta.dart' show immutable; - -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; -import 'metering_point.dart'; - -/// A configuration used to trigger a focus and/or metering action. -/// -/// See https://developer.android.com/reference/androidx/camera/core/FocusMeteringAction. -@immutable -class FocusMeteringAction extends JavaObject { - /// Creates a [FocusMeteringAction]. - FocusMeteringAction({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - required this.meteringPointInfos, - this.disableAutoCancel, - }) : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ) { - _api = _FocusMeteringActionHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - _api.createFromInstance(this, meteringPointInfos, disableAutoCancel); - } - - /// Creates a [FocusMeteringAction] that is not automatically attached to a - /// native object. - FocusMeteringAction.detached({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - required this.meteringPointInfos, - this.disableAutoCancel, - }) : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ) { - _api = _FocusMeteringActionHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - } - - late final _FocusMeteringActionHostApiImpl _api; - - /// The requested [MeteringPoint]s and modes that are relevant to each of those - /// points. - final List<(MeteringPoint meteringPoint, int? meteringMode)> - meteringPointInfos; - - /// Disables the auto-cancel. - /// - /// By default (and if set to false), auto-cancel is enabled with 5 seconds - /// duration. - final bool? disableAutoCancel; - - /// Flag for metering mode that indicates the auto focus region is enabled. - /// - /// An autofocus scan is also triggered when [flagAf] is assigned. - /// - /// See https://developer.android.com/reference/androidx/camera/core/FocusMeteringAction#FLAG_AF(). - static const int flagAf = 1; - - /// Flag for metering mode that indicates the auto exposure region is enabled. - /// - /// See https://developer.android.com/reference/androidx/camera/core/FocusMeteringAction#FLAG_AE(). - static const int flagAe = 2; - - /// Flag for metering mode that indicates the auto white balance region is - /// enabled. - /// - /// See https://developer.android.com/reference/androidx/camera/core/FocusMeteringAction#FLAG_AWB(). - static const int flagAwb = 4; -} - -/// Host API implementation of [FocusMeteringAction]. -class _FocusMeteringActionHostApiImpl extends FocusMeteringActionHostApi { - /// Constructs a [_FocusMeteringActionHostApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - _FocusMeteringActionHostApiImpl( - {this.binaryMessenger, InstanceManager? instanceManager}) { - this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - } - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default [BinaryMessenger] will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - late final InstanceManager instanceManager; - - /// Creates a [FocusMeteringAction] instance with the specified list of - /// [MeteringPoint]s and their modes in order of descending priority. - void createFromInstance( - FocusMeteringAction instance, - List<(MeteringPoint meteringPoint, int? meteringMode)> meteringPointInfos, - bool? disableAutoCancel) { - final int identifier = instanceManager.addDartCreatedInstance(instance, - onCopy: (FocusMeteringAction original) { - return FocusMeteringAction.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - meteringPointInfos: original.meteringPointInfos); - }); - - final List meteringPointInfosWithIds = - []; - for (final ( - MeteringPoint meteringPoint, - int? meteringMode - ) meteringPointInfo in meteringPointInfos) { - meteringPointInfosWithIds.add(MeteringPointInfo( - meteringPointId: instanceManager.getIdentifier(meteringPointInfo.$1)!, - meteringMode: meteringPointInfo.$2)); - } - - create(identifier, meteringPointInfosWithIds, disableAutoCancel); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/focus_metering_result.dart b/packages/camera/camera_android_camerax/lib/src/focus_metering_result.dart deleted file mode 100644 index 3a1afbd5fa54..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/focus_metering_result.dart +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart' show BinaryMessenger; -import 'package:meta/meta.dart' show immutable; - -import 'android_camera_camerax_flutter_api_impls.dart'; -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; - -/// The result of [CameraControl.startFocusAndMetering]. -/// -/// See https://developer.android.com/reference/kotlin/androidx/camera/core/FocusMeteringResult. -@immutable -class FocusMeteringResult extends JavaObject { - /// Creates a [FocusMeteringResult] that is not automatically attached to a - /// native object. - FocusMeteringResult.detached({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - }) : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ) { - _api = _FocusMeteringResultHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - } - - late final _FocusMeteringResultHostApiImpl _api; - - /// Returns whether or not auto focus is successful. - /// - /// If the current camera does not support auto focus, it will return true. If - /// auto focus is not requested, it will return false. - Future isFocusSuccessful() => _api.isFocusSuccessfulFromInstance(this); -} - -/// Host API implementation of [FocusMeteringResult]. -class _FocusMeteringResultHostApiImpl extends FocusMeteringResultHostApi { - /// Constructs a [FocusMeteringActionHostApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - _FocusMeteringResultHostApiImpl( - {this.binaryMessenger, InstanceManager? instanceManager}) { - this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - } - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default [BinaryMessenger] will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - late final InstanceManager instanceManager; - - /// Returns whether or not the [instance] indicates that auto focus was - /// successful. - Future isFocusSuccessfulFromInstance(FocusMeteringResult instance) { - final int identifier = instanceManager.getIdentifier(instance)!; - return isFocusSuccessful(identifier); - } -} - -/// Flutter API implementation of [FocusMeteringResult]. -class FocusMeteringResultFlutterApiImpl extends FocusMeteringResultFlutterApi { - /// Constructs a [FocusMeteringResultFlutterApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - FocusMeteringResultFlutterApiImpl({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - }) : _binaryMessenger = binaryMessenger, - _instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - - /// Receives binary data across the Flutter platform barrier. - final BinaryMessenger? _binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager _instanceManager; - - @override - void create(int identifier) { - _instanceManager.addHostCreatedInstance( - FocusMeteringResult.detached( - binaryMessenger: _binaryMessenger, instanceManager: _instanceManager), - identifier, - onCopy: (FocusMeteringResult original) { - return FocusMeteringResult.detached( - binaryMessenger: _binaryMessenger, - instanceManager: _instanceManager); - }, - ); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/image_analysis.dart b/packages/camera/camera_android_camerax/lib/src/image_analysis.dart deleted file mode 100644 index 3dc21ce2a7bc..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/image_analysis.dart +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'dart:async'; - -import 'package:flutter/services.dart' show BinaryMessenger; -import 'package:meta/meta.dart' show immutable; - -import 'analyzer.dart'; -import 'android_camera_camerax_flutter_api_impls.dart'; -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; -import 'resolution_selector.dart'; -import 'use_case.dart'; - -/// Use case for providing CPU accessible images for performing image analysis. -/// -/// See https://developer.android.com/reference/androidx/camera/core/ImageAnalysis. -@immutable -class ImageAnalysis extends UseCase { - /// Creates an [ImageAnalysis]. - ImageAnalysis( - {BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - this.initialTargetRotation, - this.resolutionSelector}) - : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = _ImageAnalysisHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - _api.createFromInstances(this, initialTargetRotation, resolutionSelector); - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - } - - /// Constructs an [ImageAnalysis] that is not automatically attached to a - /// native object. - ImageAnalysis.detached( - {BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - this.initialTargetRotation, - this.resolutionSelector}) - : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = _ImageAnalysisHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - } - - late final _ImageAnalysisHostApiImpl _api; - - /// Initial target rotation of the camera used for the preview stream. - /// - /// Should be specified in terms of one of the [Surface] - /// rotation constants that represents the counter-clockwise degrees of - /// rotation relative to [DeviceOrientation.portraitUp]. - // TODO(camsim99): Remove this parameter. https://github.com/flutter/flutter/issues/140664 - final int? initialTargetRotation; - - /// Target resolution of the camera preview stream. - /// - /// If not set, this [UseCase] will default to the behavior described in: - /// https://developer.android.com/reference/androidx/camera/core/ImageAnalysis.Builder#setResolutionSelector(androidx.camera.core.resolutionselector.ResolutionSelector). - final ResolutionSelector? resolutionSelector; - - /// Dynamically sets the target rotation of this instance. - /// - /// [rotation] should be specified in terms of one of the [Surface] - /// rotation constants that represents the counter-clockwise degrees of - /// rotation relative to [DeviceOrientation.portraitUp]. - Future setTargetRotation(int rotation) => - _api.setTargetRotationFromInstances(this, rotation); - - /// Sets an [Analyzer] to receive and analyze images. - Future setAnalyzer(Analyzer analyzer) => - _api.setAnalyzerFromInstances(this, analyzer); - - /// Removes a previously set [Analyzer]. - Future clearAnalyzer() => _api.clearAnalyzerFromInstances(this); -} - -/// Host API implementation of [ImageAnalysis]. -class _ImageAnalysisHostApiImpl extends ImageAnalysisHostApi { - /// Constructor for [_ImageAnalysisHostApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - _ImageAnalysisHostApiImpl({ - this.binaryMessenger, - InstanceManager? instanceManager, - }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager, - super(binaryMessenger: binaryMessenger); - - final BinaryMessenger? binaryMessenger; - - final InstanceManager instanceManager; - - /// Creates an [ImageAnalysis] instance with the specified target resolution - /// on the native side. - Future createFromInstances( - ImageAnalysis instance, - int? targetRotation, - ResolutionSelector? resolutionSelector, - ) { - return create( - instanceManager.addDartCreatedInstance( - instance, - onCopy: (ImageAnalysis original) => ImageAnalysis.detached( - initialTargetRotation: original.initialTargetRotation, - resolutionSelector: original.resolutionSelector, - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ), - ), - targetRotation, - resolutionSelector == null - ? null - : instanceManager.getIdentifier(resolutionSelector), - ); - } - - /// Dynamically sets the target rotation of [instance] to [rotation]. - Future setTargetRotationFromInstances( - ImageAnalysis instance, int rotation) { - return setTargetRotation( - instanceManager.getIdentifier(instance)!, rotation); - } - - /// Sets the [analyzer] to receive and analyze images on the [instance]. - Future setAnalyzerFromInstances( - ImageAnalysis instance, - Analyzer analyzer, - ) { - return setAnalyzer( - instanceManager.getIdentifier(instance)!, - instanceManager.getIdentifier(analyzer)!, - ); - } - - /// Removes a previously set analyzer from the [instance]. - Future clearAnalyzerFromInstances( - ImageAnalysis instance, - ) { - return clearAnalyzer( - instanceManager.getIdentifier(instance)!, - ); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/image_capture.dart b/packages/camera/camera_android_camerax/lib/src/image_capture.dart deleted file mode 100644 index b2f8671cd9f3..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/image_capture.dart +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart' show BinaryMessenger; -import 'package:meta/meta.dart' show immutable; - -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; -import 'resolution_selector.dart'; -import 'use_case.dart'; - -/// Use case for picture taking. -/// -/// See https://developer.android.com/reference/androidx/camera/core/ImageCapture. -@immutable -class ImageCapture extends UseCase { - /// Creates an [ImageCapture]. - ImageCapture({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - this.initialTargetRotation, - this.targetFlashMode, - this.resolutionSelector, - }) : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ) { - _api = ImageCaptureHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - _api.createFromInstance( - this, initialTargetRotation, targetFlashMode, resolutionSelector); - } - - /// Constructs an [ImageCapture] that is not automatically attached to a - /// native object. - ImageCapture.detached({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - this.initialTargetRotation, - this.targetFlashMode, - this.resolutionSelector, - }) : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ) { - _api = ImageCaptureHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - } - - late final ImageCaptureHostApiImpl _api; - - /// Initial target rotation of the camera used for the preview stream. - /// - /// Should be specified in terms of one of the [Surface] - /// rotation constants that represents the counter-clockwise degrees of - /// rotation relative to [DeviceOrientation.portraitUp]. - /// - // TODO(camsim99): Remove this parameter. https://github.com/flutter/flutter/issues/140664 - final int? initialTargetRotation; - - /// Flash mode used to take a picture. - final int? targetFlashMode; - - /// Target resolution of the image output from taking a picture. - /// - /// If not set, this [UseCase] will default to the behavior described in: - /// https://developer.android.com/reference/androidx/camera/core/ImageCapture.Builder#setResolutionSelector(androidx.camera.core.resolutionselector.ResolutionSelector). - final ResolutionSelector? resolutionSelector; - - /// Constant for automatic flash mode. - /// - /// See https://developer.android.com/reference/androidx/camera/core/ImageCapture#FLASH_MODE_AUTO(). - static const int flashModeAuto = 0; - - /// Constant for on flash mode. - /// - /// See https://developer.android.com/reference/androidx/camera/core/ImageCapture#FLASH_MODE_ON(). - static const int flashModeOn = 1; - - /// Constant for no flash mode. - /// - /// See https://developer.android.com/reference/androidx/camera/core/ImageCapture#FLASH_MODE_OFF(). - static const int flashModeOff = 2; - - /// Dynamically sets the target rotation of this instance. - /// - /// [rotation] should be specified in terms of one of the [Surface] - /// rotation constants that represents the counter-clockwise degrees of - /// rotation relative to [DeviceOrientation.portraitUp]. - Future setTargetRotation(int rotation) => - _api.setTargetRotationFromInstances(this, rotation); - - /// Sets the flash mode to use for image capture. - Future setFlashMode(int newFlashMode) async { - return _api.setFlashModeFromInstances(this, newFlashMode); - } - - /// Takes a picture and returns the absolute path of where the capture image - /// was saved. - /// - /// This method is not a direct mapping of the takePicture method in the CameraX, - /// as it also: - /// - /// * Configures an instance of the ImageCapture.OutputFileOptions to specify - /// how to handle the captured image. - /// * Configures an instance of ImageCapture.OnImageSavedCallback to receive - /// the results of the image capture as an instance of - /// ImageCapture.OutputFileResults. - /// * Converts the ImageCapture.OutputFileResults output instance to a String - /// that represents the full path where the captured image was saved in - /// memory to return. - /// - /// See https://developer.android.com/reference/androidx/camera/core/ImageCapture - /// for more information. - Future takePicture() async { - return _api.takePictureFromInstances(this); - } -} - -/// Host API implementation of [ImageCapture]. -class ImageCaptureHostApiImpl extends ImageCaptureHostApi { - /// Constructs a [ImageCaptureHostApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - ImageCaptureHostApiImpl( - {this.binaryMessenger, InstanceManager? instanceManager}) { - this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - } - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default [BinaryMessenger] will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - late final InstanceManager instanceManager; - - /// Creates an [ImageCapture] instance with the flash mode and target resolution - /// if specified. - void createFromInstance(ImageCapture instance, int? targetRotation, - int? targetFlashMode, ResolutionSelector? resolutionSelector) { - final int identifier = instanceManager.addDartCreatedInstance(instance, - onCopy: (ImageCapture original) { - return ImageCapture.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - initialTargetRotation: original.initialTargetRotation, - targetFlashMode: original.targetFlashMode, - resolutionSelector: original.resolutionSelector); - }); - create( - identifier, - targetRotation, - targetFlashMode, - resolutionSelector == null - ? null - : instanceManager.getIdentifier(resolutionSelector)); - } - - /// Dynamically sets the target rotation of [instance] to [rotation]. - Future setTargetRotationFromInstances( - ImageCapture instance, int rotation) { - return setTargetRotation( - instanceManager.getIdentifier(instance)!, rotation); - } - - /// Sets the flash mode for the specified [ImageCapture] instance to take - /// a picture with. - Future setFlashModeFromInstances( - ImageCapture instance, int flashMode) async { - final int? identifier = instanceManager.getIdentifier(instance); - assert(identifier != null, - 'No ImageCapture has the identifer of that requested to get the resolution information for.'); - - await setFlashMode(identifier!, flashMode); - } - - /// Takes a picture with the specified [ImageCapture] instance. - Future takePictureFromInstances(ImageCapture instance) async { - final int? identifier = instanceManager.getIdentifier(instance); - assert(identifier != null, - 'No ImageCapture has the identifer of that requested to get the resolution information for.'); - - final String picturePath = await takePicture(identifier!); - return picturePath; - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/image_proxy.dart b/packages/camera/camera_android_camerax/lib/src/image_proxy.dart deleted file mode 100644 index 230ece35089a..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/image_proxy.dart +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'dart:async'; - -import 'package:flutter/services.dart' show BinaryMessenger; -import 'package:meta/meta.dart' show immutable, protected; - -import 'android_camera_camerax_flutter_api_impls.dart'; -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; -import 'plane_proxy.dart'; - -/// Representation of a single complete image buffer. -/// -/// See https://developer.android.com/reference/androidx/camera/core/ImageProxy. -@immutable -class ImageProxy extends JavaObject { - /// Constructs a [ImageProxy] that is not automatically attached to a native object. - ImageProxy.detached( - {BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - required this.format, - required this.height, - required this.width}) - : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = _ImageProxyHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - } - - /// The image format. - final int format; - - /// The image height. - final int height; - - /// The image width. - final int width; - - late final _ImageProxyHostApiImpl _api; - - /// Returns the list of color planes of image data. - Future> getPlanes() => _api.getPlanesFromInstances(this); - - /// Closes the underlying image. - Future close() => _api.closeFromInstances(this); -} - -/// Host API implementation of [ImageProxy]. -class _ImageProxyHostApiImpl extends ImageProxyHostApi { - /// Constructor for [_ImageProxyHostApiImpl]. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an `InstanceManager` is being created. - _ImageProxyHostApiImpl({ - this.binaryMessenger, - InstanceManager? instanceManager, - }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager, - super(binaryMessenger: binaryMessenger); - - final BinaryMessenger? binaryMessenger; - - final InstanceManager instanceManager; - - /// Returns the list of color planes of the image data represnted by the - /// [instance]. - Future> getPlanesFromInstances( - ImageProxy instance, - ) async { - final List planesAsObjects = await getPlanes( - instanceManager.getIdentifier(instance)!, - ); - - return planesAsObjects.map((int? planeIdentifier) { - return instanceManager - .getInstanceWithWeakReference(planeIdentifier!)!; - }).toList(); - } - - /// Closes the underlying image of the [instance]. - Future closeFromInstances( - ImageProxy instance, - ) { - return close( - instanceManager.getIdentifier(instance)!, - ); - } -} - -/// Flutter API implementation for [ImageProxy]. -/// -/// This class may handle instantiating and adding Dart instances that are -/// attached to a native instance or receiving callback methods from an -/// overridden native class. -@protected -class ImageProxyFlutterApiImpl implements ImageProxyFlutterApi { - /// Constructs a [ImageProxyFlutterApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - ImageProxyFlutterApiImpl({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - }) : _binaryMessenger = binaryMessenger, - _instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - - /// Receives binary data across the Flutter platform barrier. - final BinaryMessenger? _binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager _instanceManager; - - @override - void create( - int identifier, - int format, - int height, - int width, - ) { - _instanceManager.addHostCreatedInstance( - ImageProxy.detached( - binaryMessenger: _binaryMessenger, - instanceManager: _instanceManager, - format: format, - height: height, - width: width, - ), - identifier, - onCopy: (ImageProxy original) => ImageProxy.detached( - binaryMessenger: _binaryMessenger, - instanceManager: _instanceManager, - format: original.format, - height: original.height, - width: original.width), - ); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/instance_manager.dart b/packages/camera/camera_android_camerax/lib/src/instance_manager.dart deleted file mode 100644 index aeb97ec36faa..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/instance_manager.dart +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/// Maintains instances used to communicate with the native objects they -/// represent. -/// -/// Added instances are stored as weak references and their copies are stored -/// as strong references to maintain access to their variables and callback -/// methods. Both are stored with the same identifier. -/// -/// When a weak referenced instance becomes inaccessible, -/// [onWeakReferenceRemoved] is called with its associated identifier. -/// -/// If an instance is retrieved and has the possibility to be used, -/// (e.g. calling [getInstanceWithWeakReference]) a copy of the strong reference -/// is added as a weak reference with the same identifier. This prevents a -/// scenario where the weak referenced instance was released and then later -/// returned by the host platform. -class InstanceManager { - /// Constructs an [InstanceManager]. - InstanceManager({required void Function(int) onWeakReferenceRemoved}) { - this.onWeakReferenceRemoved = (int identifier) { - _weakInstances.remove(identifier); - onWeakReferenceRemoved(identifier); - }; - _finalizer = Finalizer(this.onWeakReferenceRemoved); - } - - // Identifiers are locked to a specific range to avoid collisions with objects - // created simultaneously by the host platform. - // Host uses identifiers >= 2^16 and Dart is expected to use values n where, - // 0 <= n < 2^16. - static const int _maxDartCreatedIdentifier = 65536; - - // Expando is used because it doesn't prevent its keys from becoming - // inaccessible. This allows the manager to efficiently retrieve an identifier - // of an instance without holding a strong reference to that instance. - // - // It also doesn't use `==` to search for identifiers, which would lead to an - // infinite loop when comparing an object to its copy. (i.e. which was caused - // by calling instanceManager.getIdentifier() inside of `==` while this was a - // HashMap). - final Expando _identifiers = Expando(); - final Map> _weakInstances = - >{}; - final Map _strongInstances = {}; - final Map _copyCallbacks = {}; - late final Finalizer _finalizer; - int _nextIdentifier = 0; - - /// Called when a weak referenced instance is removed by [removeWeakReference] - /// or becomes inaccessible. - late final void Function(int) onWeakReferenceRemoved; - - /// Adds a new instance that was instantiated by Dart. - /// - /// In other words, Dart wants to add a new instance that will represent - /// an object that will be instantiated on the host platform. - /// - /// Throws assertion error if the instance has already been added. - /// - /// Returns the randomly generated id of the [instance] added. - int addDartCreatedInstance( - T instance, { - required T Function(T original) onCopy, - }) { - final int identifier = _nextUniqueIdentifier(); - _addInstanceWithIdentifier(instance, identifier, onCopy: onCopy); - return identifier; - } - - /// Removes the instance, if present, and call [onWeakReferenceRemoved] with - /// its identifier. - /// - /// Returns the identifier associated with the removed instance. Otherwise, - /// `null` if the instance was not found in this manager. - /// - /// This does not remove the the strong referenced instance associated with - /// [instance]. This can be done with [remove]. - int? removeWeakReference(Object instance) { - final int? identifier = getIdentifier(instance); - if (identifier == null) { - return null; - } - - _identifiers[instance] = null; - _finalizer.detach(instance); - onWeakReferenceRemoved(identifier); - - return identifier; - } - - /// Removes [identifier] and its associated strongly referenced instance, if - /// present, from the manager. - /// - /// Returns the strong referenced instance associated with [identifier] before - /// it was removed. Returns `null` if [identifier] was not associated with - /// any strong reference. - /// - /// This does not remove the the weak referenced instance associtated with - /// [identifier]. This can be done with [removeWeakReference]. - T? remove(int identifier) { - _copyCallbacks.remove(identifier); - return _strongInstances.remove(identifier) as T?; - } - - /// Retrieves the instance associated with identifier. - /// - /// The value returned is chosen from the following order: - /// - /// 1. A weakly referenced instance associated with identifier. - /// 2. If the only instance associated with identifier is a strongly - /// referenced instance, a copy of the instance is added as a weak reference - /// with the same identifier. Returning the newly created copy. - /// 3. If no instance is associated with identifier, returns null. - /// - /// This method also expects the host `InstanceManager` to have a strong - /// reference to the instance the identifier is associated with. - T? getInstanceWithWeakReference(int identifier) { - final T? weakInstance = _weakInstances[identifier]?.target as T?; - - if (weakInstance == null) { - final T? strongInstance = _strongInstances[identifier] as T?; - if (strongInstance != null) { - final Function copyCallback = _copyCallbacks[identifier]!; - // This avoid_dynamic_calls is safe since the type of strongInstance - // matches the argument type for _addInstanceWithIdentifier, which is - // the only place _copyCallbacks is populated. - // ignore: avoid_dynamic_calls - final T copy = copyCallback(strongInstance) as T; - _identifiers[copy] = identifier; - _weakInstances[identifier] = WeakReference(copy); - _finalizer.attach(copy, identifier, detach: copy); - return copy; - } - return strongInstance; - } - - return weakInstance; - } - - /// Retrieves the identifier associated with instance. - int? getIdentifier(Object instance) { - return _identifiers[instance]; - } - - /// Adds a new instance that was instantiated by the host platform. - /// - /// In other words, the host platform wants to add a new instance that - /// represents an object on the host platform. Stored with [identifier]. - /// - /// Throws assertion error if the instance or its identifier has already been - /// added. - /// - /// Returns unique identifier of the [instance] added. - void addHostCreatedInstance( - T instance, - int identifier, { - required T Function(T original) onCopy, - }) { - _addInstanceWithIdentifier(instance, identifier, onCopy: onCopy); - } - - void _addInstanceWithIdentifier( - T instance, - int identifier, { - required T Function(T original) onCopy, - }) { - assert(!containsIdentifier(identifier)); - assert(getIdentifier(instance) == null); - assert(identifier >= 0); - _identifiers[instance] = identifier; - _weakInstances[identifier] = WeakReference(instance); - _finalizer.attach(instance, identifier, detach: instance); - - final Object copy = onCopy(instance); - _identifiers[copy] = identifier; - _strongInstances[identifier] = copy; - _copyCallbacks[identifier] = onCopy; - } - - /// Whether this manager contains the given [identifier]. - bool containsIdentifier(int identifier) { - return _weakInstances.containsKey(identifier) || - _strongInstances.containsKey(identifier); - } - - int _nextUniqueIdentifier() { - late int identifier; - do { - identifier = _nextIdentifier; - _nextIdentifier = (_nextIdentifier + 1) % _maxDartCreatedIdentifier; - } while (containsIdentifier(identifier)); - return identifier; - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/java_object.dart b/packages/camera/camera_android_camerax/lib/src/java_object.dart deleted file mode 100644 index 1cf2379ad420..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/java_object.dart +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/foundation.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter/widgets.dart' show WidgetsFlutterBinding; - -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; - -/// Root of the Java class hierarchy. -/// -/// See https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html. -@immutable -class JavaObject { - /// Constructs a [JavaObject] without creating the associated Java object. - /// - /// This should only be used by subclasses created by this library or to - /// create copies. - JavaObject.detached({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - }) : _api = JavaObjectHostApiImpl( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ); - - /// Global instance of [InstanceManager]. - static final InstanceManager globalInstanceManager = _initInstanceManager(); - - static InstanceManager _initInstanceManager() { - WidgetsFlutterBinding.ensureInitialized(); - // Clears the native `InstanceManager` on initial use of the Dart one. - InstanceManagerHostApi().clear(); - return InstanceManager( - onWeakReferenceRemoved: (int identifier) { - JavaObjectHostApiImpl().dispose(identifier); - }, - ); - } - - /// Release the weak reference to the [instance]. - static void dispose(JavaObject instance) { - instance._api.instanceManager.removeWeakReference(instance); - } - - // ignore: unused_field - final JavaObjectHostApiImpl _api; -} - -/// Handles methods calls to the native Java Object class. -class JavaObjectHostApiImpl extends JavaObjectHostApi { - /// Constructs a [JavaObjectHostApiImpl]. - JavaObjectHostApiImpl({ - this.binaryMessenger, - InstanceManager? instanceManager, - }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager, - super(binaryMessenger: binaryMessenger); - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default BinaryMessenger will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager instanceManager; -} - -/// Handles callbacks methods for the native Java Object class. -class JavaObjectFlutterApiImpl implements JavaObjectFlutterApi { - /// Constructs a [JavaObjectFlutterApiImpl]. - JavaObjectFlutterApiImpl({InstanceManager? instanceManager}) - : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager instanceManager; - - @override - void dispose(int identifier) { - instanceManager.remove(identifier); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/live_data.dart b/packages/camera/camera_android_camerax/lib/src/live_data.dart deleted file mode 100644 index 1931e8169ca1..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/live_data.dart +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart'; -import 'package:meta/meta.dart'; - -import 'camera_state.dart'; -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; -import 'observer.dart'; -import 'zoom_state.dart'; - -/// A data holder class that can be observed. -/// -/// For this wrapped class, observation can only fall within the lifecycle of the -/// Android Activity to which this plugin is attached. -/// -/// See https://developer.android.com/reference/androidx/lifecycle/LiveData. -@immutable -class LiveData extends JavaObject { - /// Constructs a [LiveData] that is not automatically attached to a native object. - LiveData.detached({this.binaryMessenger, this.instanceManager}) - : _api = _LiveDataHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager), - super.detached( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - - final _LiveDataHostApiImpl _api; - - /// Receives binary data across the Flutter platform barrier. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager? instanceManager; - - /// Error message indicating a [LiveData] instance was constructed with a type - /// currently unsupported by the wrapping of this class. - static const String unsupportedLiveDataTypeErrorMessage = - 'The type of LiveData passed to this method is current unspported; please see LiveDataSupportedTypeData in pigeons/camerax_library.dart if you wish to support a new type.'; - - /// Adds specified [Observer] to the list of observers of this instance. - Future observe(Observer observer) { - return _api.observeFromInstances(this, observer); - } - - /// Removes all observers of this instance. - Future removeObservers() { - return _api.removeObserversFromInstances(this); - } - - /// Returns the current value. - Future? getValue() { - return _api.getValueFromInstances(this); - } -} - -/// Host API implementation of [LiveData]. -class _LiveDataHostApiImpl extends LiveDataHostApi { - /// Constructs a [_LiveDataHostApiImpl]. - /// - /// If [binaryMessenger] the default BinaryMessenger will be used which routes to - /// the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - _LiveDataHostApiImpl({ - this.binaryMessenger, - InstanceManager? instanceManager, - }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager, - super(binaryMessenger: binaryMessenger); - - /// Receives binary data across the Flutter platform barrier. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager instanceManager; - - /// Adds specified [Observer] to the list of observers of the specified - /// [LiveData] instance. - Future observeFromInstances( - LiveData instance, - Observer observer, - ) { - return observe( - instanceManager.getIdentifier(instance)!, - instanceManager.getIdentifier(observer)!, - ); - } - - /// Removes all observers of the specified [LiveData] instance. - Future removeObserversFromInstances( - LiveData instance, - ) { - return removeObservers( - instanceManager.getIdentifier(instance)!, - ); - } - - /// Gets current value of specified [LiveData] instance. - Future? getValueFromInstances( - LiveData instance) async { - LiveDataSupportedTypeData? typeData; - switch (T) { - case const (CameraState): - typeData = - LiveDataSupportedTypeData(value: LiveDataSupportedType.cameraState); - case const (ZoomState): - typeData = - LiveDataSupportedTypeData(value: LiveDataSupportedType.zoomState); - default: - throw ArgumentError(LiveData.unsupportedLiveDataTypeErrorMessage); - } - final int? valueIdentifier = - await getValue(instanceManager.getIdentifier(instance)!, typeData); - return valueIdentifier == null - ? null - : instanceManager.getInstanceWithWeakReference(valueIdentifier); - } -} - -/// Flutter API implementation for [LiveData]. -/// -/// This class may handle instantiating and adding Dart instances that are -/// attached to a native instance or receiving callback methods from an -/// overridden native class. -@protected -class LiveDataFlutterApiImpl implements LiveDataFlutterApi { - /// Constructs a [LiveDataFlutterApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - LiveDataFlutterApiImpl({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - }) : _binaryMessenger = binaryMessenger, - _instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - - /// Receives binary data across the Flutter platform barrier. - final BinaryMessenger? _binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager _instanceManager; - - @override - void create( - int identifier, - LiveDataSupportedTypeData typeData, - ) { - switch (typeData.value) { - case LiveDataSupportedType.cameraState: - _instanceManager.addHostCreatedInstance( - LiveData.detached( - binaryMessenger: _binaryMessenger, - instanceManager: _instanceManager, - ), - identifier, - onCopy: (LiveData original) => - LiveData.detached( - binaryMessenger: _binaryMessenger, - instanceManager: _instanceManager, - ), - ); - return; - case LiveDataSupportedType.zoomState: - _instanceManager.addHostCreatedInstance( - LiveData.detached( - binaryMessenger: _binaryMessenger, - instanceManager: _instanceManager, - ), - identifier, - onCopy: (LiveData original) => - LiveData.detached( - binaryMessenger: _binaryMessenger, - instanceManager: _instanceManager, - ), - ); - return; - // This ignore statement is safe beause this error will be useful when - // a new LiveDataSupportedType is being added, but the logic in this method - // has not yet been updated. - // ignore: no_default_cases, unreachable_switch_default - default: - throw ArgumentError(LiveData.unsupportedLiveDataTypeErrorMessage); - } - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/metering_point.dart b/packages/camera/camera_android_camerax/lib/src/metering_point.dart deleted file mode 100644 index c5ee6061de9c..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/metering_point.dart +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart' show BinaryMessenger; -import 'package:meta/meta.dart' show immutable; - -import 'android_camera_camerax_flutter_api_impls.dart'; -import 'camera_info.dart'; -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; - -/// Representation for a region which can be converted to sensor coordinate -/// system for focus and metering purpose. -/// -/// See https://developer.android.com/reference/androidx/camera/core/MeteringPoint. -@immutable -class MeteringPoint extends JavaObject { - /// Creates a [MeteringPoint]. - MeteringPoint({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - required this.x, - required this.y, - this.size, - required this.cameraInfo, - }) : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ) { - _api = _MeteringPointHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - _api.createFromInstance(this, x, y, size, cameraInfo); - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - } - - /// Creates a [MeteringPoint] that is not automatically attached to a - /// native object. - MeteringPoint.detached({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - required this.x, - required this.y, - this.size, - required this.cameraInfo, - }) : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ) { - _api = _MeteringPointHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - } - - late final _MeteringPointHostApiImpl _api; - - /// X coordinate. - final double x; - - /// Y coordinate. - final double y; - - /// The size of the [MeteringPoint] width and height (ranging from 0 to 1), - /// which is a normalized percentage of the sensor width/height (or crop - /// region width/height if crop region is set). - final double? size; - - /// The [CameraInfo] used to construct the metering point with a display- - /// oriented metering point factory. - final CameraInfo cameraInfo; - - /// The default size of the [MeteringPoint] width and height (ranging from 0 - /// to 1) which is a (normalized) percentage of the sensor width/height (or - /// crop region width/height if crop region is set). - static Future getDefaultPointSize( - {BinaryMessenger? binaryMessenger}) { - final MeteringPointHostApi hostApi = - MeteringPointHostApi(binaryMessenger: binaryMessenger); - return hostApi.getDefaultPointSize(); - } -} - -/// Host API implementation of [MeteringPoint]. -class _MeteringPointHostApiImpl extends MeteringPointHostApi { - /// Constructs a [_MeteringPointHostApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - _MeteringPointHostApiImpl( - {this.binaryMessenger, InstanceManager? instanceManager}) { - this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - } - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default [BinaryMessenger] will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - late final InstanceManager instanceManager; - - /// Creates a [MeteringPoint] instance with the specified [x] and [y] - /// coordinates as well as [size] if non-null. - Future createFromInstance(MeteringPoint instance, double x, double y, - double? size, CameraInfo cameraInfo) { - int? identifier = instanceManager.getIdentifier(instance); - identifier ??= instanceManager.addDartCreatedInstance(instance, - onCopy: (MeteringPoint original) { - return MeteringPoint.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - x: original.x, - y: original.y, - cameraInfo: original.cameraInfo, - size: original.size); - }); - final int? camInfoId = instanceManager.getIdentifier(cameraInfo); - - return create(identifier, x, y, size, camInfoId!); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/observer.dart b/packages/camera/camera_android_camerax/lib/src/observer.dart deleted file mode 100644 index 912343b44a15..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/observer.dart +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart'; -import 'package:meta/meta.dart'; - -import 'android_camera_camerax_flutter_api_impls.dart'; -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; -import 'live_data.dart'; - -/// Callback that can receive from [LiveData]. -/// -/// See https://developer.android.com/reference/androidx/lifecycle/Observer. -@immutable -class Observer extends JavaObject { - /// Constructor for [Observer]. - Observer( - {super.binaryMessenger, - super.instanceManager, - required void Function(Object value) onChanged}) - : _api = _ObserverHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager), - super.detached() { - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - this.onChanged = (Object value) { - if (value is! T) { - throw ArgumentError( - 'The type of value observed does not match the type of Observer constructed.'); - } - onChanged(value); - }; - _api.createFromInstance(this); - } - - /// Constructs a [Observer] that is not automatically attached to a native object. - Observer.detached( - {super.binaryMessenger, - super.instanceManager, - required void Function(Object value) onChanged}) - : _api = _ObserverHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager), - super.detached() { - this.onChanged = (Object value) { - assert(value is T); - onChanged(value); - }; - } - - final _ObserverHostApiImpl _api; - - /// Callback used when the observed data is changed to a new value. - /// - /// The callback parameter cannot take type [T] directly due to the issue - /// described in https://github.com/dart-lang/sdk/issues/51461. - late final void Function(Object value) onChanged; -} - -class _ObserverHostApiImpl extends ObserverHostApi { - /// Constructs an [_ObserverHostApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - _ObserverHostApiImpl({ - this.binaryMessenger, - InstanceManager? instanceManager, - }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager, - super(binaryMessenger: binaryMessenger); - - final BinaryMessenger? binaryMessenger; - - final InstanceManager instanceManager; - - /// Adds specified [Observer] instance to instance manager and makes call - /// to native side to create the instance. - Future createFromInstance( - Observer instance, - ) { - return create( - instanceManager.addDartCreatedInstance( - instance, - onCopy: (Observer original) => Observer.detached( - onChanged: original.onChanged, - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ), - ), - ); - } -} - -/// Flutter API implementation for [Observer]. -/// -/// This class may handle instantiating and adding Dart instances that are -/// attached to a native instance or receiving callback methods from an -/// overridden native class. -@protected -class ObserverFlutterApiImpl implements ObserverFlutterApi { - /// Constructs an [ObserverFlutterApiImpl]. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - ObserverFlutterApiImpl({ - InstanceManager? instanceManager, - }) : _instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager _instanceManager; - - @override - void onChanged( - int identifier, - int valueIdentifier, - ) { - final Observer instance = - _instanceManager.getInstanceWithWeakReference(identifier)!; - - // This call is safe because the onChanged callback will check the type - // of the instance to ensure it is expected before proceeding. - // ignore: avoid_dynamic_calls, void_checks - instance.onChanged( - _instanceManager.getInstanceWithWeakReference(valueIdentifier)!, - ); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/pending_recording.dart b/packages/camera/camera_android_camerax/lib/src/pending_recording.dart deleted file mode 100644 index 7dcb19e48c5d..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/pending_recording.dart +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'dart:async'; - -import 'package:flutter/services.dart' show BinaryMessenger; -import 'package:meta/meta.dart' show immutable; - -import 'android_camera_camerax_flutter_api_impls.dart'; -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; -import 'recording.dart'; - -/// Dart wrapping of PendingRecording CameraX class. -/// -/// See https://developer.android.com/reference/androidx/camera/video/PendingRecording -@immutable -class PendingRecording extends JavaObject { - /// Creates a [PendingRecording] that is not automatically attached to - /// a native object. - PendingRecording.detached( - {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager}) - : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = PendingRecordingHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - } - - late final PendingRecordingHostApiImpl _api; - - /// Stream that emits an event when the corresponding video recording is finalized. - static final StreamController - videoRecordingEventStreamController = - StreamController.broadcast(); - - /// Starts the recording, making it an active recording. - Future start() { - return _api.startFromInstance(this); - } -} - -/// Host API implementation of [PendingRecording]. -class PendingRecordingHostApiImpl extends PendingRecordingHostApi { - /// Constructs a PendingRecordingHostApiImpl. - PendingRecordingHostApiImpl( - {this.binaryMessenger, InstanceManager? instanceManager}) - : super(binaryMessenger: binaryMessenger) { - this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - } - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default BinaryMessenger will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - late final InstanceManager instanceManager; - - /// Starts the recording, making it an active recording. - Future startFromInstance(PendingRecording pendingRecording) async { - int? instanceId = instanceManager.getIdentifier(pendingRecording); - instanceId ??= instanceManager.addDartCreatedInstance(pendingRecording, - onCopy: (PendingRecording original) { - return PendingRecording.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ); - }); - return instanceManager - .getInstanceWithWeakReference(await start(instanceId))! as Recording; - } -} - -/// Flutter API implementation of [PendingRecording]. -class PendingRecordingFlutterApiImpl extends PendingRecordingFlutterApi { - /// Constructs a [PendingRecordingFlutterApiImpl]. - PendingRecordingFlutterApiImpl({ - this.binaryMessenger, - InstanceManager? instanceManager, - }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default BinaryMessenger will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager instanceManager; - - @override - void create(int identifier) { - instanceManager.addHostCreatedInstance( - PendingRecording.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ), - identifier, onCopy: (PendingRecording original) { - return PendingRecording.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ); - }); - } - - @override - void onVideoRecordingEvent(VideoRecordEventData event) { - PendingRecording.videoRecordingEventStreamController.add(event.value); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/plane_proxy.dart b/packages/camera/camera_android_camerax/lib/src/plane_proxy.dart deleted file mode 100644 index d69892e19da7..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/plane_proxy.dart +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'dart:typed_data'; - -import 'package:flutter/services.dart' show BinaryMessenger; -import 'package:meta/meta.dart' show immutable, protected; - -import 'android_camera_camerax_flutter_api_impls.dart'; -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; - -/// A single color plane of image data. -/// -/// See https://developer.android.com/reference/androidx/camera/core/ImageProxy.PlaneProxy. -@immutable -class PlaneProxy extends JavaObject { - /// Constructs a [PlaneProxy] that is not automatically attached to a native object. - PlaneProxy.detached( - {super.binaryMessenger, - super.instanceManager, - required this.buffer, - required this.pixelStride, - required this.rowStride}) - : super.detached() { - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - } - - /// Returns the pixels buffer containing frame data. - final Uint8List buffer; - - /// Returns the pixel stride, the distance between adjacent pixel samples, in - /// bytes. - final int pixelStride; - - /// Returns the row stride, the distance between the start of two consecutive - /// rows of pixels in the image, in bytes. - final int rowStride; -} - -/// Flutter API implementation for [PlaneProxy]. -/// -/// This class may handle instantiating and adding Dart instances that are -/// attached to a native instance or receiving callback methods from an -/// overridden native class. -@protected -class PlaneProxyFlutterApiImpl implements PlaneProxyFlutterApi { - /// Constructs an [PlaneProxyFlutterApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - PlaneProxyFlutterApiImpl({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - }) : _binaryMessenger = binaryMessenger, - _instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - - /// Receives binary data across the Flutter platform barrier. - final BinaryMessenger? _binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager _instanceManager; - - @override - void create( - int identifier, - Uint8List buffer, - int pixelStride, - int rowStride, - ) { - _instanceManager.addHostCreatedInstance( - PlaneProxy.detached( - binaryMessenger: _binaryMessenger, - instanceManager: _instanceManager, - buffer: buffer, - pixelStride: pixelStride, - rowStride: rowStride, - ), - identifier, - onCopy: (PlaneProxy original) => PlaneProxy.detached( - binaryMessenger: _binaryMessenger, - instanceManager: _instanceManager, - buffer: buffer, - pixelStride: pixelStride, - rowStride: rowStride), - ); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/preview.dart b/packages/camera/camera_android_camerax/lib/src/preview.dart deleted file mode 100644 index 76da65e4a81a..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/preview.dart +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart' show BinaryMessenger; -import 'package:meta/meta.dart' show immutable; - -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; -import 'resolution_selector.dart'; -import 'use_case.dart'; - -/// Use case that provides a camera preview stream for display. -/// -/// See https://developer.android.com/reference/androidx/camera/core/Preview. -@immutable -class Preview extends UseCase { - /// Creates a [Preview]. - Preview( - {BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - this.initialTargetRotation, - this.resolutionSelector}) - : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = PreviewHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - _api.createFromInstance(this, initialTargetRotation, resolutionSelector); - } - - /// Constructs a [Preview] that is not automatically attached to a native object. - Preview.detached( - {BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - this.initialTargetRotation, - this.resolutionSelector}) - : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = PreviewHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - } - - late final PreviewHostApiImpl _api; - - /// Target rotation of the camera used for the preview stream. - /// - /// Should be specified in terms of one of the [Surface] - /// rotation constants that represents the counter-clockwise degrees of - /// rotation relative to [DeviceOrientation.portraitUp]. - /// - // TODO(camsim99): Remove this parameter. https://github.com/flutter/flutter/issues/140664 - final int? initialTargetRotation; - - /// Target resolution of the camera preview stream. - /// - /// If not set, this [UseCase] will default to the behavior described in: - /// https://developer.android.com/reference/androidx/camera/core/Preview.Builder#setResolutionSelector(androidx.camera.core.resolutionselector.ResolutionSelector). - final ResolutionSelector? resolutionSelector; - - /// Dynamically sets the target rotation of this instance. - /// - /// [rotation] should be specified in terms of one of the [Surface] - /// rotation constants that represents the counter-clockwise degrees of - /// rotation relative to [DeviceOrientation.portraitUp]. - Future setTargetRotation(int rotation) => - _api.setTargetRotationFromInstances(this, rotation); - - /// Sets the surface provider for the preview stream. - /// - /// Returns the ID of the FlutterSurfaceTextureEntry used on the native end - /// used to display the preview stream on a [Texture] of the same ID. - Future setSurfaceProvider() { - return _api.setSurfaceProviderFromInstance(this); - } - - /// Releases Flutter surface texture used to provide a surface for the preview - /// stream. - void releaseFlutterSurfaceTexture() { - _api.releaseFlutterSurfaceTextureFromInstance(); - } - - /// Retrieves the selected resolution information of this [Preview]. - Future getResolutionInfo() { - return _api.getResolutionInfoFromInstance(this); - } - - /// Returns whether or not the Android surface producer automatically handles - /// correcting the rotation of camera previews for the device this plugin runs on. - Future surfaceProducerHandlesCropAndRotation() { - return _api.surfaceProducerHandlesCropAndRotationFromInstance(); - } -} - -/// Host API implementation of [Preview]. -class PreviewHostApiImpl extends PreviewHostApi { - /// Constructs an [PreviewHostApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - PreviewHostApiImpl({this.binaryMessenger, InstanceManager? instanceManager}) { - this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - } - - /// Receives binary data across the Flutter platform barrier. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - late final InstanceManager instanceManager; - - /// Creates a [Preview] with the target rotation and target resolution if - /// specified. - void createFromInstance(Preview instance, int? targetRotation, - ResolutionSelector? resolutionSelector) { - final int identifier = instanceManager.addDartCreatedInstance(instance, - onCopy: (Preview original) { - return Preview.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - initialTargetRotation: original.initialTargetRotation, - resolutionSelector: original.resolutionSelector); - }); - create( - identifier, - targetRotation, - resolutionSelector == null - ? null - : instanceManager.getIdentifier(resolutionSelector)); - } - - /// Dynamically sets the target rotation of [instance] to [rotation]. - Future setTargetRotationFromInstances(Preview instance, int rotation) { - return setTargetRotation( - instanceManager.getIdentifier(instance)!, rotation); - } - - /// Sets the surface provider of the specified [Preview] instance and returns - /// the ID corresponding to the surface it will provide. - Future setSurfaceProviderFromInstance(Preview instance) async { - final int? identifier = instanceManager.getIdentifier(instance); - final int surfaceTextureEntryId = await setSurfaceProvider(identifier!); - - return surfaceTextureEntryId; - } - - /// Releases Flutter surface texture used to provide a surface for the preview - /// stream if a surface provider was set for a [Preview] instance. - void releaseFlutterSurfaceTextureFromInstance() { - releaseFlutterSurfaceTexture(); - } - - /// Gets the resolution information of the specified [Preview] instance. - Future getResolutionInfoFromInstance(Preview instance) async { - final int? identifier = instanceManager.getIdentifier(instance); - final ResolutionInfo resolutionInfo = await getResolutionInfo(identifier!); - - return resolutionInfo; - } - - /// Returns whether or not the Android surface producer automatically handles - /// correcting the rotation of camera previews for the device this plugin runs on. - Future surfaceProducerHandlesCropAndRotationFromInstance() { - return surfaceProducerHandlesCropAndRotation(); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/process_camera_provider.dart b/packages/camera/camera_android_camerax/lib/src/process_camera_provider.dart deleted file mode 100644 index a2f8a1634ce0..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/process_camera_provider.dart +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart'; -import 'package:meta/meta.dart' show immutable; - -import 'android_camera_camerax_flutter_api_impls.dart'; -import 'camera.dart'; -import 'camera_info.dart'; -import 'camera_selector.dart'; -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; -import 'use_case.dart'; - -/// Provides an object to manage the camera. -/// -/// See https://developer.android.com/reference/androidx/camera/lifecycle/ProcessCameraProvider. -@immutable -class ProcessCameraProvider extends JavaObject { - /// Creates a detached [ProcessCameraProvider]. - ProcessCameraProvider.detached( - {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager}) - : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = ProcessCameraProviderHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - } - - late final ProcessCameraProviderHostApiImpl _api; - - /// Gets an instance of [ProcessCameraProvider]. - static Future getInstance( - {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager}) { - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - final ProcessCameraProviderHostApiImpl api = - ProcessCameraProviderHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - - return api.getInstancefromInstances(); - } - - /// Retrieves the cameras available to the device. - Future> getAvailableCameraInfos() { - return _api.getAvailableCameraInfosFromInstances(this); - } - - /// Binds the specified [UseCase]s to the lifecycle of the camera that it - /// returns. - Future bindToLifecycle( - CameraSelector cameraSelector, List useCases) { - return _api.bindToLifecycleFromInstances(this, cameraSelector, useCases); - } - - /// Returns whether or not the specified [UseCase] has been bound to the - /// lifecycle of the camera that this instance tracks. - Future isBound(UseCase useCase) { - return _api.isBoundFromInstances(this, useCase); - } - - /// Unbinds specified [UseCase]s from the lifecycle of the camera that this - /// instance tracks. - void unbind(List useCases) { - _api.unbindFromInstances(this, useCases); - } - - /// Unbinds all previously bound [UseCase]s from the lifecycle of the camera - /// that this tracks. - void unbindAll() { - _api.unbindAllFromInstances(this); - } -} - -/// Host API implementation of [ProcessCameraProvider]. -class ProcessCameraProviderHostApiImpl extends ProcessCameraProviderHostApi { - /// Constructs an [ProcessCameraProviderHostApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - ProcessCameraProviderHostApiImpl( - {this.binaryMessenger, InstanceManager? instanceManager}) - : super(binaryMessenger: binaryMessenger) { - this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - } - - /// Receives binary data across the Flutter platform barrier. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - late final InstanceManager instanceManager; - - /// Retrieves an instance of a ProcessCameraProvider from the context of - /// the FlutterActivity. - Future getInstancefromInstances() async { - return instanceManager.getInstanceWithWeakReference( - await getInstance())!; - } - - /// Gets identifier that the [instanceManager] has set for - /// the [ProcessCameraProvider] instance. - int getProcessCameraProviderIdentifier(ProcessCameraProvider instance) { - final int? identifier = instanceManager.getIdentifier(instance); - return identifier!; - } - - /// Retrives the list of CameraInfos corresponding to the available cameras. - Future> getAvailableCameraInfosFromInstances( - ProcessCameraProvider instance) async { - final int identifier = getProcessCameraProviderIdentifier(instance); - final List cameraInfos = await getAvailableCameraInfos(identifier); - return cameraInfos - .map((int? id) => - instanceManager.getInstanceWithWeakReference(id!)!) - .toList(); - } - - /// Binds the specified [UseCase]s to the lifecycle of the camera which - /// the provided [ProcessCameraProvider] instance tracks. - /// - /// The instance of the camera whose lifecycle the [UseCase]s are bound to - /// is returned. - Future bindToLifecycleFromInstances( - ProcessCameraProvider instance, - CameraSelector cameraSelector, - List useCases, - ) async { - final int identifier = getProcessCameraProviderIdentifier(instance); - final List useCaseIds = useCases - .map((UseCase useCase) => instanceManager.getIdentifier(useCase)!) - .toList(); - - final int cameraIdentifier = await bindToLifecycle( - identifier, - instanceManager.getIdentifier(cameraSelector)!, - useCaseIds, - ); - return instanceManager - .getInstanceWithWeakReference(cameraIdentifier)!; - } - - /// Returns whether or not the specified [UseCase] has been bound to the - /// lifecycle of the camera that this instance tracks. - Future isBoundFromInstances( - ProcessCameraProvider instance, - UseCase useCase, - ) async { - final int identifier = getProcessCameraProviderIdentifier(instance); - final int? useCaseId = instanceManager.getIdentifier(useCase); - - assert(useCaseId != null, - 'UseCase must have been created in order for this check to be valid.'); - - final bool useCaseIsBound = await isBound(identifier, useCaseId!); - return useCaseIsBound; - } - - /// Unbinds specified [UseCase]s from the lifecycle of the camera which the - /// provided [ProcessCameraProvider] instance tracks. - void unbindFromInstances( - ProcessCameraProvider instance, - List useCases, - ) { - final int identifier = getProcessCameraProviderIdentifier(instance); - final List useCaseIds = useCases - .map((UseCase useCase) => instanceManager.getIdentifier(useCase)!) - .toList(); - - unbind(identifier, useCaseIds); - } - - /// Unbinds all previously bound [UseCase]s from the lifecycle of the camera - /// which the provided [ProcessCameraProvider] instance tracks. - void unbindAllFromInstances(ProcessCameraProvider instance) { - final int identifier = getProcessCameraProviderIdentifier(instance); - unbindAll(identifier); - } -} - -/// Flutter API Implementation of [ProcessCameraProvider]. -class ProcessCameraProviderFlutterApiImpl - implements ProcessCameraProviderFlutterApi { - /// Constructs an [ProcessCameraProviderFlutterApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - ProcessCameraProviderFlutterApiImpl({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - }) : _binaryMessenger = binaryMessenger, - _instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - - /// Receives binary data across the Flutter platform barrier. - final BinaryMessenger? _binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager _instanceManager; - - @override - void create(int identifier) { - _instanceManager.addHostCreatedInstance( - ProcessCameraProvider.detached( - binaryMessenger: _binaryMessenger, instanceManager: _instanceManager), - identifier, - onCopy: (ProcessCameraProvider original) { - return ProcessCameraProvider.detached( - binaryMessenger: _binaryMessenger, - instanceManager: _instanceManager); - }, - ); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/quality_selector.dart b/packages/camera/camera_android_camerax/lib/src/quality_selector.dart deleted file mode 100644 index 6daff7d06827..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/quality_selector.dart +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart'; -import 'package:meta/meta.dart' show immutable; - -import 'camera_info.dart'; -import 'camerax_library.g.dart'; -import 'fallback_strategy.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; - -/// Quality setting used to configure components with quality setting -/// requirements such as creating a Recorder. -/// -/// See https://developer.android.com/reference/androidx/camera/video/QualitySelector. -@immutable -class QualitySelector extends JavaObject { - /// Creates a [QualitySelector] with the desired quality and fallback - /// strategy, if specified. - QualitySelector.from( - {BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - required VideoQualityData quality, - this.fallbackStrategy}) - : qualityList = [quality], - super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = _QualitySelectorHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - _api.createFromInstance(this, qualityList, fallbackStrategy); - } - - /// Creates a [QualitySelector] with ordered desired qualities and fallback - /// strategy, if specified. - /// - /// The final quality will be selected according to the order in which they are - /// specified. - QualitySelector.fromOrderedList( - {BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - required this.qualityList, - this.fallbackStrategy}) - : assert(qualityList.isNotEmpty, - 'Quality list specified must be non-empty.'), - super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = _QualitySelectorHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - _api.createFromInstance(this, qualityList, fallbackStrategy); - } - - /// Creates a [QualitySelector] that is not automatically attached to a - /// native object. - QualitySelector.detached({ - super.binaryMessenger, - super.instanceManager, - required this.qualityList, - this.fallbackStrategy, - }) : super.detached(); - - late final _QualitySelectorHostApiImpl _api; - - /// Desired qualities for this selector instance. - final List qualityList; - - /// Desired fallback strategy for this selector instance. - final FallbackStrategy? fallbackStrategy; - - /// Retrieves the corresponding resolution from the input [quality] for the - /// camera represented by [cameraInfo]. - static Future getResolution( - CameraInfo cameraInfo, VideoQuality quality, - {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager}) { - final _QualitySelectorHostApiImpl api = _QualitySelectorHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - return api.getResolutionFromInstance(cameraInfo, quality); - } -} - -/// Host API implementation of [QualitySelector]. -class _QualitySelectorHostApiImpl extends QualitySelectorHostApi { - /// Constructs a [QualitySelectorHostApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - _QualitySelectorHostApiImpl( - {this.binaryMessenger, InstanceManager? instanceManager}) { - this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - } - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default [BinaryMessenger] will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - late final InstanceManager instanceManager; - - /// Creates a [QualitySelector] instance with the desired qualities and - /// fallback strategy specified. - void createFromInstance(QualitySelector instance, - List qualityList, FallbackStrategy? fallbackStrategy) { - final int identifier = instanceManager.addDartCreatedInstance(instance, - onCopy: (QualitySelector original) { - return QualitySelector.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - qualityList: original.qualityList, - fallbackStrategy: original.fallbackStrategy, - ); - }); - - create( - identifier, - qualityList, - fallbackStrategy == null - ? null - : instanceManager.getIdentifier(fallbackStrategy)); - } - - /// Retrieves the corresponding resolution from the input [quality] for the - /// camera represented by [cameraInfo]. - Future getResolutionFromInstance( - CameraInfo cameraInfo, VideoQuality quality) async { - final int? cameraInfoIdentifier = instanceManager.getIdentifier(cameraInfo); - - if (cameraInfoIdentifier == null) { - throw ArgumentError( - 'The CameraInfo instance specified needs to be added to the InstanceManager instance in use.'); - } - - final ResolutionInfo resolution = - await getResolution(cameraInfoIdentifier, quality); - return resolution; - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/recorder.dart b/packages/camera/camera_android_camerax/lib/src/recorder.dart deleted file mode 100644 index 1fd93ec1b6eb..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/recorder.dart +++ /dev/null @@ -1,179 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart'; -import 'package:meta/meta.dart' show immutable; - -import 'android_camera_camerax_flutter_api_impls.dart'; -import 'camerax_library.g.dart'; -import 'fallback_strategy.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; -import 'pending_recording.dart'; -import 'quality_selector.dart'; - -/// A dart wrapping of the CameraX Recorder class. -/// -/// See https://developer.android.com/reference/androidx/camera/video/Recorder. -@immutable -class Recorder extends JavaObject { - /// Creates a [Recorder]. - Recorder( - {BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - this.aspectRatio, - this.bitRate, - this.qualitySelector}) - : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - _api = RecorderHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - _api.createFromInstance(this, aspectRatio, bitRate, qualitySelector); - } - - /// Creates a [Recorder] that is not automatically attached to a native object - Recorder.detached( - {BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - this.aspectRatio, - this.bitRate, - this.qualitySelector}) - : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = RecorderHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - } - - /// Returns default [QualitySelector] for recordings. - /// - /// See https://developer.android.com/reference/androidx/camera/video/Recorder#DEFAULT_QUALITY_SELECTOR(). - static QualitySelector getDefaultQualitySelector({ - BinaryMessenger? binaryMessenger, - InstanceManager? instanceManager, - }) { - return QualitySelector.fromOrderedList( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - qualityList: [ - VideoQualityData(quality: VideoQuality.FHD), - VideoQualityData(quality: VideoQuality.HD), - VideoQualityData(quality: VideoQuality.SD), - ], - fallbackStrategy: FallbackStrategy( - quality: VideoQuality.FHD, - fallbackRule: VideoResolutionFallbackRule.higherQualityOrLowerThan), - ); - } - - late final RecorderHostApiImpl _api; - - /// The video aspect ratio of this [Recorder]. - final int? aspectRatio; - - /// The intended video encoding bitrate for recording. - final int? bitRate; - - /// The [QualitySelector] of this [Recorder] used to select the resolution of - /// the recording depending on the resoutions supported by the camera. - /// - /// Default selector is that returned by [getDefaultQualitySelector], and it - /// is compatible with setting the aspect ratio. - final QualitySelector? qualitySelector; - - /// Prepare a recording that will be saved to a file. - Future prepareRecording(String path) { - return _api.prepareRecordingFromInstance(this, path); - } -} - -/// Host API implementation of [Recorder]. -class RecorderHostApiImpl extends RecorderHostApi { - /// Constructs a [RecorderHostApiImpl]. - RecorderHostApiImpl( - {this.binaryMessenger, InstanceManager? instanceManager}) { - this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - } - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default BinaryMessenger will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - late final InstanceManager instanceManager; - - /// Creates a [Recorder] with the provided aspect ratio and bitrate if specified. - void createFromInstance(Recorder instance, int? aspectRatio, int? bitRate, - QualitySelector? qualitySelector) { - int? identifier = instanceManager.getIdentifier(instance); - identifier ??= instanceManager.addDartCreatedInstance(instance, - onCopy: (Recorder original) { - return Recorder.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - aspectRatio: aspectRatio, - bitRate: bitRate, - qualitySelector: qualitySelector); - }); - create( - identifier, - aspectRatio, - bitRate, - qualitySelector == null - ? null - : instanceManager.getIdentifier(qualitySelector)!); - } - - /// Prepares a [Recording] using this recorder. The output file will be saved - /// at the provided path. - Future prepareRecordingFromInstance( - Recorder instance, String path) async { - final int pendingRecordingId = - await prepareRecording(instanceManager.getIdentifier(instance)!, path); - - return instanceManager.getInstanceWithWeakReference(pendingRecordingId)!; - } -} - -/// Flutter API implementation of [Recorder]. -class RecorderFlutterApiImpl extends RecorderFlutterApi { - /// Constructs a [RecorderFlutterApiImpl]. - RecorderFlutterApiImpl({ - this.binaryMessenger, - InstanceManager? instanceManager, - }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default BinaryMessenger will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager instanceManager; - - @override - void create(int identifier, int? aspectRatio, int? bitRate) { - instanceManager.addHostCreatedInstance( - Recorder.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - aspectRatio: aspectRatio, - bitRate: bitRate, - ), - identifier, onCopy: (Recorder original) { - return Recorder.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - aspectRatio: aspectRatio, - bitRate: bitRate, - ); - }); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/recording.dart b/packages/camera/camera_android_camerax/lib/src/recording.dart deleted file mode 100644 index ece29b3fa83f..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/recording.dart +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart' show BinaryMessenger; -import 'package:meta/meta.dart' show immutable; - -import 'android_camera_camerax_flutter_api_impls.dart'; -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; - -/// Wraps a CameraX recording class. -/// -/// See https://developer.android.com/reference/androidx/camera/video/Recording. -@immutable -class Recording extends JavaObject { - /// Constructs a detached [Recording] - Recording.detached( - {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager}) - : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ) { - _api = RecordingHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - } - - late final RecordingHostApiImpl _api; - - /// Closes this recording. - Future close() { - return _api.closeFromInstance(this); - } - - /// Pauses this recording if active. - Future pause() { - return _api.pauseFromInstance(this); - } - - /// Resumes the current recording if paused. - Future resume() { - return _api.resumeFromInstance(this); - } - - /// Stops the recording, as if calling close(). - Future stop() { - return _api.stopFromInstance(this); - } -} - -/// Host API implementation of [Recording]. -class RecordingHostApiImpl extends RecordingHostApi { - /// Creates a [RecordingHostApiImpl]. - RecordingHostApiImpl({this.binaryMessenger, InstanceManager? instanceManager}) - : super(binaryMessenger: binaryMessenger) { - this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - } - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default BinaryMessenger will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - late final InstanceManager instanceManager; - - /// Closes the specified recording instance. - Future closeFromInstance(Recording recording) async { - await close(instanceManager.getIdentifier(recording)!); - } - - /// Pauses the specified recording instance if active. - Future pauseFromInstance(Recording recording) async { - await pause(instanceManager.getIdentifier(recording)!); - } - - /// Resumes the specified recording instance if paused. - Future resumeFromInstance(Recording recording) async { - await resume(instanceManager.getIdentifier(recording)!); - } - - /// Stops the specified recording instance, as if calling closeFromInstance(). - Future stopFromInstance(Recording recording) async { - await stop(instanceManager.getIdentifier(recording)!); - } -} - -/// Flutter API implementation of [Recording]. -class RecordingFlutterApiImpl extends RecordingFlutterApi { - /// Constructs a [RecordingFlutterApiImpl]. - RecordingFlutterApiImpl({ - this.binaryMessenger, - InstanceManager? instanceManager, - }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default BinaryMessenger will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager instanceManager; - - @override - void create(int identifier) { - instanceManager.addHostCreatedInstance( - Recording.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ), - identifier, onCopy: (Recording original) { - return Recording.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ); - }); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/resolution_filter.dart b/packages/camera/camera_android_camerax/lib/src/resolution_filter.dart deleted file mode 100644 index 3a428a00e73a..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/resolution_filter.dart +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart'; -import 'package:meta/meta.dart' show immutable; - -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; - -/// Filterer for applications to specify preferred resolutions. -/// -/// This is an indirect wrapping of the native Android `ResolutionFilter`, -/// an interface that requires a synchronous response. Achieving such is not -/// possible through pigeon. Thus, constructing a [ResolutionFilter] with a -/// particular constructor will create a native `ResolutionFilter` with the -/// characteristics described in the documentation for that constructor, -/// respectively. -/// -/// If the provided constructors do not meet your needs, feel free to add a new -/// constructor; see CONTRIBUTING.MD for more information on how to do so. -/// -/// See https://developer.android.com/reference/androidx/camera/core/ResolutionFilter/ResolutionFilter. -@immutable -class ResolutionFilter extends JavaObject { - /// Constructs a [ResolutionFilter]. - /// - /// This will construct a native `ResolutionFilter` that will prioritize the - /// specified [preferredResolution] (if supported) over other supported - /// resolutions, whose priorities (as determined by CameraX) will remain the - /// same. - ResolutionFilter.onePreferredSize({ - required this.preferredResolution, - super.binaryMessenger, - super.instanceManager, - }) : _api = _ResolutionFilterHostApiImpl( - instanceManager: instanceManager, - binaryMessenger: binaryMessenger, - ), - super.detached() { - _api.createWithOnePreferredSizeFromInstances(this, preferredResolution); - } - - /// Instantiates a [ResolutionFilter.onePreferredSize] that is not - /// automatically attached to a native object. - ResolutionFilter.onePreferredSizeDetached({ - required this.preferredResolution, - super.binaryMessenger, - super.instanceManager, - }) : _api = _ResolutionFilterHostApiImpl( - instanceManager: instanceManager, - binaryMessenger: binaryMessenger, - ), - super.detached(); - - final _ResolutionFilterHostApiImpl _api; - - /// The resolution for a [ResolutionFilter.onePreferredSize] to prioritize. - final Size preferredResolution; -} - -/// Host API implementation of [ResolutionFilter]. -class _ResolutionFilterHostApiImpl extends ResolutionFilterHostApi { - /// Constructs an [_ResolutionFilterHostApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - _ResolutionFilterHostApiImpl({ - this.binaryMessenger, - InstanceManager? instanceManager, - }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager, - super(binaryMessenger: binaryMessenger); - - /// Receives binary data across the Flutter platform barrier. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager instanceManager; - - /// Creates a [ResolutionFilter] on the native side that will prioritize - /// the specified [preferredResolution]. - Future createWithOnePreferredSizeFromInstances( - ResolutionFilter instance, - Size preferredResolution, - ) { - return createWithOnePreferredSize( - instanceManager.addDartCreatedInstance( - instance, - onCopy: (ResolutionFilter original) => - ResolutionFilter.onePreferredSizeDetached( - preferredResolution: original.preferredResolution, - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ), - ), - ResolutionInfo( - width: preferredResolution.width.toInt(), - height: preferredResolution.height.toInt(), - ), - ); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/resolution_selector.dart b/packages/camera/camera_android_camerax/lib/src/resolution_selector.dart deleted file mode 100644 index 3017daab811a..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/resolution_selector.dart +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart'; -import 'package:meta/meta.dart' show immutable; - -import 'aspect_ratio_strategy.dart'; -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; -import 'resolution_filter.dart'; -import 'resolution_strategy.dart'; - -/// A set of requirements and priorities used to select a resolution for a -/// UseCase. -/// -/// See https://developer.android.com/reference/androidx/camera/core/resolutionselector/ResolutionSelector. -@immutable -class ResolutionSelector extends JavaObject { - /// Construct a [ResolutionSelector]. - ResolutionSelector({ - this.resolutionStrategy, - this.resolutionFilter, - this.aspectRatioStrategy, - super.binaryMessenger, - super.instanceManager, - }) : _api = _ResolutionSelectorHostApiImpl( - instanceManager: instanceManager, - binaryMessenger: binaryMessenger, - ), - super.detached() { - _api.createFromInstances( - this, resolutionStrategy, resolutionFilter, aspectRatioStrategy); - } - - /// Instantiates a [ResolutionSelector] without creating and attaching to an - /// instance of the associated native class. - /// - /// This should only be used outside of tests by subclasses created by this - /// library or to create a copy for an [InstanceManager]. - ResolutionSelector.detached({ - this.resolutionStrategy, - this.resolutionFilter, - this.aspectRatioStrategy, - super.binaryMessenger, - super.instanceManager, - }) : _api = _ResolutionSelectorHostApiImpl( - instanceManager: instanceManager, - binaryMessenger: binaryMessenger, - ), - super.detached(); - - final _ResolutionSelectorHostApiImpl _api; - - /// Determines how the UseCase will choose the resolution of the captured - /// image. - final ResolutionStrategy? resolutionStrategy; - - /// Filter for CameraX to automatically select a desirable resolution. - final ResolutionFilter? resolutionFilter; - - /// Determines how the UseCase will choose the aspect ratio of the captured - /// image. - final AspectRatioStrategy? aspectRatioStrategy; -} - -/// Host API implementation of [ResolutionSelector]. -class _ResolutionSelectorHostApiImpl extends ResolutionSelectorHostApi { - /// Constructs an [_ResolutionSelectorHostApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - _ResolutionSelectorHostApiImpl({ - this.binaryMessenger, - InstanceManager? instanceManager, - }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager, - super(binaryMessenger: binaryMessenger); - - /// Receives binary data across the Flutter platform barrier. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager instanceManager; - - /// Creates a [ResolutionSelector] on the native side with the - /// [ResolutionStrategy], [ResolutionFilter], and [AspectRatioStrategy] if - /// specified. - Future createFromInstances( - ResolutionSelector instance, - ResolutionStrategy? resolutionStrategy, - ResolutionFilter? resolutionFilter, - AspectRatioStrategy? aspectRatioStrategy, - ) { - return create( - instanceManager.addDartCreatedInstance( - instance, - onCopy: (ResolutionSelector original) => ResolutionSelector.detached( - resolutionStrategy: original.resolutionStrategy, - aspectRatioStrategy: original.aspectRatioStrategy, - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ), - ), - resolutionStrategy == null - ? null - : instanceManager.getIdentifier(resolutionStrategy)!, - resolutionFilter == null - ? null - : instanceManager.getIdentifier(resolutionFilter)!, - aspectRatioStrategy == null - ? null - : instanceManager.getIdentifier(aspectRatioStrategy)!, - ); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/resolution_strategy.dart b/packages/camera/camera_android_camerax/lib/src/resolution_strategy.dart deleted file mode 100644 index 80669f3f8d58..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/resolution_strategy.dart +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart'; -import 'package:meta/meta.dart' show immutable; - -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; - -/// The resolution strategy defines the resolution selection sequence to select -/// the best size. -/// -/// See https://developer.android.com/reference/androidx/camera/core/resolutionselector/ResolutionStrategy. -@immutable -class ResolutionStrategy extends JavaObject { - /// Constructs a [ResolutionStrategy]. - ResolutionStrategy({ - required Size this.boundSize, - this.fallbackRule, - super.binaryMessenger, - super.instanceManager, - }) : _api = _ResolutionStrategyHostApiImpl( - instanceManager: instanceManager, - binaryMessenger: binaryMessenger, - ), - super.detached() { - _api.createFromInstances(this, boundSize, fallbackRule); - } - - /// Constructs a [ResolutionStrategy] that represents the strategy that - /// chooses the highest available resolution. - /// - /// See https://developer.android.com/reference/androidx/camera/core/resolutionselector/ResolutionStrategy#HIGHEST_AVAILABLE_STRATEGY(). - ResolutionStrategy.highestAvailableStrategy({ - super.binaryMessenger, - super.instanceManager, - }) : _api = _ResolutionStrategyHostApiImpl( - instanceManager: instanceManager, - binaryMessenger: binaryMessenger, - ), - boundSize = null, - fallbackRule = null, - super.detached() { - _api.createFromInstances(this, boundSize, fallbackRule); - } - - /// Instantiates a [ResolutionStrategy] without creating and attaching to an - /// instance of the associated native class. - /// - /// This should only be used outside of tests by subclasses created by this - /// library or to create a copy for an [InstanceManager]. - ResolutionStrategy.detached({ - required this.boundSize, - this.fallbackRule, - super.binaryMessenger, - super.instanceManager, - }) : _api = _ResolutionStrategyHostApiImpl( - instanceManager: instanceManager, - binaryMessenger: binaryMessenger, - ), - super.detached(); - - /// Instantiates a [ResolutionStrategy] that represents the strategy that - /// chooses the highest available resolution without creating and attaching to - /// an instance of the associated native class. - /// - /// This should only be used outside of tests by subclasses created by this - /// library or to create a copy for an [InstanceManager]. - ResolutionStrategy.detachedHighestAvailableStrategy({ - super.binaryMessenger, - super.instanceManager, - }) : _api = _ResolutionStrategyHostApiImpl( - instanceManager: instanceManager, - binaryMessenger: binaryMessenger, - ), - boundSize = null, - fallbackRule = null, - super.detached(); - - /// CameraX doesn't select an alternate size when the specified bound size is - /// unavailable. - /// - /// Applications will receive [PlatformException] when binding the [UseCase]s - /// with this fallback rule if the device doesn't support the specified bound - /// size. - /// - /// See https://developer.android.com/reference/androidx/camera/core/resolutionselector/ResolutionStrategy#FALLBACK_RULE_NONE(). - static const int fallbackRuleNone = 0; - - /// When the specified bound size is unavailable, CameraX falls back to select - /// the closest higher resolution size. - /// - /// See https://developer.android.com/reference/androidx/camera/core/resolutionselector/ResolutionStrategy#FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER(). - static const int fallbackRuleClosestHigherThenLower = 1; - - /// When the specified bound size is unavailable, CameraX falls back to the - /// closest higher resolution size. - /// - /// If CameraX still cannot find any available resolution, it will fallback to - /// select other lower resolutions. - /// - /// See https://developer.android.com/reference/androidx/camera/core/resolutionselector/ResolutionStrategy#FALLBACK_RULE_CLOSEST_HIGHER(). - static const int fallbackRuleClosestHigher = 2; - - /// When the specified bound size is unavailable, CameraX falls back to select - /// the closest lower resolution size. - /// - /// If CameraX still cannot find any available resolution, it will fallback to - /// select other higher resolutions. - /// - /// See https://developer.android.com/reference/androidx/camera/core/resolutionselector/ResolutionStrategy#FALLBACK_RULE_CLOSEST_LOWER_THEN_HIGHER(). - static const int fallbackRuleClosestLowerThenHigher = 3; - - /// When the specified bound size is unavailable, CameraX falls back to the - /// closest lower resolution size. - /// - /// See https://developer.android.com/reference/androidx/camera/core/resolutionselector/ResolutionStrategy#FALLBACK_RULE_CLOSEST_LOWER(). - static const int fallbackRuleClosestLower = 4; - - final _ResolutionStrategyHostApiImpl _api; - - /// The specified bound size for the desired resolution of the camera. - /// - /// If left null, [fallbackRule] must also be left null in order to create a - /// valid [ResolutionStrategy]. This will create the [ResolutionStrategy] - /// that chooses the highest available resolution, which can also be retrieved - /// by calling [getHighestAvailableStrategy]. - final Size? boundSize; - - /// The fallback rule for choosing an alternate size when the specified bound - /// size is unavailable. - /// - /// Must be left null if [boundSize] is specified as null. This will create - /// the [ResolutionStrategy] that chooses the highest available resolution, - /// which can also be retrieved by calling [getHighestAvailableStrategy]. - final int? fallbackRule; -} - -/// Host API implementation of [ResolutionStrategy]. -class _ResolutionStrategyHostApiImpl extends ResolutionStrategyHostApi { - /// Constructs an [_ResolutionStrategyHostApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. If left null, it - /// will default to the global instance defined in [JavaObject]. - _ResolutionStrategyHostApiImpl({ - this.binaryMessenger, - InstanceManager? instanceManager, - }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager, - super(binaryMessenger: binaryMessenger); - - /// Receives binary data across the Flutter platform barrier. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager instanceManager; - - /// Creates a [ResolutionStrategy] on the native side with the bound [Size] - /// and fallback rule, if specified. - Future createFromInstances( - ResolutionStrategy instance, - Size? boundSize, - int? fallbackRule, - ) { - return create( - instanceManager.addDartCreatedInstance( - instance, - onCopy: (ResolutionStrategy original) => ResolutionStrategy.detached( - boundSize: original.boundSize, - fallbackRule: original.fallbackRule, - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ), - ), - boundSize == null - ? null - : ResolutionInfo( - width: boundSize.width.toInt(), - height: boundSize.height.toInt(), - ), - fallbackRule, - ); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/rotated_preview.dart b/packages/camera/camera_android_camerax/lib/src/rotated_preview.dart index 849de39013f0..f757b77366b8 100644 --- a/packages/camera/camera_android_camerax/lib/src/rotated_preview.dart +++ b/packages/camera/camera_android_camerax/lib/src/rotated_preview.dart @@ -60,8 +60,9 @@ final class _RotatedPreviewState extends State { @override void initState() { deviceOrientation = widget.initialDeviceOrientation; - deviceOrientationSubscription = - widget.deviceOrientation.listen((DeviceOrientation event) { + deviceOrientationSubscription = widget.deviceOrientation.listen(( + DeviceOrientation event, + ) { // Ensure that we aren't updating the state if the widget is being destroyed. if (!mounted) { return; @@ -111,9 +112,6 @@ final class _RotatedPreviewState extends State { sensorOrientationDegrees: widget.sensorOrientationDegrees, sign: widget.facingSign, ); - return RotatedBox( - quarterTurns: rotationDegrees ~/ 90, - child: widget.child, - ); + return RotatedBox(quarterTurns: rotationDegrees ~/ 90, child: widget.child); } } diff --git a/packages/camera/camera_android_camerax/lib/src/surface.dart b/packages/camera/camera_android_camerax/lib/src/surface.dart deleted file mode 100644 index 925b43bf3c08..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/surface.dart +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:meta/meta.dart' show immutable; - -import 'java_object.dart'; - -/// Handle onto the raw buffer managed by screen compositor. -/// -/// See https://developer.android.com/reference/android/view/Surface.html. -@immutable -class Surface extends JavaObject { - /// Creates a detached [Surface]. - Surface.detached({super.binaryMessenger, super.instanceManager}) - : super.detached(); - - /// Rotation constant to signify the natural orientation. - /// - /// See https://developer.android.com/reference/android/view/Surface.html#ROTATION_0. - static const int rotation0 = 0; - - /// Rotation constant to signify a 90 degrees rotation. - /// - /// See https://developer.android.com/reference/android/view/Surface.html#ROTATION_90. - static const int rotation90 = 1; - - /// Rotation constant to signify a 180 degrees rotation. - /// - /// See https://developer.android.com/reference/android/view/Surface.html#ROTATION_180. - static const int rotation180 = 2; - - /// Rotation constant to signify a 270 degrees rotation. - /// - /// See https://developer.android.com/reference/android/view/Surface.html#ROTATION_270. - static const int rotation270 = 3; -} diff --git a/packages/camera/camera_android_camerax/lib/src/system_services.dart b/packages/camera/camera_android_camerax/lib/src/system_services.dart deleted file mode 100644 index b75a1cb98035..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/system_services.dart +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'dart:async'; - -import 'package:camera_platform_interface/camera_platform_interface.dart' - show CameraException; -import 'package:flutter/services.dart'; - -import 'camerax_library.g.dart'; - -// Ignoring lint indicating this class only contains static members -// as this class is a wrapper for various Android system services. -// ignore_for_file: avoid_classes_with_only_static_members - -/// Utility class that offers access to Android system services needed for -/// camera usage and other informational streams. -class SystemServices { - /// Stream that emits the errors caused by camera usage on the native side. - static final StreamController cameraErrorStreamController = - StreamController.broadcast(); - - /// Requests permission to access the camera and audio if specified. - static Future requestCameraPermissions(bool enableAudio, - {BinaryMessenger? binaryMessenger}) { - final SystemServicesHostApiImpl api = - SystemServicesHostApiImpl(binaryMessenger: binaryMessenger); - - return api.sendCameraPermissionsRequest(enableAudio); - } - - /// Returns a file path which was used to create a temporary file. - /// Prefix is a part of the file name, and suffix is the file extension. - /// - /// The file and path constraints are determined by the implementation of - /// File.createTempFile(prefix, suffix, cacheDir), on the android side, where - /// where cacheDir is the cache directory identified by the current application - /// context using context.getCacheDir(). - /// - /// Ex: getTempFilePath('prefix', 'suffix') would return a string of the form - /// '/prefix3213453.suffix', where the numbers after prefix and - /// before suffix are determined by the call to File.createTempFile and - /// therefore random. - static Future getTempFilePath(String prefix, String suffix, - {BinaryMessenger? binaryMessenger}) { - final SystemServicesHostApi api = - SystemServicesHostApi(binaryMessenger: binaryMessenger); - return api.getTempFilePath(prefix, suffix); - } -} - -/// Host API implementation of [SystemServices]. -class SystemServicesHostApiImpl extends SystemServicesHostApi { - /// Constructs an [SystemServicesHostApiImpl]. - /// - /// If [binaryMessenger] is null, the default [BinaryMessenger] will be used, - /// which routes to the host platform. - SystemServicesHostApiImpl({this.binaryMessenger}) - : super(binaryMessenger: binaryMessenger); - - /// Receives binary data across the Flutter platform barrier. - final BinaryMessenger? binaryMessenger; - - /// Requests permission to access the camera and audio if specified. - /// - /// Will complete normally if permissions are successfully granted; otherwise, - /// will throw a [CameraException]. - Future sendCameraPermissionsRequest(bool enableAudio) async { - final CameraPermissionsErrorData? error = - await requestCameraPermissions(enableAudio); - - if (error != null) { - throw CameraException( - error.errorCode, - error.description, - ); - } - } -} - -/// Flutter API implementation of [SystemServices]. -class SystemServicesFlutterApiImpl implements SystemServicesFlutterApi { - /// Constructs an [SystemServicesFlutterApiImpl]. - SystemServicesFlutterApiImpl(); - - /// Callback method for any errors caused by camera usage on the Java side. - @override - void onCameraError(String errorDescription) { - SystemServices.cameraErrorStreamController.add(errorDescription); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/use_case.dart b/packages/camera/camera_android_camerax/lib/src/use_case.dart deleted file mode 100644 index bb305c91a22a..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/use_case.dart +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:meta/meta.dart' show immutable; - -import 'java_object.dart'; - -/// An object representing the different functionalities of the camera. -/// -/// See https://developer.android.com/reference/androidx/camera/core/UseCase. -@immutable -class UseCase extends JavaObject { - /// Creates a detached [UseCase]. - UseCase.detached({super.binaryMessenger, super.instanceManager}) - : super.detached(); -} diff --git a/packages/camera/camera_android_camerax/lib/src/video_capture.dart b/packages/camera/camera_android_camerax/lib/src/video_capture.dart deleted file mode 100644 index c3d4403a6ca7..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/video_capture.dart +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart'; -import 'package:meta/meta.dart' show immutable; - -import 'android_camera_camerax_flutter_api_impls.dart'; -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; -import 'recorder.dart'; -import 'use_case.dart'; - -/// Dart wrapping of CameraX VideoCapture class. -/// -/// See https://developer.android.com/reference/androidx/camera/video/VideoCapture. -@immutable -class VideoCapture extends UseCase { - /// Creates a [VideoCapture] that is not automatically attached to a native - /// object. - VideoCapture.detached( - {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager}) - : super.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager) { - _api = VideoCaptureHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - } - - late final VideoCaptureHostApiImpl _api; - - /// Creates a [VideoCapture] associated with the given [Recorder]. - static Future withOutput(Recorder recorder, - {BinaryMessenger? binaryMessenger, InstanceManager? instanceManager}) { - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - final VideoCaptureHostApiImpl api = VideoCaptureHostApiImpl( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - - return api.withOutputFromInstance(recorder); - } - - /// Dynamically sets the target rotation of this instance. - /// - /// [rotation] should be specified in terms of one of the [Surface] - /// rotation constants that represents the counter-clockwise degrees of - /// rotation relative to [DeviceOrientation.portraitUp]. - Future setTargetRotation(int rotation) => - _api.setTargetRotationFromInstances(this, rotation); - - /// Gets the [Recorder] associated with this VideoCapture. - Future getOutput() { - return _api.getOutputFromInstance(this); - } -} - -/// Host API implementation of [VideoCapture]. -class VideoCaptureHostApiImpl extends VideoCaptureHostApi { - /// Constructs a [VideoCaptureHostApiImpl]. - VideoCaptureHostApiImpl( - {this.binaryMessenger, InstanceManager? instanceManager}) { - this.instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - } - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default BinaryMessenger will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - late final InstanceManager instanceManager; - - /// Creates a [VideoCapture] associated with the provided [Recorder] instance. - Future withOutputFromInstance(Recorder recorder) async { - int? identifier = instanceManager.getIdentifier(recorder); - identifier ??= instanceManager.addDartCreatedInstance(recorder, - onCopy: (Recorder original) { - return Recorder( - binaryMessenger: binaryMessenger, instanceManager: instanceManager); - }); - final int videoCaptureId = await withOutput(identifier); - return instanceManager - .getInstanceWithWeakReference(videoCaptureId)!; - } - - /// Dynamically sets the target rotation of [instance] to [rotation]. - Future setTargetRotationFromInstances( - VideoCapture instance, int rotation) { - return setTargetRotation( - instanceManager.getIdentifier(instance)!, rotation); - } - - /// Gets the [Recorder] associated with the provided [VideoCapture] instance. - Future getOutputFromInstance(VideoCapture instance) async { - final int? identifier = instanceManager.getIdentifier(instance); - final int recorderId = await getOutput(identifier!); - return instanceManager.getInstanceWithWeakReference(recorderId)!; - } -} - -/// Flutter API implementation of [VideoCapture]. -class VideoCaptureFlutterApiImpl implements VideoCaptureFlutterApi { - /// Constructs a [VideoCaptureFlutterApiImpl]. - VideoCaptureFlutterApiImpl({ - this.binaryMessenger, - InstanceManager? instanceManager, - }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default BinaryMessenger will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager instanceManager; - - @override - void create(int identifier) { - instanceManager.addHostCreatedInstance( - VideoCapture.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ), - identifier, onCopy: (VideoCapture original) { - return VideoCapture.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - ); - }); - } -} diff --git a/packages/camera/camera_android_camerax/lib/src/zoom_state.dart b/packages/camera/camera_android_camerax/lib/src/zoom_state.dart deleted file mode 100644 index 6fe5321389b6..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/zoom_state.dart +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:flutter/services.dart' show BinaryMessenger; -import 'package:meta/meta.dart' show immutable; - -import 'android_camera_camerax_flutter_api_impls.dart'; -import 'camerax_library.g.dart'; -import 'instance_manager.dart'; -import 'java_object.dart'; - -/// Represents zoom related information of a camera. -/// -/// See https://developer.android.com/reference/androidx/camera/core/ZoomState. -@immutable -class ZoomState extends JavaObject { - /// Constructs a [ZoomState] that is not automatically attached to a native object. - ZoomState.detached( - {super.binaryMessenger, - super.instanceManager, - required this.minZoomRatio, - required this.maxZoomRatio}) - : super.detached() { - AndroidCameraXCameraFlutterApis.instance.ensureSetUp(); - } - - /// The minimum zoom ratio of the camera represented by this instance. - final double minZoomRatio; - - /// The maximum zoom ratio of the camera represented by this instance. - final double maxZoomRatio; -} - -/// Flutter API implementation of [ZoomState]. -class ZoomStateFlutterApiImpl implements ZoomStateFlutterApi { - /// Constructs a [ZoomStateFlutterApiImpl]. - /// - /// An [instanceManager] is typically passed when a copy of an instance - /// contained by an [InstanceManager] is being created. - ZoomStateFlutterApiImpl({ - this.binaryMessenger, - InstanceManager? instanceManager, - }) : instanceManager = instanceManager ?? JavaObject.globalInstanceManager; - - /// Receives binary data across the Flutter platform barrier. - /// - /// If it is null, the default BinaryMessenger will be used which routes to - /// the host platform. - final BinaryMessenger? binaryMessenger; - - /// Maintains instances stored to communicate with native language objects. - final InstanceManager instanceManager; - - @override - void create(int identifier, double minZoomRatio, double maxZoomRatio) { - instanceManager.addHostCreatedInstance( - ZoomState.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - minZoomRatio: minZoomRatio, - maxZoomRatio: maxZoomRatio), - identifier, - onCopy: (ZoomState original) { - return ZoomState.detached( - binaryMessenger: binaryMessenger, - instanceManager: instanceManager, - minZoomRatio: original.minZoomRatio, - maxZoomRatio: original.maxZoomRatio); - }, - ); - } -} diff --git a/packages/camera/camera_android_camerax/pigeons/camerax_library.dart b/packages/camera/camera_android_camerax/pigeons/camerax_library.dart index a6e4eded23ab..41430df0d064 100644 --- a/packages/camera/camera_android_camerax/pigeons/camerax_library.dart +++ b/packages/camera/camera_android_camerax/pigeons/camerax_library.dart @@ -2,98 +2,136 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// ignore_for_file: avoid_unused_constructor_parameters + import 'package:pigeon/pigeon.dart'; @ConfigurePigeon( PigeonOptions( + copyrightHeader: 'pigeons/copyright.txt', dartOut: 'lib/src/camerax_library.g.dart', - dartTestOut: 'test/test_camerax_library.g.dart', - dartOptions: DartOptions(copyrightHeader: [ - 'Copyright 2013 The Flutter Authors. All rights reserved.', - 'Use of this source code is governed by a BSD-style license that can be', - 'found in the LICENSE file.', - ]), - javaOut: - 'android/src/main/java/io/flutter/plugins/camerax/GeneratedCameraXLibrary.java', - javaOptions: JavaOptions( + kotlinOut: + 'android/src/main/java/io/flutter/plugins/camerax/CameraXLibrary.g.kt', + kotlinOptions: KotlinOptions( package: 'io.flutter.plugins.camerax', - className: 'GeneratedCameraXLibrary', - copyrightHeader: [ - 'Copyright 2013 The Flutter Authors. All rights reserved.', - 'Use of this source code is governed by a BSD-style license that can be', - 'found in the LICENSE file.', - ], + errorClassName: 'CameraXError', ), ), ) -class ResolutionInfo { - ResolutionInfo({ - required this.width, - required this.height, - }); - int width; - int height; +/// Immutable class for describing width and height dimensions in pixels. +/// +/// See https://developer.android.com/reference/android/util/Size.html. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.util.Size'), +) +abstract class CameraSize { + CameraSize(); + + /// The width of the size (in pixels). + late int width; + + /// The height of the size (in pixels). + late int height; +} + +/// A `ResolutionInfo` allows the application to know the resolution information +/// of a specific use case. +/// +/// See https://developer.android.com/reference/androidx/camera/core/ResolutionInfo. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.ResolutionInfo', + ), +) +abstract class ResolutionInfo { + /// Returns the output resolution used for the use case. + late CameraSize resolution; } -class CameraPermissionsErrorData { - CameraPermissionsErrorData({ - required this.errorCode, - required this.description, - }); +/// Generally classifies the overall set of the camera device functionality. +/// +/// See https://developer.android.com/reference/android/hardware/camera2/CameraMetadata#INFO_SUPPORTED_HARDWARE_LEVEL_3. +enum InfoSupportedHardwareLevel { + /// This camera device is capable of YUV reprocessing and RAW data capture, in + /// addition to FULL-level capabilities. + level3, + + /// This camera device is backed by an external camera connected to this + /// Android device. + external, + + /// This camera device is capable of supporting advanced imaging applications. + full, + + /// This camera device is running in backward compatibility mode. + legacy, - String errorCode; - String description; + /// This camera device does not have enough capabilities to qualify as a FULL + /// device or better. + limited, +} + +/// The aspect ratio of the use case. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/AspectRatio. +enum AspectRatio { + /// 16:9 standard aspect ratio. + ratio16To9, + + /// 4:3 standard aspect ratio. + ratio4To3, + + /// The aspect ratio representing no preference for aspect ratio. + ratioDefault, + + /// The value is not recognized by the wrapper. + unknown, } /// The states the camera can be in. /// /// See https://developer.android.com/reference/androidx/camera/core/CameraState.Type. enum CameraStateType { + /// Represents a state where the camera device is closed. closed, + + /// Represents a state where the camera device is currently closing. closing, + + /// Represents a state where the camera device is open. open, + + /// Represents a state where the camera device is currently opening. opening, + + /// Represents a state where the camera is waiting for a signal to attempt to + /// open the camera device. pendingOpen, -} -class CameraStateTypeData { - late CameraStateType value; + /// This value is not recognized by this wrapper. + unknown, } /// The types (T) properly wrapped to be used as a LiveData. +enum LiveDataSupportedType { cameraState, zoomState } + +/// Immutable class for describing the range of two integer values. /// -/// If you need to add another type to support a type S to use a LiveData in -/// this plugin, ensure the following is done on the Dart side: -/// -/// * In `camera_android_camerax/lib/src/live_data.dart`, add new cases for S in -/// `_LiveDataHostApiImpl#getValueFromInstances` to get the current value of -/// type S from a LiveData instance and in `LiveDataFlutterApiImpl#create` -/// to create the expected type of LiveData when requested. -/// -/// On the native side, ensure the following is done: +/// This is the equivalent to `android.util.Range`. /// -/// * Make sure `LiveDataHostApiImpl#getValue` is updated to properly return -/// identifiers for instances of type S. -/// * Update `ObserverFlutterApiWrapper#onChanged` to properly handle receiving -/// calls with instances of type S if a LiveData instance is observed. -enum LiveDataSupportedType { - cameraState, - zoomState, -} - -class LiveDataSupportedTypeData { - late LiveDataSupportedType value; -} +/// See https://developer.android.com/reference/android/util/Range.html. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions(fullClassName: 'android.util.Range<*>'), +) +abstract class CameraIntegerRange { + CameraIntegerRange(); -class ExposureCompensationRange { - ExposureCompensationRange({ - required this.minCompensation, - required this.maxCompensation, - }); + /// The lower endpoint. + late int lower; - int minCompensation; - int maxCompensation; + /// The upper endpoint. + late int upper; } /// Video quality constraints that will be used by a QualitySelector to choose @@ -103,174 +141,262 @@ class ExposureCompensationRange { /// /// See https://developer.android.com/reference/androidx/camera/video/Quality. enum VideoQuality { - SD, // 480p - HD, // 720p - FHD, // 1080p - UHD, // 2160p + /// Standard Definition (SD) 480p video quality. + SD, + + /// High Definition (HD) 720p video quality. + HD, + + /// Full High Definition (FHD) 1080p video quality. + FHD, + + /// Ultra High Definition (UHD) 2160p video quality. + UHD, + + /// The lowest video quality supported by the video frame producer. lowest, + + /// The highest video quality supported by the video frame producer. highest, } -/// Convenience class for sending lists of [Quality]s. -class VideoQualityData { - late VideoQuality quality; -} +/// VideoRecordEvent is used to report video recording events and status. +/// +/// See https://developer.android.com/reference/androidx/camera/video/VideoRecordEvent. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.video.VideoRecordEvent', + ), +) +abstract class VideoRecordEvent {} -/// Fallback rules for selecting video resolution. +/// Indicates the start of recording. /// -/// See https://developer.android.com/reference/androidx/camera/video/FallbackStrategy. -enum VideoResolutionFallbackRule { - higherQualityOrLowerThan, - higherQualityThan, - lowerQualityOrHigherThan, - lowerQualityThan, -} +/// See https://developer.android.com/reference/androidx/camera/video/VideoRecordEvent.Start. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.video.VideoRecordEvent.Start', + ), +) +abstract class VideoRecordEventStart extends VideoRecordEvent {} -/// Video recording status. +/// Indicates the finalization of recording. /// -/// See https://developer.android.com/reference/androidx/camera/video/VideoRecordEvent. -enum VideoRecordEvent { start, finalize } +/// See https://developer.android.com/reference/androidx/camera/video/VideoRecordEvent.Finalize. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.video.VideoRecordEvent.Finalize', + ), +) +abstract class VideoRecordEventFinalize extends VideoRecordEvent {} -class VideoRecordEventData { - late VideoRecordEvent value; +/// A MeteringPoint is used to specify a region which can then be converted to +/// sensor coordinate system for focus and metering purpose. +/// +/// See https://developer.android.com/reference/androidx/camera/core/MeteringPoint. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.MeteringPoint', + ), +) +abstract class MeteringPoint { + /// Size of the MeteringPoint width and height (ranging from 0 to 1). + /// + /// It is the percentage of the sensor width/height (or crop region + /// width/height if crop region is set). + double getSize(); } -/// Convenience class for building [FocusMeteringAction]s with multiple metering -/// points. -class MeteringPointInfo { - MeteringPointInfo({ - required this.meteringPointId, - required this.meteringMode, - }); +/// A flag used for indicating metering mode regions. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/FocusMeteringAction#FLAG_AF(). +enum MeteringMode { + /// A flag used in metering mode indicating the AE (Auto Exposure) region is + /// enabled. + ae, - /// InstanceManager ID for a [MeteringPoint]. - int meteringPointId; + /// A flag used in metering mode indicating the AF (Auto Focus) region is + /// enabled. + af, - /// The metering mode of the [MeteringPoint] whose ID is [meteringPointId]. - /// - /// Metering mode should be one of the [FocusMeteringAction] constants. - int? meteringMode; + /// A flag used in metering mode indicating the AWB (Auto White Balance) + /// region is enabled. + awb, } -/// The types of capture request options this plugin currently supports. -/// -/// If you need to add another option to support, ensure the following is done -/// on the Dart side: -/// -/// * In `camera_android_camerax/lib/src/capture_request_options.dart`, add new cases for this -/// option in `_CaptureRequestOptionsHostApiImpl#createFromInstances` -/// to create the expected Map entry of option key index and value to send to -/// the native side. -/// -/// On the native side, ensure the following is done: +/// A simple callback that can receive from LiveData. /// -/// * Update `CaptureRequestOptionsHostApiImpl#create` to set the correct -/// `CaptureRequest` key with a valid value type for this option. -/// -/// See https://developer.android.com/reference/android/hardware/camera2/CaptureRequest -/// for the sorts of capture request options that can be supported via CameraX's -/// interoperability with Camera2. -enum CaptureRequestKeySupportedType { - controlAeLock, -} +/// See https://developer.android.com/reference/androidx/lifecycle/Observer. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.lifecycle.Observer<*>', + ), +) +abstract class Observer { + Observer(); -@HostApi(dartHostTestHandler: 'TestInstanceManagerHostApi') -abstract class InstanceManagerHostApi { - /// Clear the native `InstanceManager`. - /// - /// This is typically only used after a hot restart. - void clear(); + /// Called when the data is changed to value. + late void Function(Object value) onChanged; } -@HostApi(dartHostTestHandler: 'TestJavaObjectHostApi') -abstract class JavaObjectHostApi { - void dispose(int identifier); -} +/// An interface for retrieving camera information. +/// +/// See https://developer.android.com/reference/androidx/camera/core/CameraInfo. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.CameraInfo', + ), +) +abstract class CameraInfo { + /// Returns the sensor rotation in degrees, relative to the device's "natural" + /// (default) orientation. + late int sensorRotationDegrees; + + /// Returns a ExposureState. + late ExposureState exposureState; -@FlutterApi() -abstract class JavaObjectFlutterApi { - void dispose(int identifier); + /// A LiveData of the camera's state. + LiveData getCameraState(); + + /// A LiveData of ZoomState. + LiveData getZoomState(); } -@HostApi(dartHostTestHandler: 'TestCameraInfoHostApi') -abstract class CameraInfoHostApi { - int getSensorRotationDegrees(int identifier); +/// Direction of lens of a camera. +/// +/// See https://developer.android.com/reference/androidx/camera/core/CameraSelector#LENS_FACING_BACK(). +enum LensFacing { + /// A camera on the device facing the same direction as the device's screen. + front, - int getCameraState(int identifier); + /// A camera on the device facing the opposite direction as the device's + /// screen. + back, - int getExposureState(int identifier); + /// An external camera that has no fixed facing relative to the device's + /// screen. + external, - int getZoomState(int identifier); + /// A camera on the devices that its lens facing is resolved. + unknown, } -@FlutterApi() -abstract class CameraInfoFlutterApi { - void create(int identifier); -} +/// A set of requirements and priorities used to select a camera or return a +/// filtered set of cameras. +/// +/// See https://developer.android.com/reference/androidx/camera/core/CameraSelector. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.CameraSelector', + ), +) +abstract class CameraSelector { + CameraSelector(LensFacing? requireLensFacing); -@HostApi(dartHostTestHandler: 'TestCameraSelectorHostApi') -abstract class CameraSelectorHostApi { - void create(int identifier, int? lensFacing); + /// A static `CameraSelector` that selects the default back facing camera. + @static + late CameraSelector defaultBackCamera; - List filter(int identifier, List cameraInfoIds); -} + /// A static `CameraSelector` that selects the default front facing camera. + @static + late CameraSelector defaultFrontCamera; -@FlutterApi() -abstract class CameraSelectorFlutterApi { - void create(int identifier, int? lensFacing); + /// Filters the input `CameraInfo`s using the `CameraFilter`s assigned to the + /// selector. + List filter(List cameraInfos); } -@HostApi(dartHostTestHandler: 'TestProcessCameraProviderHostApi') -abstract class ProcessCameraProviderHostApi { +/// A singleton which can be used to bind the lifecycle of cameras to any +/// `LifecycleOwner` within an application's process. +/// +/// See https://developer.android.com/reference/androidx/camera/lifecycle/ProcessCameraProvider. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.lifecycle.ProcessCameraProvider', + ), +) +abstract class ProcessCameraProvider { + /// Retrieves the ProcessCameraProvider associated with the current process. @async - int getInstance(); + @static + ProcessCameraProvider getInstance(); - List getAvailableCameraInfos(int identifier); + /// The `CameraInfo` instances of the available cameras. + List getAvailableCameraInfos(); - int bindToLifecycle( - int identifier, int cameraSelectorIdentifier, List useCaseIds); + /// Binds the collection of `UseCase` to a `LifecycleOwner`. + Camera bindToLifecycle(CameraSelector cameraSelector, List useCases); - bool isBound(int identifier, int useCaseIdentifier); + /// Returns true if the `UseCase` is bound to a lifecycle. + bool isBound(UseCase useCase); - void unbind(int identifier, List useCaseIds); + /// Unbinds all specified use cases from the lifecycle provider. + void unbind(List useCases); - void unbindAll(int identifier); + /// Unbinds all use cases from the lifecycle provider and removes them from + /// CameraX. + void unbindAll(); } -@FlutterApi() -abstract class ProcessCameraProviderFlutterApi { - void create(int identifier); -} +/// The use case which all other use cases are built on top of. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/UseCase. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.UseCase', + ), +) +abstract class UseCase {} -@HostApi(dartHostTestHandler: 'TestCameraHostApi') -abstract class CameraHostApi { - int getCameraInfo(int identifier); +/// The camera interface is used to control the flow of data to use cases, +/// control the camera via the `CameraControl`, and publish the state of the +/// camera via CameraInfo. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/Camera. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.Camera', + ), +) +abstract class Camera { + /// The `CameraControl` for the Camera. + late CameraControl cameraControl; - int getCameraControl(int identifier); + /// Returns information about this camera. + CameraInfo getCameraInfo(); } -@FlutterApi() -abstract class CameraFlutterApi { - void create(int identifier); -} +/// Convenience class for accessing system resources. +@ProxyApi() +abstract class SystemServicesManager { + SystemServicesManager(); + + late void Function(String errorDescription) onCameraError; -@HostApi(dartHostTestHandler: 'TestSystemServicesHostApi') -abstract class SystemServicesHostApi { @async - CameraPermissionsErrorData? requestCameraPermissions(bool enableAudio); + CameraPermissionsError? requestCameraPermissions(bool enableAudio); + /// Returns a path to be used to create a temp file in the current cache + /// directory. String getTempFilePath(String prefix, String suffix); } -@FlutterApi() -abstract class SystemServicesFlutterApi { - void onCameraError(String errorDescription); +/// Contains data when an attempt to retrieve camera permissions fails. +@ProxyApi() +abstract class CameraPermissionsError { + late final String errorCode; + late final String description; } -@HostApi(dartHostTestHandler: 'TestDeviceOrientationManagerHostApi') -abstract class DeviceOrientationManagerHostApi { - void startListeningForDeviceOrientationChange( - bool isFrontFacing, int sensorOrientation); +/// Support class to help to determine the media orientation based on the +/// orientation of the device. +@ProxyApi() +abstract class DeviceOrientationManager { + DeviceOrientationManager(); + + late void Function(String orientation) onDeviceOrientationChanged; + + void startListeningForDeviceOrientationChange(); void stopListeningForDeviceOrientationChange(); @@ -279,298 +405,861 @@ abstract class DeviceOrientationManagerHostApi { String getUiOrientation(); } -@FlutterApi() -abstract class DeviceOrientationManagerFlutterApi { - void onDeviceOrientationChanged(String orientation); +/// A use case that provides a camera preview stream for displaying on-screen. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/Preview. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.Preview', + ), +) +abstract class Preview extends UseCase { + Preview(int? targetRotation); + + late final ResolutionSelector? resolutionSelector; + + /// Sets a SurfaceProvider to provide a Surface for Preview. + /// + /// This is a convenience function that + /// 1. Creates a `SurfaceProvider` using the `SurfaceProducer` provided by the + /// Flutter engine. + /// 2. Sets this method with the created `SurfaceProvider`. + /// 3. Returns the texture id of the `TextureEntry` that provided the + /// `SurfaceProducer`. + int setSurfaceProvider(SystemServicesManager systemServicesManager); + + /// Releases the `SurfaceProducer` created in `setSurfaceProvider` if one was + /// created. + void releaseSurfaceProvider(); + + /// Gets selected resolution information of the `Preview`. + ResolutionInfo? getResolutionInfo(); + + /// Sets the target rotation. + void setTargetRotation(int rotation); + + /// Returns whether or not the preview's surface producer handles correctly + /// rotating the camera preview automatically. + bool surfaceProducerHandlesCropAndRotation(); } -@HostApi(dartHostTestHandler: 'TestPreviewHostApi') -abstract class PreviewHostApi { - void create(int identifier, int? rotation, int? resolutionSelectorId); +/// A use case that provides camera stream suitable for video application. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/video/VideoCapture. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.video.VideoCapture<*>', + ), +) +abstract class VideoCapture extends UseCase { + /// Create a `VideoCapture` associated with the given `VideoOutput`. + VideoCapture.withOutput(VideoOutput videoOutput); - int setSurfaceProvider(int identifier); + /// Gets the VideoOutput associated with this VideoCapture. + VideoOutput getOutput(); - void releaseFlutterSurfaceTexture(); + /// Sets the desired rotation of the output video. + void setTargetRotation(int rotation); +} - ResolutionInfo getResolutionInfo(int identifier); +/// A class that will produce video data from a Surface. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/video/VideoOutput. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.video.VideoOutput', + ), +) +abstract class VideoOutput {} - void setTargetRotation(int identifier, int rotation); +/// An implementation of `VideoOutput` for starting video recordings that are +/// saved to a File, ParcelFileDescriptor, or MediaStore. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/video/Recorder. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.video.Recorder', + ), +) +abstract class Recorder implements VideoOutput { + Recorder( + int? aspectRatio, + int? targetVideoEncodingBitRate, + QualitySelector? qualitySelector, + ); - bool surfaceProducerHandlesCropAndRotation(); -} + /// Gets the aspect ratio of this Recorder. + int getAspectRatio(); -@HostApi(dartHostTestHandler: 'TestVideoCaptureHostApi') -abstract class VideoCaptureHostApi { - int withOutput(int videoOutputId); + /// Gets the target video encoding bitrate of this Recorder. + int getTargetVideoEncodingBitRate(); - int getOutput(int identifier); + /// The quality selector of this Recorder. + QualitySelector getQualitySelector(); - void setTargetRotation(int identifier, int rotation); + /// Prepares a recording that will be saved to a File. + PendingRecording prepareRecording(String path); } -@FlutterApi() -abstract class VideoCaptureFlutterApi { - void create(int identifier); +/// Listens for `VideoRecordEvent`s from a `PendingRecording`. +@ProxyApi() +abstract class VideoRecordEventListener { + VideoRecordEventListener(); + + late void Function(VideoRecordEvent event) onEvent; } -@HostApi(dartHostTestHandler: 'TestRecorderHostApi') -abstract class RecorderHostApi { - void create( - int identifier, int? aspectRatio, int? bitRate, int? qualitySelectorId); +/// A recording that can be started at a future time. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/video/PendingRecording. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.video.PendingRecording', + ), +) +abstract class PendingRecording { + /// Starts the recording, making it an active recording. + Recording start(VideoRecordEventListener listener); +} - int getAspectRatio(int identifier); +/// Provides controls for the currently active recording. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/video/Recording. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.video.Recording', + ), +) +abstract class Recording { + /// Close this recording. + void close(); - int getTargetVideoEncodingBitRate(int identifier); + /// Pauses the current recording if active. + void pause(); - int prepareRecording(int identifier, String path); -} + /// Resumes the current recording if paused. + void resume(); -@FlutterApi() -abstract class RecorderFlutterApi { - void create(int identifier, int? aspectRatio, int? bitRate); + /// Stops the recording, as if calling `close`. + /// + /// This method is equivalent to calling `close`. + void stop(); } -@HostApi(dartHostTestHandler: 'TestPendingRecordingHostApi') -abstract class PendingRecordingHostApi { - int start(int identifier); -} +/// FlashModes for image capture. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageCapture#FLASH_MODE_AUTO(). +enum CameraXFlashMode { + /// Auto flash. + /// + /// The flash will be used according to the camera system's determination when + /// taking a picture. + auto, -@FlutterApi() -abstract class PendingRecordingFlutterApi { - void create(int identifier); + /// No flash. + /// + /// The flash will never be used when taking a picture. + off, - void onVideoRecordingEvent(VideoRecordEventData event); + /// Always flash. + /// + /// The flash will always be used when taking a picture. + on, } -@HostApi(dartHostTestHandler: 'TestRecordingHostApi') -abstract class RecordingHostApi { - void close(int identifier); +/// A use case for taking a picture. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageCapture. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.ImageCapture', + ), +) +abstract class ImageCapture extends UseCase { + ImageCapture(int? targetRotation, CameraXFlashMode? flashMode); - void pause(int identifier); + late final ResolutionSelector? resolutionSelector; - void resume(int identifier); + /// Set the flash mode. + void setFlashMode(CameraXFlashMode flashMode); - void stop(int identifier); + /// Captures a new still image for in memory access. + @async + String takePicture(); + + /// Sets the desired rotation of the output image. + void setTargetRotation(int rotation); } -@FlutterApi() -abstract class RecordingFlutterApi { - void create(int identifier); +/// Fallback rule for choosing an alternate size when the specified bound size +/// is unavailable. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/resolutionselector/ResolutionStrategy. +enum ResolutionStrategyFallbackRule { + /// When the specified bound size is unavailable, CameraX falls back to the + /// closest higher resolution size. + closestHigher, + + /// When the specified bound size is unavailable, CameraX falls back to select + /// the closest higher resolution size. + closestHigherThenLower, + + /// When the specified bound size is unavailable, CameraX falls back to the + /// closest lower resolution size. + closestLower, + + /// When the specified bound size is unavailable, CameraX falls back to select + /// the closest lower resolution size. + /// + /// If CameraX still cannot find any available resolution, it will fallback to + /// select other higher resolutions. + closestLowerThenHigher, + + /// CameraX doesn't select an alternate size when the specified bound size is + /// unavailable. + none, + + /// The value is not recognized by the wrapper. + unknown, } -@HostApi(dartHostTestHandler: 'TestImageCaptureHostApi') -abstract class ImageCaptureHostApi { - void create(int identifier, int? targetRotation, int? flashMode, - int? resolutionSelectorId); +/// The resolution strategy defines the resolution selection sequence to select +/// the best size. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/resolutionselector/ResolutionStrategy. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.resolutionselector.ResolutionStrategy', + ), +) +abstract class ResolutionStrategy { + ResolutionStrategy( + CameraSize boundSize, + ResolutionStrategyFallbackRule fallbackRule, + ); - void setFlashMode(int identifier, int flashMode); + /// A resolution strategy chooses the highest available resolution. + @static + late ResolutionStrategy highestAvailableStrategy; - @async - String takePicture(int identifier); + /// The specified bound size. + CameraSize? getBoundSize(); - void setTargetRotation(int identifier, int rotation); + /// The fallback rule for choosing an alternate size when the specified bound + /// size is unavailable. + ResolutionStrategyFallbackRule getFallbackRule(); } -@HostApi(dartHostTestHandler: 'TestResolutionStrategyHostApi') -abstract class ResolutionStrategyHostApi { - void create(int identifier, ResolutionInfo? boundSize, int? fallbackRule); +/// A set of requirements and priorities used to select a resolution for the +/// `UseCase`. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/resolutionselector/ResolutionSelector. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.resolutionselector.ResolutionSelector', + ), +) +abstract class ResolutionSelector { + ResolutionSelector(AspectRatioStrategy? aspectRatioStrategy); + + /// The resolution filter to output the final desired sizes list. + late final ResolutionFilter? resolutionFilter; + + /// The resolution selection strategy for the `UseCase`. + late final ResolutionStrategy? resolutionStrategy; + + /// Returns the specified `AspectRatioStrategy`, or + /// `AspectRatioStrategy.ratio_4_3FallbackAutoStrategy` if none is specified + /// when creating the ResolutionSelector. + AspectRatioStrategy getAspectRatioStrategy(); } -@HostApi(dartHostTestHandler: 'TestResolutionSelectorHostApi') -abstract class ResolutionSelectorHostApi { - void create( - int identifier, - int? resolutionStrategyIdentifier, - int? resolutionSelectorIdentifier, - int? aspectRatioStrategyIdentifier, - ); +/// Fallback rule for choosing the aspect ratio when the preferred aspect ratio +/// is not available. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/resolutionselector/AspectRatioStrategy#FALLBACK_RULE_AUTO(). +enum AspectRatioStrategyFallbackRule { + /// CameraX automatically chooses the next best aspect ratio which contains + /// the closest field of view (FOV) of the camera sensor, from the remaining + /// options. + auto, + + /// CameraX doesn't fall back to select sizes of any other aspect ratio when + /// this fallback rule is used. + none, + + /// The value is not recognized by the wrapper. + unknown, } -@HostApi(dartHostTestHandler: 'TestAspectRatioStrategyHostApi') -abstract class AspectRatioStrategyHostApi { - void create(int identifier, int preferredAspectRatio, int fallbackRule); +/// The aspect ratio strategy defines the sequence of aspect ratios that are +/// used to select the best size for a particular image. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/resolutionselector/AspectRatioStrategy. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: + 'androidx.camera.core.resolutionselector.AspectRatioStrategy', + ), +) +abstract class AspectRatioStrategy { + /// Creates a new AspectRatioStrategy instance, configured with the specified + /// preferred aspect ratio and fallback rule. + AspectRatioStrategy( + AspectRatio preferredAspectRatio, + AspectRatioStrategyFallbackRule fallbackRule, + ); + + /// The pre-defined aspect ratio strategy that selects sizes with RATIO_16_9 + /// in priority. + @static + late AspectRatioStrategy ratio_16_9FallbackAutoStrategy; + + /// The pre-defined default aspect ratio strategy that selects sizes with + /// RATIO_4_3 in priority. + @static + late AspectRatioStrategy ratio_4_3FallbackAutoStrategy; + + /// The specified fallback rule for choosing the aspect ratio when the + /// preferred aspect ratio is not available. + AspectRatioStrategyFallbackRule getFallbackRule(); + + /// The specified preferred aspect ratio. + AspectRatio getPreferredAspectRatio(); } -@FlutterApi() -abstract class CameraStateFlutterApi { - void create(int identifier, CameraStateTypeData type, int? errorIdentifier); +/// Represents the different states the camera can be in. +/// +/// See https://developer.android.com/reference/androidx/camera/core/CameraState. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.CameraState', + ), +) +abstract class CameraState { + /// The camera's state. + late CameraStateType type; + + /// Potentially returns an error the camera encountered. + late CameraStateStateError? error; } -@FlutterApi() -abstract class ExposureStateFlutterApi { - void create( - int identifier, - ExposureCompensationRange exposureCompensationRange, - double exposureCompensationStep); +/// An interface which contains the camera exposure related information. +/// +/// See https://developer.android.com/reference/androidx/camera/core/ExposureState. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.ExposureState', + ), +) +abstract class ExposureState { + /// Get the maximum and minimum exposure compensation values for + /// `CameraControl.setExposureCompensationIndex`. + late CameraIntegerRange exposureCompensationRange; + + /// Get the smallest step by which the exposure compensation can be changed. + late double exposureCompensationStep; } -@FlutterApi() -abstract class ZoomStateFlutterApi { - void create(int identifier, double minZoomRatio, double maxZoomRatio); +/// An interface which contains the zoom related information from a camera. +/// +/// See https://developer.android.com/reference/androidx/camera/core/ZoomState. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.ZoomState', + ), +) +abstract class ZoomState { + /// The minimum zoom ratio. + late double minZoomRatio; + + /// The maximum zoom ratio. + late double maxZoomRatio; } -@HostApi(dartHostTestHandler: 'TestImageAnalysisHostApi') -abstract class ImageAnalysisHostApi { - void create(int identifier, int? targetRotation, int? resolutionSelectorId); +/// A use case providing CPU accessible images for an app to perform image +/// analysis on. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageAnalysis. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.ImageAnalysis', + ), +) +abstract class ImageAnalysis extends UseCase { + ImageAnalysis(int? targetRotation); - void setAnalyzer(int identifier, int analyzerIdentifier); + late final ResolutionSelector? resolutionSelector; - void clearAnalyzer(int identifier); + /// Sets an analyzer to receive and analyze images. + void setAnalyzer(Analyzer analyzer); - void setTargetRotation(int identifier, int rotation); -} + /// Removes a previously set analyzer. + void clearAnalyzer(); -@HostApi(dartHostTestHandler: 'TestAnalyzerHostApi') -abstract class AnalyzerHostApi { - void create(int identifier); + /// Sets the target rotation. + void setTargetRotation(int rotation); } -@HostApi(dartHostTestHandler: 'TestObserverHostApi') -abstract class ObserverHostApi { - void create(int identifier); -} +/// Interface for analyzing images. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageAnalysis.Analyzer. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.ImageAnalysis.Analyzer', + ), +) +abstract class Analyzer { + Analyzer(); -@FlutterApi() -abstract class ObserverFlutterApi { - void onChanged(int identifier, int valueIdentifier); + /// Analyzes an image to produce a result. + late void Function(ImageProxy image) analyze; } -@FlutterApi() -abstract class CameraStateErrorFlutterApi { - void create(int identifier, int code); -} +/// Code for a `CameraState` error. +/// +/// https://developer.android.com/reference/androidx/camera/core/CameraState#ERROR_CAMERA_DISABLED() +enum CameraStateErrorCode { + /// An error indicating that the camera device could not be opened due to a + /// device policy. + cameraDisabled, + + /// An error indicating that the camera device was closed due to a fatal + /// error. + cameraFatalError, + + /// An error indicating that the camera device is already in use. + cameraInUse, -@HostApi(dartHostTestHandler: 'TestLiveDataHostApi') -abstract class LiveDataHostApi { - void observe(int identifier, int observerIdentifier); + /// An error indicating that the camera could not be opened because "Do Not + /// Disturb" mode is enabled on devices affected by a bug in Android 9 (API + /// level 28). + doNotDisturbModeEnabled, - void removeObservers(int identifier); + /// An error indicating that the limit number of open cameras has been + /// reached, and more cameras cannot be opened until other instances are + /// closed. + maxCamerasInUse, - int? getValue(int identifier, LiveDataSupportedTypeData type); + /// An error indicating that the camera device has encountered a recoverable + /// error. + otherRecoverableError, + + /// An error indicating that configuring the camera has failed. + streamConfig, + + /// The value is not recognized by this wrapper. + unknown, } -@FlutterApi() -abstract class LiveDataFlutterApi { - void create(int identifier, LiveDataSupportedTypeData type); +/// Error that the camera has encountered. +/// +/// See https://developer.android.com/reference/androidx/camera/core/CameraState.StateError. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.CameraState.StateError', + ), +) +abstract class CameraStateStateError { + /// The code of this error. + late CameraStateErrorCode code; } -@FlutterApi() -abstract class AnalyzerFlutterApi { - void create(int identifier); +/// LiveData is a data holder class that can be observed within a given +/// lifecycle. +/// +/// This is a wrapper around the native class to better support the generic +/// type. Java has type erasure; +/// +/// See https://developer.android.com/reference/androidx/lifecycle/LiveData. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: + 'io.flutter.plugins.camerax.LiveDataProxyApi.LiveDataWrapper', + ), +) +abstract class LiveData { + /// The generic type used by this instance. + late LiveDataSupportedType type; - void analyze(int identifier, int imageProxyIdentifier); -} + /// Adds the given observer to the observers list within the lifespan of the + /// given owner. + void observe(Observer observer); -@HostApi(dartHostTestHandler: 'TestImageProxyHostApi') -abstract class ImageProxyHostApi { - List getPlanes(int identifier); + /// Removes all observers that are tied to the given `LifecycleOwner`. + void removeObservers(); - void close(int identifier); + /// Returns the current value. + Object? getValue(); } -@FlutterApi() -abstract class ImageProxyFlutterApi { - void create(int identifier, int format, int height, int width); +/// An image proxy which has a similar interface as `android.media.Image`. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageProxy. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.ImageProxy', + ), +) +abstract class ImageProxy { + /// The image format. + late int format; + + /// The image width. + late int width; + + /// The image height. + late int height; + + /// Returns the array of planes. + List getPlanes(); + + /// Closes the underlying `android.media.Image`. + void close(); } -@FlutterApi() -abstract class PlaneProxyFlutterApi { - void create(int identifier, Uint8List buffer, int pixelStride, int rowStride); +/// A plane proxy which has an analogous interface as +/// `android.media.Image.Plane`. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/ImageProxy.PlaneProxy. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.ImageProxy.PlaneProxy', + ), +) +abstract class PlaneProxy { + /// The pixels buffer. + late Uint8List buffer; + + /// The pixel stride. + late int pixelStride; + + /// The row stride. + late int rowStride; } -@HostApi(dartHostTestHandler: 'TestQualitySelectorHostApi') -abstract class QualitySelectorHostApi { - void create(int identifier, List videoQualityDataList, - int? fallbackStrategyId); +/// Defines a desired quality setting that can be used to configure components +/// with quality setting requirements such as creating a Recorder. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/video/QualitySelector. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.video.QualitySelector', + ), +) +abstract class QualitySelector { + /// Gets an instance of QualitySelector with a desired quality. + QualitySelector.from( + VideoQuality quality, + FallbackStrategy? fallbackStrategy, + ); - ResolutionInfo getResolution(int cameraInfoId, VideoQuality quality); + /// Gets an instance of QualitySelector with ordered desired qualities. + QualitySelector.fromOrderedList( + List qualities, + FallbackStrategy? fallbackStrategy, + ); + + /// Gets the corresponding resolution from the input quality. + @static + CameraSize? getResolution(CameraInfo cameraInfo, VideoQuality quality); } -@HostApi(dartHostTestHandler: 'TestFallbackStrategyHostApi') -abstract class FallbackStrategyHostApi { - void create(int identifier, VideoQuality quality, - VideoResolutionFallbackRule fallbackRule); +/// A class represents the strategy that will be adopted when the device does +/// not support all the desired Quality in QualitySelector in order to select +/// the quality as possible. +/// +/// See https://developer.android.com/reference/androidx/camera/video/FallbackStrategy. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.video.FallbackStrategy', + ), +) +abstract class FallbackStrategy { + /// Returns a fallback strategy that will choose the quality that is closest + /// to and higher than the input quality. + FallbackStrategy.higherQualityOrLowerThan(VideoQuality quality); + + /// Returns a fallback strategy that will choose the quality that is closest + /// to and higher than the input quality. + FallbackStrategy.higherQualityThan(VideoQuality quality); + + /// Returns a fallback strategy that will choose the quality that is closest + /// to and lower than the input quality. + FallbackStrategy.lowerQualityOrHigherThan(VideoQuality quality); + + /// Returns a fallback strategy that will choose the quality that is closest + /// to and lower than the input quality. + FallbackStrategy.lowerQualityThan(VideoQuality quality); } -@HostApi(dartHostTestHandler: 'TestCameraControlHostApi') -abstract class CameraControlHostApi { +/// The CameraControl provides various asynchronous operations like zoom, focus +/// and metering which affects output of all UseCases currently bound to that +/// camera. +/// +/// See https://developer.android.com/reference/androidx/camera/core/CameraControl. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.CameraControl', + ), +) +abstract class CameraControl { + /// Enable the torch or disable the torch. @async - void enableTorch(int identifier, bool torch); + void enableTorch(bool torch); + /// Sets current zoom by ratio. @async - void setZoomRatio(int identifier, double ratio); + void setZoomRatio(double ratio); + /// Starts a focus and metering action configured by the + /// `FocusMeteringAction`. @async - int? startFocusAndMetering(int identifier, int focusMeteringActionId); + FocusMeteringResult? startFocusAndMetering(FocusMeteringAction action); + /// Cancels current FocusMeteringAction and clears AF/AE/AWB regions. @async - void cancelFocusAndMetering(int identifier); + void cancelFocusAndMetering(); + /// Set the exposure compensation value for the camera. @async - int? setExposureCompensationIndex(int identifier, int index); + int? setExposureCompensationIndex(int index); } -@FlutterApi() -abstract class CameraControlFlutterApi { - void create(int identifier); +/// The builder used to create the `FocusMeteringAction`. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/FocusMeteringAction.Builder. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.FocusMeteringAction.Builder', + ), +) +abstract class FocusMeteringActionBuilder { + /// Creates a Builder from a `MeteringPoint` with default mode FLAG_AF | + /// FLAG_AE | FLAG_AWB. + FocusMeteringActionBuilder(MeteringPoint point); + + /// Creates a Builder from a `MeteringPoint` and `MeteringMode`. + FocusMeteringActionBuilder.withMode(MeteringPoint point, MeteringMode mode); + + /// Adds another MeteringPoint with default metering mode. + void addPoint(MeteringPoint point); + + /// Adds another MeteringPoint with specified meteringMode. + void addPointWithMode(MeteringPoint point, MeteringMode mode); + + /// Disables the auto-cancel. + void disableAutoCancel(); + + /// Builds the `FocusMeteringAction` instance. + FocusMeteringAction build(); } -@HostApi(dartHostTestHandler: 'TestFocusMeteringActionHostApi') -abstract class FocusMeteringActionHostApi { - void create(int identifier, List meteringPointInfos, - bool? disableAutoCancel); +/// A configuration used to trigger a focus and/or metering action. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/FocusMeteringAction. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.FocusMeteringAction', + ), +) +abstract class FocusMeteringAction { + /// All MeteringPoints used for AE regions. + late List meteringPointsAe; + + /// All MeteringPoints used for AF regions. + late List meteringPointsAf; + + /// All MeteringPoints used for AWB regions. + late List meteringPointsAwb; + + /// If auto-cancel is enabled or not. + late bool isAutoCancelEnabled; } -@HostApi(dartHostTestHandler: 'TestFocusMeteringResultHostApi') -abstract class FocusMeteringResultHostApi { - bool isFocusSuccessful(int identifier); +/// Result of the `CameraControl.startFocusAndMetering`. +/// +/// See https://developer.android.com/reference/androidx/camera/core/FocusMeteringResult. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.FocusMeteringResult', + ), +) +abstract class FocusMeteringResult { + /// If auto focus is successful. + late bool isFocusSuccessful; } -@FlutterApi() -abstract class FocusMeteringResultFlutterApi { - void create(int identifier); +/// An immutable package of settings and outputs needed to capture a single +/// image from the camera device. +/// +/// See https://developer.android.com/reference/android/hardware/camera2/CaptureRequest. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'android.hardware.camera2.CaptureRequest', + ), +) +abstract class CaptureRequest { + /// Whether auto-exposure (AE) is currently locked to its latest calculated + /// values. + /// + /// Value is boolean. + /// + /// This key is available on all devices. + @static + late CaptureRequestKey controlAELock; } -@HostApi(dartHostTestHandler: 'TestMeteringPointHostApi') -abstract class MeteringPointHostApi { - void create( - int identifier, double x, double y, double? size, int cameraInfoId); +/// A Key is used to do capture request field lookups with CaptureRequest.get or +/// to set fields with `CaptureRequest.Builder.set`. +/// +/// See https://developer.android.com/reference/android/hardware/camera2/CaptureRequest.Key.html. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'android.hardware.camera2.CaptureRequest.Key<*>', + ), +) +abstract class CaptureRequestKey {} - double getDefaultPointSize(); -} +/// A bundle of Camera2 capture request options. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/camera2/interop/CaptureRequestOptions. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.camera2.interop.CaptureRequestOptions', + ), +) +abstract class CaptureRequestOptions { + CaptureRequestOptions(Map options); -@HostApi(dartHostTestHandler: 'TestCaptureRequestOptionsHostApi') -abstract class CaptureRequestOptionsHostApi { - void create(int identifier, Map options); + /// Returns a value for the given CaptureRequestKey or null if it hasn't been + /// set. + Object? getCaptureRequestOption(CaptureRequestKey key); } -@HostApi(dartHostTestHandler: 'TestCamera2CameraControlHostApi') -abstract class Camera2CameraControlHostApi { - void create(int identifier, int cameraControlIdentifier); +/// An class that provides ability to interoperate with the +/// 1android.hardware.camera21 APIs. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/camera2/interop/Camera2CameraControl. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.camera2.interop.Camera2CameraControl', + ), +) +abstract class Camera2CameraControl { + /// Gets the `Camera2CameraControl` from a `CameraControl`. + Camera2CameraControl.from(CameraControl cameraControl); + /// Adds a `CaptureRequestOptions` updates the session with the options it + /// contains. @async - void addCaptureRequestOptions( - int identifier, int captureRequestOptionsIdentifier); + void addCaptureRequestOptions(CaptureRequestOptions bundle); } -@HostApi(dartHostTestHandler: 'TestResolutionFilterHostApi') -abstract class ResolutionFilterHostApi { - void createWithOnePreferredSize( - int identifier, ResolutionInfo preferredResolution); +/// Applications can filter out unsuitable sizes and sort the resolution list in +/// the preferred order by implementing the resolution filter interface. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/core/resolutionselector/ResolutionFilter. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.resolutionselector.ResolutionFilter', + ), +) +abstract class ResolutionFilter { + ResolutionFilter.createWithOnePreferredSize(CameraSize preferredSize); +} + +/// A Key is used to do camera characteristics field lookups with +/// `CameraCharacteristics.get`. +/// +/// See https://developer.android.com/reference/android/hardware/camera2/CameraCharacteristics.Key.html. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'android.hardware.camera2.CameraCharacteristics.Key<*>', + ), +) +abstract class CameraCharacteristicsKey {} + +/// The properties describing a `CameraDevice`. +/// +/// See https://developer.android.com/reference/android/hardware/camera2/CameraCharacteristics. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'android.hardware.camera2.CameraCharacteristics', + ), +) +abstract class CameraCharacteristics { + /// Generally classifies the overall set of the camera device functionality. + /// + /// Value is `InfoSupportedHardwareLevel`. + /// + /// This key is available on all devices. + @static + late CameraCharacteristicsKey infoSupportedHardwareLevel; + + /// Clockwise angle through which the output image needs to be rotated to be + /// upright on the device screen in its native orientation.. + /// + /// Value is int. + /// + /// This key is available on all devices. + @static + late CameraCharacteristicsKey sensorOrientation; } -@HostApi(dartHostTestHandler: 'TestCamera2CameraInfoHostApi') -abstract class Camera2CameraInfoHostApi { - int createFrom(int cameraInfoIdentifier); +/// An interface for retrieving Camera2-related camera information. +/// +/// See https://developer.android.com/reference/kotlin/androidx/camera/camera2/interop/Camera2CameraInfo. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.camera2.interop.Camera2CameraInfo', + ), +) +abstract class Camera2CameraInfo { + /// Gets the `Camera2CameraInfo` from a `CameraInfo`. + Camera2CameraInfo.from(CameraInfo cameraInfo); - int getSupportedHardwareLevel(int identifier); + /// Gets the string camera ID. + String getCameraId(); - String getCameraId(int identifier); + /// Gets a camera characteristic value. + Object? getCameraCharacteristic(CameraCharacteristicsKey key); +} - int getSensorOrientation(int identifier); +/// A factory to create a MeteringPoint. +/// +/// See https://developer.android.com/reference/androidx/camera/core/MeteringPointFactory. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.MeteringPointFactory', + ), +) +abstract class MeteringPointFactory { + /// Creates a MeteringPoint by x, y. + MeteringPoint createPoint(double x, double y); + + /// Creates a MeteringPoint by x, y, size. + MeteringPoint createPointWithSize(double x, double y, double size); } -@FlutterApi() -abstract class Camera2CameraInfoFlutterApi { - void create(int identifier); +/// A MeteringPointFactory that can convert a View (x, y) into a MeteringPoint +/// which can then be used to construct a FocusMeteringAction to start a focus +/// and metering action. +/// +/// See https://developer.android.com/reference/androidx/camera/core/DisplayOrientedMeteringPointFactory. +@ProxyApi( + kotlinOptions: KotlinProxyApiOptions( + fullClassName: 'androidx.camera.core.DisplayOrientedMeteringPointFactory', + ), +) +abstract class DisplayOrientedMeteringPointFactory + extends MeteringPointFactory { + /// Creates a DisplayOrientedMeteringPointFactory for converting View (x, y) + /// into a MeteringPoint based on the current display's rotation and + /// CameraInfo. + DisplayOrientedMeteringPointFactory( + CameraInfo cameraInfo, + double width, + double height, + ); } diff --git a/packages/camera/camera_android_camerax/pigeons/copyright.txt b/packages/camera/camera_android_camerax/pigeons/copyright.txt new file mode 100644 index 000000000000..fb682b1ab965 --- /dev/null +++ b/packages/camera/camera_android_camerax/pigeons/copyright.txt @@ -0,0 +1,3 @@ +Copyright 2013 The Flutter Authors. All rights reserved. +Use of this source code is governed by a BSD-style license that can be +found in the LICENSE file. \ No newline at end of file diff --git a/packages/camera/camera_android_camerax/pubspec.yaml b/packages/camera/camera_android_camerax/pubspec.yaml index c611b2f69b49..2f524a3b132f 100644 --- a/packages/camera/camera_android_camerax/pubspec.yaml +++ b/packages/camera/camera_android_camerax/pubspec.yaml @@ -2,7 +2,7 @@ name: camera_android_camerax description: Android implementation of the camera plugin using the CameraX library. repository: https://github.com/flutter/packages/tree/main/packages/camera/camera_android_camerax issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+camera%22 -version: 0.6.14+1 +version: 0.6.15 environment: sdk: ^3.6.0 @@ -31,7 +31,7 @@ dev_dependencies: sdk: flutter leak_tracker_flutter_testing: any mockito: ^5.4.4 - pigeon: ^9.1.0 + pigeon: ^25.0.0 topics: - camera diff --git a/packages/camera/camera_android_camerax/test/analyzer_test.dart b/packages/camera/camera_android_camerax/test/analyzer_test.dart deleted file mode 100644 index 9729a5bd5625..000000000000 --- a/packages/camera/camera_android_camerax/test/analyzer_test.dart +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/analyzer.dart'; -import 'package:camera_android_camerax/src/image_proxy.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'analyzer_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([TestAnalyzerHostApi, TestInstanceManagerHostApi]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('Analyzer', () { - setUp(() {}); - - tearDown(() { - TestAnalyzerHostApi.setup(null); - }); - - test('HostApi create', () { - final MockTestAnalyzerHostApi mockApi = MockTestAnalyzerHostApi(); - TestAnalyzerHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final Analyzer instance = Analyzer( - analyze: (ImageProxy imageProxy) async {}, - instanceManager: instanceManager, - ); - - verify(mockApi.create( - instanceManager.getIdentifier(instance), - )); - }); - - test('FlutterAPI create', () { - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final AnalyzerFlutterApiImpl api = AnalyzerFlutterApiImpl( - instanceManager: instanceManager, - ); - - const int instanceIdentifier = 0; - - api.create( - instanceIdentifier, - ); - - expect( - instanceManager.getInstanceWithWeakReference(instanceIdentifier), - isA(), - ); - }); - - test('analyze', () { - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - const int instanceIdentifier = 0; - const int imageProxyIdentifier = 44; - late final Object callbackParameter; - final Analyzer instance = Analyzer.detached( - analyze: ( - ImageProxy imageProxy, - ) async { - callbackParameter = imageProxy; - }, - instanceManager: instanceManager, - ); - instanceManager.addHostCreatedInstance( - instance, - instanceIdentifier, - onCopy: (Analyzer original) => Analyzer.detached( - analyze: original.analyze, - instanceManager: instanceManager, - ), - ); - final ImageProxy imageProxy = ImageProxy.detached( - instanceManager: instanceManager, format: 3, height: 4, width: 5); - instanceManager.addHostCreatedInstance(imageProxy, imageProxyIdentifier, - onCopy: (ImageProxy original) => ImageProxy.detached( - instanceManager: instanceManager, - format: original.format, - height: original.height, - width: original.width)); - - final AnalyzerFlutterApiImpl flutterApi = AnalyzerFlutterApiImpl( - instanceManager: instanceManager, - ); - - flutterApi.analyze( - instanceIdentifier, - imageProxyIdentifier, - ); - - expect( - callbackParameter, - imageProxy, - ); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/analyzer_test.mocks.dart b/packages/camera/camera_android_camerax/test/analyzer_test.mocks.dart deleted file mode 100644 index d4800f14839d..000000000000 --- a/packages/camera/camera_android_camerax/test/analyzer_test.mocks.dart +++ /dev/null @@ -1,59 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/analyzer_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestAnalyzerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestAnalyzerHostApi extends _i1.Mock - implements _i2.TestAnalyzerHostApi { - MockTestAnalyzerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void create(int? identifier) => super.noSuchMethod( - Invocation.method( - #create, - [identifier], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} diff --git a/packages/camera/camera_android_camerax/test/android_camera_camerax_test.dart b/packages/camera/camera_android_camerax/test/android_camera_camerax_test.dart index 2e4a5c83af71..a9c2141ee6b3 100644 --- a/packages/camera/camera_android_camerax/test/android_camera_camerax_test.dart +++ b/packages/camera/camera_android_camerax/test/android_camera_camerax_test.dart @@ -7,70 +7,36 @@ import 'dart:math' show Point; import 'package:async/async.dart'; import 'package:camera_android_camerax/camera_android_camerax.dart'; -import 'package:camera_android_camerax/src/analyzer.dart'; -import 'package:camera_android_camerax/src/aspect_ratio_strategy.dart'; -import 'package:camera_android_camerax/src/camera.dart'; -import 'package:camera_android_camerax/src/camera2_camera_control.dart'; -import 'package:camera_android_camerax/src/camera2_camera_info.dart'; -import 'package:camera_android_camerax/src/camera_control.dart'; -import 'package:camera_android_camerax/src/camera_info.dart'; -import 'package:camera_android_camerax/src/camera_metadata.dart'; -import 'package:camera_android_camerax/src/camera_selector.dart'; -import 'package:camera_android_camerax/src/camera_state.dart'; -import 'package:camera_android_camerax/src/camera_state_error.dart'; -import 'package:camera_android_camerax/src/camerax_library.g.dart'; +import 'package:camera_android_camerax/src/camerax_library.dart'; import 'package:camera_android_camerax/src/camerax_proxy.dart'; -import 'package:camera_android_camerax/src/capture_request_options.dart'; -import 'package:camera_android_camerax/src/device_orientation_manager.dart'; -import 'package:camera_android_camerax/src/exposure_state.dart'; -import 'package:camera_android_camerax/src/fallback_strategy.dart'; -import 'package:camera_android_camerax/src/focus_metering_action.dart'; -import 'package:camera_android_camerax/src/focus_metering_result.dart'; -import 'package:camera_android_camerax/src/image_analysis.dart'; -import 'package:camera_android_camerax/src/image_capture.dart'; -import 'package:camera_android_camerax/src/image_proxy.dart'; -import 'package:camera_android_camerax/src/live_data.dart'; -import 'package:camera_android_camerax/src/metering_point.dart'; -import 'package:camera_android_camerax/src/observer.dart'; -import 'package:camera_android_camerax/src/pending_recording.dart'; -import 'package:camera_android_camerax/src/plane_proxy.dart'; -import 'package:camera_android_camerax/src/preview.dart'; -import 'package:camera_android_camerax/src/process_camera_provider.dart'; -import 'package:camera_android_camerax/src/quality_selector.dart'; -import 'package:camera_android_camerax/src/recorder.dart'; -import 'package:camera_android_camerax/src/recording.dart'; -import 'package:camera_android_camerax/src/resolution_filter.dart'; -import 'package:camera_android_camerax/src/resolution_selector.dart'; -import 'package:camera_android_camerax/src/resolution_strategy.dart'; -import 'package:camera_android_camerax/src/surface.dart'; -import 'package:camera_android_camerax/src/system_services.dart'; -import 'package:camera_android_camerax/src/use_case.dart'; -import 'package:camera_android_camerax/src/video_capture.dart'; -import 'package:camera_android_camerax/src/zoom_state.dart'; import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:flutter/services.dart' - show DeviceOrientation, PlatformException, Uint8List; -import 'package:flutter/widgets.dart' show BuildContext, Size; + show BinaryMessenger, DeviceOrientation, PlatformException, Uint8List; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'android_camera_camerax_test.mocks.dart'; -import 'test_camerax_library.g.dart'; @GenerateNiceMocks(>[ MockSpec(), MockSpec(), - MockSpec(), MockSpec(), MockSpec(), + MockSpec(), MockSpec(), + MockSpec(), MockSpec(), MockSpec(), MockSpec(), MockSpec(), + MockSpec(), + MockSpec(), + MockSpec(), + MockSpec(), MockSpec(), MockSpec(), + MockSpec(), MockSpec(), MockSpec(), MockSpec(), @@ -86,26 +52,33 @@ import 'test_camerax_library.g.dart'; MockSpec(), MockSpec(), MockSpec(), - MockSpec(), - MockSpec(), + MockSpec(), MockSpec(), MockSpec(), ]) -@GenerateMocks([], customMocks: >[ - MockSpec>(as: #MockLiveCameraState), - MockSpec>(as: #MockLiveZoomState), -]) +@GenerateMocks( + [], + customMocks: >[ + MockSpec>(as: #MockLiveCameraState), + MockSpec>(as: #MockLiveZoomState), + ], +) void main() { TestWidgetsFlutterBinding.ensureInitialized(); - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - /// Helper method for testing sending/receiving CameraErrorEvents. - Future testCameraClosingObserver(AndroidCameraCameraX camera, - int cameraId, Observer observer) async { - final CameraStateError testCameraStateError = - CameraStateError.detached(code: 0); + Future testCameraClosingObserver( + AndroidCameraCameraX camera, + int cameraId, + Observer observer, + ) async { + final CameraStateStateError testCameraStateError = + CameraStateStateError.pigeon_detached( + code: CameraStateErrorCode.doNotDisturbModeEnabled, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); final Stream cameraClosingEventStream = camera.onCameraClosing(cameraId); final StreamQueue cameraClosingStreamQueue = @@ -115,13 +88,24 @@ void main() { final StreamQueue cameraErrorStreamQueue = StreamQueue(cameraErrorEventStream); - observer.onChanged(CameraState.detached( - type: CameraStateType.closing, error: testCameraStateError)); + observer.onChanged( + observer, + CameraState.pigeon_detached( + type: CameraStateType.closing, + error: testCameraStateError, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ), + ); final bool cameraClosingEventSent = await cameraClosingStreamQueue.next == CameraClosingEvent(cameraId); final bool cameraErrorSent = await cameraErrorStreamQueue.next == - CameraErrorEvent(cameraId, testCameraStateError.getDescription()); + CameraErrorEvent( + cameraId, + 'The camera could not be opened because "Do Not Disturb" mode is enabled. Please disable this mode, and try opening the camera again.', + ); await cameraClosingStreamQueue.cancel(); await cameraErrorStreamQueue.cancel(); @@ -132,94 +116,438 @@ void main() { /// CameraXProxy for testing functionality related to the camera resolution /// preset (setting expected ResolutionSelectors, QualitySelectors, etc.). CameraXProxy getProxyForTestingResolutionPreset( - MockProcessCameraProvider mockProcessCameraProvider) => - CameraXProxy( - getProcessCameraProvider: () => - Future.value(mockProcessCameraProvider), - createCameraSelector: (int cameraSelectorLensDirection) => - MockCameraSelector(), - createPreview: - (ResolutionSelector? resolutionSelector, int? targetRotation) => - Preview.detached( - initialTargetRotation: targetRotation, - resolutionSelector: resolutionSelector), - createImageCapture: - (ResolutionSelector? resolutionSelector, int? targetRotation) => - ImageCapture.detached( - resolutionSelector: resolutionSelector, - initialTargetRotation: targetRotation), - createRecorder: (QualitySelector? qualitySelector) => - Recorder.detached(qualitySelector: qualitySelector), - createVideoCapture: (_) => - Future.value(MockVideoCapture()), - createImageAnalysis: - (ResolutionSelector? resolutionSelector, int? targetRotation) => - ImageAnalysis.detached( - resolutionSelector: resolutionSelector, - initialTargetRotation: targetRotation), - createResolutionStrategy: ( - {bool highestAvailable = false, - Size? boundSize, - int? fallbackRule}) { - if (highestAvailable) { - return ResolutionStrategy.detachedHighestAvailableStrategy(); - } - return ResolutionStrategy.detached( - boundSize: boundSize, fallbackRule: fallbackRule); - }, - createResolutionSelector: (ResolutionStrategy resolutionStrategy, - ResolutionFilter? resolutionFilter, - AspectRatioStrategy? aspectRatioStrategy) => - ResolutionSelector.detached( - resolutionStrategy: resolutionStrategy, - resolutionFilter: resolutionFilter, - aspectRatioStrategy: aspectRatioStrategy), - createFallbackStrategy: ( - {required VideoQuality quality, - required VideoResolutionFallbackRule fallbackRule}) => - FallbackStrategy.detached( - quality: quality, fallbackRule: fallbackRule), - createQualitySelector: ( - {required VideoQuality videoQuality, - required FallbackStrategy fallbackStrategy}) => - QualitySelector.detached(qualityList: [ - VideoQualityData(quality: videoQuality) - ], fallbackStrategy: fallbackStrategy), - createCameraStateObserver: (_) => MockObserver(), - requestCameraPermissions: (_) => Future.value(), - startListeningForDeviceOrientationChange: (_, __) {}, - setPreviewSurfaceProvider: (_) => Future.value( - 3), // 3 is a random Flutter SurfaceTexture ID for testing, - createAspectRatioStrategy: (int aspectRatio, int fallbackRule) => - AspectRatioStrategy.detached( - preferredAspectRatio: aspectRatio, fallbackRule: fallbackRule), - createResolutionFilterWithOnePreferredSize: - (Size preferredResolution) => - ResolutionFilter.onePreferredSizeDetached( - preferredResolution: preferredResolution), - getCamera2CameraInfo: (_) => - Future.value(MockCamera2CameraInfo()), - getUiOrientation: () => - Future.value(DeviceOrientation.portraitUp), - previewSurfaceProducerHandlesCropAndRotation: (_) => - Future.value(false), - ); + MockProcessCameraProvider mockProcessCameraProvider, { + ResolutionFilter Function({ + required CameraSize preferredSize, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + })? createWithOnePreferredSizeResolutionFilter, + FallbackStrategy Function({ + required VideoQuality quality, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + })? lowerQualityOrHigherThanFallbackStrategy, + QualitySelector Function({ + required VideoQuality quality, + FallbackStrategy? fallbackStrategy, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + })? fromQualitySelector, + Preview Function({ + int? targetRotation, + ResolutionSelector? resolutionSelector, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + })? newPreview, + }) { + late final CameraXProxy proxy; + final AspectRatioStrategy ratio_4_3FallbackAutoStrategyAspectRatioStrategy = + MockAspectRatioStrategy(); + final ResolutionStrategy highestAvailableStrategyResolutionStrategy = + MockResolutionStrategy(); + proxy = CameraXProxy( + getInstanceProcessCameraProvider: ({ + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) async { + return mockProcessCameraProvider; + }, + newCameraSelector: ({ + LensFacing? requireLensFacing, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + switch (requireLensFacing) { + case LensFacing.front: + return MockCameraSelector(); + case LensFacing.back: + case LensFacing.external: + case LensFacing.unknown: + case null: + } + + return MockCameraSelector(); + }, + newPreview: newPreview ?? + ({ + int? targetRotation, + ResolutionSelector? resolutionSelector, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockPreview mockPreview = MockPreview(); + when( + mockPreview.surfaceProducerHandlesCropAndRotation(), + ).thenAnswer((_) async => false); + when(mockPreview.resolutionSelector).thenReturn(resolutionSelector); + return mockPreview; + }, + newImageCapture: ({ + int? targetRotation, + CameraXFlashMode? flashMode, + ResolutionSelector? resolutionSelector, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockImageCapture mockImageCapture = MockImageCapture(); + when( + mockImageCapture.resolutionSelector, + ).thenReturn(resolutionSelector); + return mockImageCapture; + }, + newRecorder: ({ + int? aspectRatio, + int? targetVideoEncodingBitRate, + QualitySelector? qualitySelector, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockRecorder mockRecorder = MockRecorder(); + when( + mockRecorder.getQualitySelector(), + ).thenAnswer((_) async => qualitySelector ?? MockQualitySelector()); + return mockRecorder; + }, + withOutputVideoCapture: ({ + required VideoOutput videoOutput, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockVideoCapture(); + }, + newImageAnalysis: ({ + int? targetRotation, + ResolutionSelector? resolutionSelector, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); + when( + mockImageAnalysis.resolutionSelector, + ).thenReturn(resolutionSelector); + return mockImageAnalysis; + }, + newResolutionStrategy: ({ + required CameraSize boundSize, + required ResolutionStrategyFallbackRule fallbackRule, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockResolutionStrategy resolutionStrategy = + MockResolutionStrategy(); + when( + resolutionStrategy.getBoundSize(), + ).thenAnswer((_) async => boundSize); + when( + resolutionStrategy.getFallbackRule(), + ).thenAnswer((_) async => fallbackRule); + return resolutionStrategy; + }, + newResolutionSelector: ({ + AspectRatioStrategy? aspectRatioStrategy, + ResolutionStrategy? resolutionStrategy, + ResolutionFilter? resolutionFilter, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockResolutionSelector mockResolutionSelector = + MockResolutionSelector(); + when(mockResolutionSelector.getAspectRatioStrategy()).thenAnswer( + (_) async => + aspectRatioStrategy ?? + proxy.ratio_4_3FallbackAutoStrategyAspectRatioStrategy(), + ); + when( + mockResolutionSelector.resolutionStrategy, + ).thenReturn(resolutionStrategy); + when( + mockResolutionSelector.resolutionFilter, + ).thenReturn(resolutionFilter); + return mockResolutionSelector; + }, + fromQualitySelector: fromQualitySelector ?? + ({ + required VideoQuality quality, + FallbackStrategy? fallbackStrategy, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockQualitySelector(); + }, + newObserver: ({ + required void Function(Observer, T) onChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Observer.detached( + onChanged: onChanged, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + newSystemServicesManager: ({ + required void Function(SystemServicesManager, String) onCameraError, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockSystemServicesManager(); + }, + newDeviceOrientationManager: ({ + required void Function(DeviceOrientationManager, String) + onDeviceOrientationChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockDeviceOrientationManager manager = + MockDeviceOrientationManager(); + when(manager.getUiOrientation()).thenAnswer((_) async { + return 'PORTRAIT_UP'; + }); + return manager; + }, + newAspectRatioStrategy: ({ + required AspectRatio preferredAspectRatio, + required AspectRatioStrategyFallbackRule fallbackRule, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockAspectRatioStrategy mockAspectRatioStrategy = + MockAspectRatioStrategy(); + when( + mockAspectRatioStrategy.getFallbackRule(), + ).thenAnswer((_) async => fallbackRule); + when( + mockAspectRatioStrategy.getPreferredAspectRatio(), + ).thenAnswer((_) async => preferredAspectRatio); + return mockAspectRatioStrategy; + }, + createWithOnePreferredSizeResolutionFilter: + createWithOnePreferredSizeResolutionFilter ?? + ({ + required CameraSize preferredSize, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockResolutionFilter(); + }, + fromCamera2CameraInfo: ({ + required CameraInfo cameraInfo, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockCamera2CameraInfo camera2cameraInfo = MockCamera2CameraInfo(); + when( + camera2cameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => 90); + return camera2cameraInfo; + }, + newCameraSize: ({ + required int width, + required int height, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return CameraSize.pigeon_detached( + width: width, + height: height, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + sensorOrientationCameraCharacteristics: () { + return MockCameraCharacteristicsKey(); + }, + lowerQualityOrHigherThanFallbackStrategy: + lowerQualityOrHigherThanFallbackStrategy ?? + ({ + required VideoQuality quality, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockFallbackStrategy(); + }, + highestAvailableStrategyResolutionStrategy: () { + return highestAvailableStrategyResolutionStrategy; + }, + ratio_4_3FallbackAutoStrategyAspectRatioStrategy: () => + ratio_4_3FallbackAutoStrategyAspectRatioStrategy, + lowerQualityThanFallbackStrategy: ({ + required VideoQuality quality, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockFallbackStrategy(); + }, + ); + + return proxy; + } /// CameraXProxy for testing exposure and focus related controls. /// /// Modifies the creation of [MeteringPoint]s and [FocusMeteringAction]s to /// return objects detached from a native object. - CameraXProxy getProxyForExposureAndFocus() => CameraXProxy( - createMeteringPoint: - (double x, double y, double? size, CameraInfo cameraInfo) => - MeteringPoint.detached( - x: x, y: y, size: size, cameraInfo: cameraInfo), - createFocusMeteringAction: - (List<(MeteringPoint, int?)> meteringPointInfos, - bool? disableAutoCancel) => - FocusMeteringAction.detached( - meteringPointInfos: meteringPointInfos, - disableAutoCancel: disableAutoCancel), + CameraXProxy getProxyForExposureAndFocus({ + FocusMeteringActionBuilder Function({ + required MeteringPoint point, + required MeteringMode mode, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + })? withModeFocusMeteringActionBuilder, + DisplayOrientedMeteringPointFactory Function({ + required CameraInfo cameraInfo, + required double width, + required double height, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + })? newDisplayOrientedMeteringPointFactory, + }) => + CameraXProxy( + newDisplayOrientedMeteringPointFactory: + newDisplayOrientedMeteringPointFactory ?? + ({ + required CameraInfo cameraInfo, + required double width, + required double height, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockDisplayOrientedMeteringPointFactory mockFactory = + MockDisplayOrientedMeteringPointFactory(); + when(mockFactory.createPoint(any, any)).thenAnswer( + (Invocation invocation) async => TestMeteringPoint.detached( + x: invocation.positionalArguments[0]! as double, + y: invocation.positionalArguments[1]! as double, + ), + ); + when(mockFactory.createPointWithSize(any, any, any)) + .thenAnswer( + (Invocation invocation) async => TestMeteringPoint.detached( + x: invocation.positionalArguments[0]! as double, + y: invocation.positionalArguments[1]! as double, + size: invocation.positionalArguments[2]! as double, + ), + ); + return mockFactory; + }, + withModeFocusMeteringActionBuilder: + withModeFocusMeteringActionBuilder ?? + ({ + required MeteringPoint point, + required MeteringMode mode, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final PigeonInstanceManager testInstanceManager = + PigeonInstanceManager(onWeakReferenceRemoved: (_) {}); + final MockFocusMeteringActionBuilder mockBuilder = + MockFocusMeteringActionBuilder(); + bool disableAutoCancelCalled = false; + when(mockBuilder.disableAutoCancel()).thenAnswer((_) async { + disableAutoCancelCalled = true; + }); + final List meteringPointsAe = + []; + final List meteringPointsAf = + []; + final List meteringPointsAwb = + []; + + switch (mode) { + case MeteringMode.ae: + meteringPointsAe.add(point); + case MeteringMode.af: + meteringPointsAf.add(point); + case MeteringMode.awb: + meteringPointsAwb.add(point); + } + + when(mockBuilder.addPointWithMode(any, any)).thenAnswer(( + Invocation invocation, + ) async { + switch (invocation.positionalArguments[1]) { + case MeteringMode.ae: + meteringPointsAe.add( + invocation.positionalArguments.first as MeteringPoint, + ); + case MeteringMode.af: + meteringPointsAf.add( + invocation.positionalArguments.first as MeteringPoint, + ); + case MeteringMode.awb: + meteringPointsAwb.add( + invocation.positionalArguments.first as MeteringPoint, + ); + } + }); + + when(mockBuilder.build()).thenAnswer( + (_) async => FocusMeteringAction.pigeon_detached( + meteringPointsAe: meteringPointsAe, + meteringPointsAf: meteringPointsAf, + meteringPointsAwb: meteringPointsAwb, + isAutoCancelEnabled: !disableAutoCancelCalled, + pigeon_instanceManager: testInstanceManager, + ), + ); + return mockBuilder; + }, ); /// CameraXProxy for testing setting focus and exposure points. @@ -228,191 +556,450 @@ void main() { /// interaction with expected [cameraControl] instance and modifies creation /// of [CaptureRequestOptions] to return objects detached from a native object. CameraXProxy getProxyForSettingFocusandExposurePoints( - CameraControl cameraControlForComparison, - Camera2CameraControl camera2cameraControl) { + CameraControl cameraControlForComparison, + Camera2CameraControl camera2cameraControl, { + FocusMeteringActionBuilder Function({ + required MeteringPoint point, + required MeteringMode mode, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + })? withModeFocusMeteringActionBuilder, + DisplayOrientedMeteringPointFactory Function({ + required CameraInfo cameraInfo, + required double width, + required double height, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + })? newDisplayOrientedMeteringPointFactory, + }) { final CameraXProxy proxy = getProxyForExposureAndFocus(); - proxy.getCamera2CameraControl = (CameraControl cameraControl) => + final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); + if (withModeFocusMeteringActionBuilder != null) { + proxy.withModeFocusMeteringActionBuilder = + withModeFocusMeteringActionBuilder; + } + if (newDisplayOrientedMeteringPointFactory != null) { + proxy.newDisplayOrientedMeteringPointFactory = + newDisplayOrientedMeteringPointFactory; + } + proxy.fromCamera2CameraControl = ({ + required CameraControl cameraControl, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => cameraControl == cameraControlForComparison ? camera2cameraControl - : Camera2CameraControl.detached(cameraControl: cameraControl); - - proxy.createCaptureRequestOptions = - (List<(CaptureRequestKeySupportedType, Object?)> options) => - CaptureRequestOptions.detached(requestedOptions: options); + : Camera2CameraControl.pigeon_detached( + pigeon_instanceManager: testInstanceManager, + ); + proxy.newCaptureRequestOptions = ({ + required Map options, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockCaptureRequestOptions mockCaptureRequestOptions = + MockCaptureRequestOptions(); + options.forEach((CaptureRequestKey key, Object? value) { + when( + mockCaptureRequestOptions.getCaptureRequestOption(key), + ).thenAnswer((_) async => value); + }); + return mockCaptureRequestOptions; + }; + final CaptureRequestKey controlAeLock = CaptureRequestKey.pigeon_detached( + pigeon_instanceManager: testInstanceManager, + ); + proxy.controlAELockCaptureRequest = () => controlAeLock; return proxy; } - test('Should fetch CameraDescription instances for available cameras', - () async { - // Arrange - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final List returnData = [ - { - 'name': 'Camera 0', - 'lensFacing': 'back', - 'sensorOrientation': 0 - }, - { - 'name': 'Camera 1', - 'lensFacing': 'front', - 'sensorOrientation': 90 - } - ]; + test( + 'Should fetch CameraDescription instances for available cameras', + () async { + // Arrange + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final List returnData = [ + { + 'name': 'Camera 0', + 'lensFacing': 'back', + 'sensorOrientation': 0, + }, + { + 'name': 'Camera 1', + 'lensFacing': 'front', + 'sensorOrientation': 90, + }, + ]; - // Create mocks to use - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockCameraSelector mockFrontCameraSelector = MockCameraSelector(); - final MockCameraSelector mockBackCameraSelector = MockCameraSelector(); - final MockCameraInfo mockFrontCameraInfo = MockCameraInfo(); - final MockCameraInfo mockBackCameraInfo = MockCameraInfo(); + // Create mocks to use + final MockProcessCameraProvider mockProcessCameraProvider = + MockProcessCameraProvider(); + final MockCameraSelector mockFrontCameraSelector = MockCameraSelector(); + final MockCameraSelector mockBackCameraSelector = MockCameraSelector(); + final MockCameraInfo mockFrontCameraInfo = MockCameraInfo(); + final MockCameraInfo mockBackCameraInfo = MockCameraInfo(); - // Tell plugin to create mock CameraSelectors for testing. - camera.proxy = CameraXProxy( - getProcessCameraProvider: () => - Future.value(mockProcessCameraProvider), - createCameraSelector: (int cameraSelectorLensDirection) { - switch (cameraSelectorLensDirection) { - case CameraSelector.lensFacingFront: - return mockFrontCameraSelector; - case CameraSelector.lensFacingBack: - default: - return mockBackCameraSelector; - } - }, - ); + // Tell plugin to create mock CameraSelectors for testing. + camera.proxy = CameraXProxy( + setUpGenericsProxy: ({ + BinaryMessenger? pigeonBinaryMessenger, + PigeonInstanceManager? pigeonInstanceManager, + }) {}, + getInstanceProcessCameraProvider: ({ + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + Future.value(mockProcessCameraProvider), + newCameraSelector: ({ + LensFacing? requireLensFacing, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + switch (requireLensFacing) { + case LensFacing.front: + return mockFrontCameraSelector; + case LensFacing.back: + case LensFacing.external: + case LensFacing.unknown: + case null: + } - // Mock calls to native platform - when(mockProcessCameraProvider.getAvailableCameraInfos()).thenAnswer( - (_) async => [mockBackCameraInfo, mockFrontCameraInfo]); - when(mockBackCameraSelector.filter([mockFrontCameraInfo])) - .thenAnswer((_) async => []); - when(mockBackCameraSelector.filter([mockBackCameraInfo])) - .thenAnswer((_) async => [mockBackCameraInfo]); - when(mockFrontCameraSelector.filter([mockBackCameraInfo])) - .thenAnswer((_) async => []); - when(mockFrontCameraSelector.filter([mockFrontCameraInfo])) - .thenAnswer((_) async => [mockFrontCameraInfo]); - when(mockBackCameraInfo.getSensorRotationDegrees()) - .thenAnswer((_) async => 0); - when(mockFrontCameraInfo.getSensorRotationDegrees()) - .thenAnswer((_) async => 90); - - final List cameraDescriptions = - await camera.availableCameras(); - - expect(cameraDescriptions.length, returnData.length); - for (int i = 0; i < returnData.length; i++) { - final Map typedData = - (returnData[i] as Map).cast(); - final CameraDescription cameraDescription = CameraDescription( - name: typedData['name']! as String, - lensDirection: (typedData['lensFacing']! as String) == 'front' - ? CameraLensDirection.front - : CameraLensDirection.back, - sensorOrientation: typedData['sensorOrientation']! as int, - ); - expect(cameraDescriptions[i], cameraDescription); - } - }); + return mockBackCameraSelector; + }, + newSystemServicesManager: ({ + required void Function(SystemServicesManager, String) onCameraError, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockSystemServicesManager(); + }, + ); + + // Mock calls to native platform + when(mockProcessCameraProvider.getAvailableCameraInfos()).thenAnswer( + (_) async => [mockBackCameraInfo, mockFrontCameraInfo], + ); + when( + mockBackCameraSelector.filter([mockFrontCameraInfo]), + ).thenAnswer((_) async => []); + when( + mockBackCameraSelector.filter([mockBackCameraInfo]), + ).thenAnswer((_) async => [mockBackCameraInfo]); + when( + mockFrontCameraSelector.filter([mockBackCameraInfo]), + ).thenAnswer((_) async => []); + when( + mockFrontCameraSelector.filter([mockFrontCameraInfo]), + ).thenAnswer((_) async => [mockFrontCameraInfo]); + when(mockBackCameraInfo.sensorRotationDegrees).thenReturn(0); + when(mockFrontCameraInfo.sensorRotationDegrees).thenReturn(90); + + final List cameraDescriptions = + await camera.availableCameras(); + + expect(cameraDescriptions.length, returnData.length); + for (int i = 0; i < returnData.length; i++) { + final Map typedData = + (returnData[i] as Map).cast(); + final CameraDescription cameraDescription = CameraDescription( + name: typedData['name']! as String, + lensDirection: (typedData['lensFacing']! as String) == 'front' + ? CameraLensDirection.front + : CameraLensDirection.back, + sensorOrientation: typedData['sensorOrientation']! as int, + ); + expect(cameraDescriptions[i], cameraDescription); + } + }, + ); test( - 'createCamera requests permissions, starts listening for device orientation changes, updates camera state observers, and returns flutter surface texture ID', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const CameraLensDirection testLensDirection = CameraLensDirection.back; - const int testSensorOrientation = 90; - const CameraDescription testCameraDescription = CameraDescription( + 'createCamera requests permissions, starts listening for device orientation changes, updates camera state observers, and returns flutter surface texture ID', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const CameraLensDirection testLensDirection = CameraLensDirection.back; + const int testSensorOrientation = 90; + const CameraDescription testCameraDescription = CameraDescription( name: 'cameraName', lensDirection: testLensDirection, - sensorOrientation: testSensorOrientation); + sensorOrientation: testSensorOrientation, + ); - const int testSurfaceTextureId = 6; + const int testSurfaceTextureId = 6; - // Mock/Detached objects for (typically attached) objects created by - // createCamera. - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockPreview mockPreview = MockPreview(); - final MockCameraSelector mockBackCameraSelector = MockCameraSelector(); - final MockImageCapture mockImageCapture = MockImageCapture(); - final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); - final MockRecorder mockRecorder = MockRecorder(); - final MockVideoCapture mockVideoCapture = MockVideoCapture(); - final MockCamera mockCamera = MockCamera(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final MockLiveCameraState mockLiveCameraState = MockLiveCameraState(); - final TestSystemServicesHostApi mockSystemServicesApi = - MockTestSystemServicesHostApi(); - TestSystemServicesHostApi.setup(mockSystemServicesApi); + // Mock/Detached objects for (typically attached) objects created by + // createCamera. + final MockProcessCameraProvider mockProcessCameraProvider = + MockProcessCameraProvider(); + final MockPreview mockPreview = MockPreview(); + final MockCameraSelector mockBackCameraSelector = MockCameraSelector(); + final MockImageCapture mockImageCapture = MockImageCapture(); + final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); + final MockRecorder mockRecorder = MockRecorder(); + final MockVideoCapture mockVideoCapture = MockVideoCapture(); + final MockCamera mockCamera = MockCamera(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final MockLiveCameraState mockLiveCameraState = MockLiveCameraState(); + final MockSystemServicesManager mockSystemServicesManager = + MockSystemServicesManager(); + final MockCameraCharacteristicsKey mockCameraCharacteristicsKey = + MockCameraCharacteristicsKey(); - bool cameraPermissionsRequested = false; - bool startedListeningForDeviceOrientationChanges = false; + bool cameraPermissionsRequested = false; + bool startedListeningForDeviceOrientationChanges = false; - // Tell plugin to create mock/detached objects and stub method calls for the - // testing of createCamera. - camera.proxy = CameraXProxy( - getProcessCameraProvider: () => - Future.value(mockProcessCameraProvider), - createCameraSelector: (int cameraSelectorLensDirection) { - switch (cameraSelectorLensDirection) { - case CameraSelector.lensFacingFront: - return MockCameraSelector(); - case CameraSelector.lensFacingBack: - default: - return mockBackCameraSelector; - } - }, - createPreview: (_, __) => mockPreview, - createImageCapture: (_, __) => mockImageCapture, - createRecorder: (_) => mockRecorder, - createVideoCapture: (_) => Future.value(mockVideoCapture), - createImageAnalysis: (_, __) => mockImageAnalysis, - createResolutionStrategy: ( - {bool highestAvailable = false, - Size? boundSize, - int? fallbackRule}) => - MockResolutionStrategy(), - createResolutionSelector: (_, __, ___) => MockResolutionSelector(), - createFallbackStrategy: ( - {required VideoQuality quality, - required VideoResolutionFallbackRule fallbackRule}) => - MockFallbackStrategy(), - createQualitySelector: ( - {required VideoQuality videoQuality, - required FallbackStrategy fallbackStrategy}) => - MockQualitySelector(), - createCameraStateObserver: (void Function(Object) onChanged) => - Observer.detached(onChanged: onChanged), - requestCameraPermissions: (_) { - cameraPermissionsRequested = true; - return Future.value(); - }, - startListeningForDeviceOrientationChange: (_, __) { - startedListeningForDeviceOrientationChanges = true; - }, - createAspectRatioStrategy: (_, __) => MockAspectRatioStrategy(), - createResolutionFilterWithOnePreferredSize: (_) => MockResolutionFilter(), - getCamera2CameraInfo: (_) => - Future.value(MockCamera2CameraInfo()), - getUiOrientation: () => - Future.value(DeviceOrientation.portraitUp), - ); + camera.proxy = CameraXProxy( + getInstanceProcessCameraProvider: ({ + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) async { + return mockProcessCameraProvider; + }, + newCameraSelector: ({ + LensFacing? requireLensFacing, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + switch (requireLensFacing) { + case LensFacing.front: + return MockCameraSelector(); + case LensFacing.back: + case LensFacing.external: + case LensFacing.unknown: + case null: + } + + return mockBackCameraSelector; + }, + newPreview: ({ + int? targetRotation, + ResolutionSelector? resolutionSelector, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return mockPreview; + }, + newImageCapture: ({ + int? targetRotation, + CameraXFlashMode? flashMode, + ResolutionSelector? resolutionSelector, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return mockImageCapture; + }, + newRecorder: ({ + int? aspectRatio, + int? targetVideoEncodingBitRate, + QualitySelector? qualitySelector, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return mockRecorder; + }, + withOutputVideoCapture: ({ + required VideoOutput videoOutput, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return mockVideoCapture; + }, + newImageAnalysis: ({ + int? targetRotation, + ResolutionSelector? resolutionSelector, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return mockImageAnalysis; + }, + newResolutionStrategy: ({ + required CameraSize boundSize, + required ResolutionStrategyFallbackRule fallbackRule, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockResolutionStrategy(); + }, + newResolutionSelector: ({ + AspectRatioStrategy? aspectRatioStrategy, + ResolutionStrategy? resolutionStrategy, + ResolutionFilter? resolutionFilter, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockResolutionSelector(); + }, + fromQualitySelector: ({ + required VideoQuality quality, + FallbackStrategy? fallbackStrategy, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockQualitySelector(); + }, + newObserver: ({ + required void Function(Observer, T) onChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Observer.detached( + onChanged: onChanged, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + newSystemServicesManager: ({ + required void Function(SystemServicesManager, String) onCameraError, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + when( + mockSystemServicesManager.requestCameraPermissions(any), + ).thenAnswer((_) async { + cameraPermissionsRequested = true; + return null; + }); + return mockSystemServicesManager; + }, + newDeviceOrientationManager: ({ + required void Function(DeviceOrientationManager, String) + onDeviceOrientationChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockDeviceOrientationManager manager = + MockDeviceOrientationManager(); + when(manager.startListeningForDeviceOrientationChange()).thenAnswer(( + _, + ) async { + startedListeningForDeviceOrientationChanges = true; + }); + when(manager.getUiOrientation()).thenAnswer((_) async { + return 'PORTRAIT_UP'; + }); + return manager; + }, + newAspectRatioStrategy: ({ + required AspectRatio preferredAspectRatio, + required AspectRatioStrategyFallbackRule fallbackRule, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockAspectRatioStrategy(); + }, + createWithOnePreferredSizeResolutionFilter: ({ + required CameraSize preferredSize, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockResolutionFilter(); + }, + fromCamera2CameraInfo: ({ + required CameraInfo cameraInfo, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockCamera2CameraInfo camera2cameraInfo = + MockCamera2CameraInfo(); + when( + camera2cameraInfo.getCameraCharacteristic( + mockCameraCharacteristicsKey, + ), + ).thenAnswer((_) async => testSensorOrientation); + return camera2cameraInfo; + }, + newCameraSize: ({ + required int width, + required int height, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockCameraSize(); + }, + sensorOrientationCameraCharacteristics: () { + return mockCameraCharacteristicsKey; + }, + lowerQualityOrHigherThanFallbackStrategy: ({ + required VideoQuality quality, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockFallbackStrategy(); + }, + ); - camera.processCameraProvider = mockProcessCameraProvider; + camera.processCameraProvider = mockProcessCameraProvider; - when(mockPreview.setSurfaceProvider()) - .thenAnswer((_) async => testSurfaceTextureId); - when(mockProcessCameraProvider.bindToLifecycle(mockBackCameraSelector, - [mockPreview, mockImageCapture, mockImageAnalysis])) - .thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => mockLiveCameraState); + when( + mockPreview.setSurfaceProvider(mockSystemServicesManager), + ).thenAnswer((_) async => testSurfaceTextureId); + when( + mockProcessCameraProvider.bindToLifecycle( + mockBackCameraSelector, + [mockPreview, mockImageCapture, mockImageAnalysis], + ), + ).thenAnswer((_) async => mockCamera); + when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => mockLiveCameraState); - expect( + expect( await camera.createCameraWithSettings( testCameraDescription, const MediaSettings( @@ -423,128 +1010,295 @@ void main() { enableAudio: true, ), ), - equals(testSurfaceTextureId)); + equals(testSurfaceTextureId), + ); - // Verify permissions are requested and the camera starts listening for device orientation changes. - expect(cameraPermissionsRequested, isTrue); - expect(startedListeningForDeviceOrientationChanges, isTrue); + // Verify permissions are requested and the camera starts listening for device orientation changes. + expect(cameraPermissionsRequested, isTrue); + expect(startedListeningForDeviceOrientationChanges, isTrue); - // Verify CameraSelector is set with appropriate lens direction. - expect(camera.cameraSelector, equals(mockBackCameraSelector)); + // Verify CameraSelector is set with appropriate lens direction. + expect(camera.cameraSelector, equals(mockBackCameraSelector)); - // Verify the camera's Preview instance is instantiated properly. - expect(camera.preview, equals(mockPreview)); + // Verify the camera's Preview instance is instantiated properly. + expect(camera.preview, equals(mockPreview)); - // Verify the camera's ImageCapture instance is instantiated properly. - expect(camera.imageCapture, equals(mockImageCapture)); + // Verify the camera's ImageCapture instance is instantiated properly. + expect(camera.imageCapture, equals(mockImageCapture)); - // Verify the camera's Recorder and VideoCapture instances are instantiated properly. - expect(camera.recorder, equals(mockRecorder)); - expect(camera.videoCapture, equals(mockVideoCapture)); + // Verify the camera's Recorder and VideoCapture instances are instantiated properly. + expect(camera.recorder, equals(mockRecorder)); + expect(camera.videoCapture, equals(mockVideoCapture)); - // Verify the camera's Preview instance has its surface provider set. - verify(camera.preview!.setSurfaceProvider()); + // Verify the camera's Preview instance has its surface provider set. + verify(camera.preview!.setSurfaceProvider(mockSystemServicesManager)); - // Verify the camera state observer is updated. - expect( + // Verify the camera state observer is updated. + expect( await testCameraClosingObserver( - camera, - testSurfaceTextureId, - verify(mockLiveCameraState.observe(captureAny)).captured.single - as Observer), - isTrue); - }); + camera, + testSurfaceTextureId, + verify(mockLiveCameraState.observe(captureAny)).captured.single + as Observer, + ), + isTrue, + ); + }, + ); test( - 'createCamera binds Preview and ImageCapture use cases to ProcessCameraProvider instance', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const CameraLensDirection testLensDirection = CameraLensDirection.back; - const int testSensorOrientation = 90; - const CameraDescription testCameraDescription = CameraDescription( + 'createCamera binds Preview and ImageCapture use cases to ProcessCameraProvider instance', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const CameraLensDirection testLensDirection = CameraLensDirection.back; + const int testSensorOrientation = 90; + const CameraDescription testCameraDescription = CameraDescription( name: 'cameraName', lensDirection: testLensDirection, - sensorOrientation: testSensorOrientation); - const ResolutionPreset testResolutionPreset = ResolutionPreset.veryHigh; - const bool enableAudio = true; + sensorOrientation: testSensorOrientation, + ); + const ResolutionPreset testResolutionPreset = ResolutionPreset.veryHigh; + const bool enableAudio = true; - // Mock/Detached objects for (typically attached) objects created by - // createCamera. - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockPreview mockPreview = MockPreview(); - final MockCameraSelector mockBackCameraSelector = MockCameraSelector(); - final MockImageCapture mockImageCapture = MockImageCapture(); - final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); - final MockRecorder mockRecorder = MockRecorder(); - final MockVideoCapture mockVideoCapture = MockVideoCapture(); - final MockCamera mockCamera = MockCamera(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final MockCameraControl mockCameraControl = MockCameraControl(); - final MockCamera2CameraInfo mockCamera2CameraInfo = MockCamera2CameraInfo(); - final TestSystemServicesHostApi mockSystemServicesApi = - MockTestSystemServicesHostApi(); - TestSystemServicesHostApi.setup(mockSystemServicesApi); + // Mock/Detached objects for (typically attached) objects created by + // createCamera. + final MockProcessCameraProvider mockProcessCameraProvider = + MockProcessCameraProvider(); + final MockPreview mockPreview = MockPreview(); + final MockCameraSelector mockBackCameraSelector = MockCameraSelector(); + final MockImageCapture mockImageCapture = MockImageCapture(); + final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); + final MockRecorder mockRecorder = MockRecorder(); + final MockVideoCapture mockVideoCapture = MockVideoCapture(); + final MockCamera mockCamera = MockCamera(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final MockCameraControl mockCameraControl = MockCameraControl(); + final MockCamera2CameraInfo mockCamera2CameraInfo = + MockCamera2CameraInfo(); + final MockCameraCharacteristicsKey mockCameraCharacteristicsKey = + MockCameraCharacteristicsKey(); - // Tell plugin to create mock/detached objects and stub method calls for the - // testing of createCamera. - camera.proxy = CameraXProxy( - getProcessCameraProvider: () => - Future.value(mockProcessCameraProvider), - createCameraSelector: (int cameraSelectorLensDirection) { - switch (cameraSelectorLensDirection) { - case CameraSelector.lensFacingFront: - return MockCameraSelector(); - case CameraSelector.lensFacingBack: - default: - return mockBackCameraSelector; - } - }, - createPreview: (_, __) => mockPreview, - createImageCapture: (_, __) => mockImageCapture, - createRecorder: (_) => mockRecorder, - createVideoCapture: (_) => Future.value(mockVideoCapture), - createImageAnalysis: (_, __) => mockImageAnalysis, - createResolutionStrategy: ( - {bool highestAvailable = false, - Size? boundSize, - int? fallbackRule}) => - MockResolutionStrategy(), - createResolutionSelector: (_, __, ___) => MockResolutionSelector(), - createFallbackStrategy: ( - {required VideoQuality quality, - required VideoResolutionFallbackRule fallbackRule}) => - MockFallbackStrategy(), - createQualitySelector: ( - {required VideoQuality videoQuality, - required FallbackStrategy fallbackStrategy}) => - MockQualitySelector(), - createCameraStateObserver: (void Function(Object) onChanged) => - Observer.detached(onChanged: onChanged), - requestCameraPermissions: (_) => Future.value(), - startListeningForDeviceOrientationChange: (_, __) {}, - createAspectRatioStrategy: (_, __) => MockAspectRatioStrategy(), - createResolutionFilterWithOnePreferredSize: (_) => MockResolutionFilter(), - getCamera2CameraInfo: (CameraInfo cameraInfo) => - cameraInfo == mockCameraInfo - ? Future.value(mockCamera2CameraInfo) - : Future.value(MockCamera2CameraInfo()), - getUiOrientation: () => - Future.value(DeviceOrientation.portraitUp), - ); + // Tell plugin to create mock/detached objects and stub method calls for the + // testing of createCamera. + camera.proxy = CameraXProxy( + getInstanceProcessCameraProvider: ({ + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) async { + return mockProcessCameraProvider; + }, + newCameraSelector: ({ + LensFacing? requireLensFacing, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + switch (requireLensFacing) { + case LensFacing.front: + return MockCameraSelector(); + case LensFacing.back: + case LensFacing.external: + case LensFacing.unknown: + case null: + } - when(mockProcessCameraProvider.bindToLifecycle(mockBackCameraSelector, - [mockPreview, mockImageCapture, mockImageAnalysis])) - .thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => MockLiveCameraState()); - when(mockCamera.getCameraControl()) - .thenAnswer((_) async => mockCameraControl); + return mockBackCameraSelector; + }, + newPreview: ({ + int? targetRotation, + ResolutionSelector? resolutionSelector, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return mockPreview; + }, + newImageCapture: ({ + int? targetRotation, + CameraXFlashMode? flashMode, + ResolutionSelector? resolutionSelector, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return mockImageCapture; + }, + newRecorder: ({ + int? aspectRatio, + int? targetVideoEncodingBitRate, + QualitySelector? qualitySelector, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return mockRecorder; + }, + withOutputVideoCapture: ({ + required VideoOutput videoOutput, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return mockVideoCapture; + }, + newImageAnalysis: ({ + int? targetRotation, + ResolutionSelector? resolutionSelector, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return mockImageAnalysis; + }, + newResolutionStrategy: ({ + required CameraSize boundSize, + required ResolutionStrategyFallbackRule fallbackRule, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockResolutionStrategy(); + }, + newResolutionSelector: ({ + AspectRatioStrategy? aspectRatioStrategy, + ResolutionStrategy? resolutionStrategy, + ResolutionFilter? resolutionFilter, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockResolutionSelector(); + }, + fromQualitySelector: ({ + required VideoQuality quality, + FallbackStrategy? fallbackStrategy, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockQualitySelector(); + }, + newObserver: ({ + required void Function(Observer, T) onChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Observer.detached( + onChanged: onChanged, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + newSystemServicesManager: ({ + required void Function(SystemServicesManager, String) onCameraError, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockSystemServicesManager(); + }, + newDeviceOrientationManager: ({ + required void Function(DeviceOrientationManager, String) + onDeviceOrientationChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockDeviceOrientationManager manager = + MockDeviceOrientationManager(); + when(manager.getUiOrientation()).thenAnswer((_) async { + return 'PORTRAIT_UP'; + }); + return manager; + }, + newAspectRatioStrategy: ({ + required AspectRatio preferredAspectRatio, + required AspectRatioStrategyFallbackRule fallbackRule, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockAspectRatioStrategy(); + }, + createWithOnePreferredSizeResolutionFilter: ({ + required CameraSize preferredSize, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockResolutionFilter(); + }, + fromCamera2CameraInfo: ({ + required CameraInfo cameraInfo, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + when( + mockCamera2CameraInfo.getCameraCharacteristic( + mockCameraCharacteristicsKey, + ), + ).thenAnswer((_) async => testSensorOrientation); + return mockCamera2CameraInfo; + }, + newCameraSize: ({ + required int width, + required int height, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockCameraSize(); + }, + sensorOrientationCameraCharacteristics: () { + return mockCameraCharacteristicsKey; + }, + lowerQualityOrHigherThanFallbackStrategy: ({ + required VideoQuality quality, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockFallbackStrategy(); + }, + ); - camera.processCameraProvider = mockProcessCameraProvider; + when( + mockProcessCameraProvider.bindToLifecycle( + mockBackCameraSelector, + [mockPreview, mockImageCapture, mockImageAnalysis], + ), + ).thenAnswer((_) async => mockCamera); + when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => MockLiveCameraState()); + when(mockCamera.cameraControl).thenAnswer((_) => mockCameraControl); - await camera.createCameraWithSettings( + camera.processCameraProvider = mockProcessCameraProvider; + + await camera.createCameraWithSettings( testCameraDescription, const MediaSettings( resolutionPreset: testResolutionPreset, @@ -552,432 +1306,627 @@ void main() { videoBitrate: 2000000, audioBitrate: 64000, enableAudio: enableAudio, - )); + ), + ); - // Verify expected UseCases were bound. - verify(camera.processCameraProvider!.bindToLifecycle(camera.cameraSelector!, - [mockPreview, mockImageCapture, mockImageAnalysis])); + // Verify expected UseCases were bound. + verify( + camera.processCameraProvider!.bindToLifecycle( + camera.cameraSelector!, + [mockPreview, mockImageCapture, mockImageAnalysis], + ), + ); - // Verify the camera's CameraInfo instance got updated. - expect(camera.cameraInfo, equals(mockCameraInfo)); + // Verify the camera's CameraInfo instance got updated. + expect(camera.cameraInfo, equals(mockCameraInfo)); - // Verify camera's CameraControl instance got updated. - expect(camera.cameraControl, equals(mockCameraControl)); + // Verify camera's CameraControl instance got updated. + expect(camera.cameraControl, equals(mockCameraControl)); - // Verify preview has been marked as bound to the camera lifecycle by - // createCamera. - expect(camera.previewInitiallyBound, isTrue); - }); + // Verify preview has been marked as bound to the camera lifecycle by + // createCamera. + expect(camera.previewInitiallyBound, isTrue); + }, + ); test( - 'createCamera properly sets preset resolution selection strategy for non-video capture use cases', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const CameraLensDirection testLensDirection = CameraLensDirection.back; - const int testSensorOrientation = 90; - const CameraDescription testCameraDescription = CameraDescription( + 'createCamera properly sets preset resolution selection strategy for non-video capture use cases', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const CameraLensDirection testLensDirection = CameraLensDirection.back; + const int testSensorOrientation = 90; + const CameraDescription testCameraDescription = CameraDescription( name: 'cameraName', lensDirection: testLensDirection, - sensorOrientation: testSensorOrientation); - const bool enableAudio = true; - final MockCamera mockCamera = MockCamera(); - - // Mock/Detached objects for (typically attached) objects created by - // createCamera. - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final TestSystemServicesHostApi mockSystemServicesApi = - MockTestSystemServicesHostApi(); - TestSystemServicesHostApi.setup(mockSystemServicesApi); + sensorOrientation: testSensorOrientation, + ); + const bool enableAudio = true; + final MockCamera mockCamera = MockCamera(); - // Tell plugin to create mock/detached objects for testing createCamera - // as needed. - camera.proxy = - getProxyForTestingResolutionPreset(mockProcessCameraProvider); + // Mock/Detached objects for (typically attached) objects created by + // createCamera. + final MockProcessCameraProvider mockProcessCameraProvider = + MockProcessCameraProvider(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); - when(mockProcessCameraProvider.bindToLifecycle(any, any)) - .thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => MockLiveCameraState()); - camera.processCameraProvider = mockProcessCameraProvider; + when( + mockProcessCameraProvider.bindToLifecycle(any, any), + ).thenAnswer((_) async => mockCamera); + when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => MockLiveCameraState()); + camera.processCameraProvider = mockProcessCameraProvider; - // Test non-null resolution presets. - for (final ResolutionPreset resolutionPreset in ResolutionPreset.values) { - await camera.createCamera( - testCameraDescription, - resolutionPreset, - enableAudio: enableAudio, + // Tell plugin to create mock/detached objects for testing createCamera + // as needed. + camera.proxy = getProxyForTestingResolutionPreset( + mockProcessCameraProvider, ); - Size? expectedBoundSize; - ResolutionStrategy? expectedResolutionStrategy; - switch (resolutionPreset) { - case ResolutionPreset.low: - expectedBoundSize = const Size(320, 240); - case ResolutionPreset.medium: - expectedBoundSize = const Size(720, 480); - case ResolutionPreset.high: - expectedBoundSize = const Size(1280, 720); - case ResolutionPreset.veryHigh: - expectedBoundSize = const Size(1920, 1080); - case ResolutionPreset.ultraHigh: - expectedBoundSize = const Size(3840, 2160); - case ResolutionPreset.max: - expectedResolutionStrategy = - ResolutionStrategy.detachedHighestAvailableStrategy(); + // Test non-null resolution presets. + for (final ResolutionPreset resolutionPreset in ResolutionPreset.values) { + await camera.createCamera( + testCameraDescription, + resolutionPreset, + enableAudio: enableAudio, + ); + + late final CameraSize? expectedBoundSize; + final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); + switch (resolutionPreset) { + case ResolutionPreset.low: + expectedBoundSize = CameraSize.pigeon_detached( + width: 320, + height: 240, + pigeon_instanceManager: testInstanceManager, + ); + case ResolutionPreset.medium: + expectedBoundSize = CameraSize.pigeon_detached( + width: 720, + height: 480, + pigeon_instanceManager: testInstanceManager, + ); + case ResolutionPreset.high: + expectedBoundSize = CameraSize.pigeon_detached( + width: 1280, + height: 720, + pigeon_instanceManager: testInstanceManager, + ); + case ResolutionPreset.veryHigh: + expectedBoundSize = CameraSize.pigeon_detached( + width: 1920, + height: 1080, + pigeon_instanceManager: testInstanceManager, + ); + case ResolutionPreset.ultraHigh: + expectedBoundSize = CameraSize.pigeon_detached( + width: 3840, + height: 2160, + pigeon_instanceManager: testInstanceManager, + ); + case ResolutionPreset.max: + continue; + } + + final CameraSize? previewSize = await camera + .preview!.resolutionSelector!.resolutionStrategy! + .getBoundSize(); + expect(previewSize?.width, equals(expectedBoundSize.width)); + expect(previewSize?.height, equals(expectedBoundSize.height)); + expect( + await camera.preview!.resolutionSelector!.resolutionStrategy! + .getFallbackRule(), + ResolutionStrategyFallbackRule.closestLowerThenHigher, + ); + + final CameraSize? imageCaptureSize = await camera + .imageCapture!.resolutionSelector!.resolutionStrategy! + .getBoundSize(); + expect(imageCaptureSize?.width, equals(expectedBoundSize.width)); + expect(imageCaptureSize?.height, equals(expectedBoundSize.height)); + expect( + await camera.imageCapture!.resolutionSelector!.resolutionStrategy! + .getFallbackRule(), + ResolutionStrategyFallbackRule.closestLowerThenHigher, + ); + + final CameraSize? imageAnalysisSize = await camera + .imageAnalysis!.resolutionSelector!.resolutionStrategy! + .getBoundSize(); + expect(imageAnalysisSize?.width, equals(expectedBoundSize.width)); + expect(imageAnalysisSize?.height, equals(expectedBoundSize.height)); + expect( + await camera.imageAnalysis!.resolutionSelector!.resolutionStrategy! + .getFallbackRule(), + ResolutionStrategyFallbackRule.closestLowerThenHigher, + ); } - // We expect the strategy to be the highest available or correspond to the - // expected bound size, with fallback to the closest and highest available - // resolution. - expectedResolutionStrategy ??= ResolutionStrategy.detached( - boundSize: expectedBoundSize, - fallbackRule: ResolutionStrategy.fallbackRuleClosestLowerThenHigher); + // Test max case. + await camera.createCamera( + testCameraDescription, + ResolutionPreset.max, + enableAudio: true, + ); - expect(camera.preview!.resolutionSelector!.resolutionStrategy!.boundSize, - equals(expectedResolutionStrategy.boundSize)); - expect( - camera - .imageCapture!.resolutionSelector!.resolutionStrategy!.boundSize, - equals(expectedResolutionStrategy.boundSize)); - expect( - camera - .imageAnalysis!.resolutionSelector!.resolutionStrategy!.boundSize, - equals(expectedResolutionStrategy.boundSize)); expect( - camera.preview!.resolutionSelector!.resolutionStrategy!.fallbackRule, - equals(expectedResolutionStrategy.fallbackRule)); + camera.preview!.resolutionSelector!.resolutionStrategy, + equals(camera.proxy.highestAvailableStrategyResolutionStrategy()), + ); expect( - camera.imageCapture!.resolutionSelector!.resolutionStrategy! - .fallbackRule, - equals(expectedResolutionStrategy.fallbackRule)); + camera.imageCapture!.resolutionSelector!.resolutionStrategy, + equals(camera.proxy.highestAvailableStrategyResolutionStrategy()), + ); expect( - camera.imageAnalysis!.resolutionSelector!.resolutionStrategy! - .fallbackRule, - equals(expectedResolutionStrategy.fallbackRule)); - } + camera.imageAnalysis!.resolutionSelector!.resolutionStrategy, + equals(camera.proxy.highestAvailableStrategyResolutionStrategy()), + ); - // Test null case. - await camera.createCamera(testCameraDescription, null); - expect(camera.preview!.resolutionSelector, isNull); - expect(camera.imageCapture!.resolutionSelector, isNull); - expect(camera.imageAnalysis!.resolutionSelector, isNull); - }); + // Test null case. + await camera.createCamera(testCameraDescription, null); + expect(camera.preview!.resolutionSelector, isNull); + expect(camera.imageCapture!.resolutionSelector, isNull); + expect(camera.imageAnalysis!.resolutionSelector, isNull); + }, + ); test( - 'createCamera properly sets filter for resolution preset for non-video capture use cases', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const CameraLensDirection testLensDirection = CameraLensDirection.front; - const int testSensorOrientation = 180; - const CameraDescription testCameraDescription = CameraDescription( + 'createCamera properly sets filter for resolution preset for non-video capture use cases', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const CameraLensDirection testLensDirection = CameraLensDirection.front; + const int testSensorOrientation = 180; + const CameraDescription testCameraDescription = CameraDescription( name: 'cameraName', lensDirection: testLensDirection, - sensorOrientation: testSensorOrientation); - const bool enableAudio = true; - final MockCamera mockCamera = MockCamera(); + sensorOrientation: testSensorOrientation, + ); + const bool enableAudio = true; + final MockCamera mockCamera = MockCamera(); - // Mock/Detached objects for (typically attached) objects created by - // createCamera. - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); + // Mock/Detached objects for (typically attached) objects created by + // createCamera. + final MockProcessCameraProvider mockProcessCameraProvider = + MockProcessCameraProvider(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); - // Tell plugin to create mock/detached objects for testing createCamera - // as needed. - camera.proxy = - getProxyForTestingResolutionPreset(mockProcessCameraProvider); + // Tell plugin to create mock/detached objects for testing createCamera + // as needed. + CameraSize? lastSetPreferredSize; + camera.proxy = getProxyForTestingResolutionPreset( + mockProcessCameraProvider, + createWithOnePreferredSizeResolutionFilter: ({ + required CameraSize preferredSize, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + lastSetPreferredSize = preferredSize; + return MockResolutionFilter(); + }, + ); - when(mockProcessCameraProvider.bindToLifecycle(any, any)) - .thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => MockLiveCameraState()); - camera.processCameraProvider = mockProcessCameraProvider; - - // Test non-null resolution presets. - for (final ResolutionPreset resolutionPreset in ResolutionPreset.values) { - await camera.createCamera(testCameraDescription, resolutionPreset, - enableAudio: enableAudio); - - Size? expectedPreferredResolution; - switch (resolutionPreset) { - case ResolutionPreset.low: - expectedPreferredResolution = const Size(320, 240); - case ResolutionPreset.medium: - expectedPreferredResolution = const Size(720, 480); - case ResolutionPreset.high: - expectedPreferredResolution = const Size(1280, 720); - case ResolutionPreset.veryHigh: - expectedPreferredResolution = const Size(1920, 1080); - case ResolutionPreset.ultraHigh: - expectedPreferredResolution = const Size(3840, 2160); - case ResolutionPreset.max: - expectedPreferredResolution = null; - } + when( + mockProcessCameraProvider.bindToLifecycle(any, any), + ).thenAnswer((_) async => mockCamera); + when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => MockLiveCameraState()); + camera.processCameraProvider = mockProcessCameraProvider; + + // Test non-null resolution presets. + for (final ResolutionPreset resolutionPreset in ResolutionPreset.values) { + await camera.createCamera( + testCameraDescription, + resolutionPreset, + enableAudio: enableAudio, + ); + + CameraSize? expectedPreferredResolution; + final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); + switch (resolutionPreset) { + case ResolutionPreset.low: + expectedPreferredResolution = CameraSize.pigeon_detached( + width: 320, + height: 240, + pigeon_instanceManager: testInstanceManager, + ); + case ResolutionPreset.medium: + expectedPreferredResolution = CameraSize.pigeon_detached( + width: 720, + height: 480, + pigeon_instanceManager: testInstanceManager, + ); + case ResolutionPreset.high: + expectedPreferredResolution = CameraSize.pigeon_detached( + width: 1280, + height: 720, + pigeon_instanceManager: testInstanceManager, + ); + case ResolutionPreset.veryHigh: + expectedPreferredResolution = CameraSize.pigeon_detached( + width: 1920, + height: 1080, + pigeon_instanceManager: testInstanceManager, + ); + case ResolutionPreset.ultraHigh: + expectedPreferredResolution = CameraSize.pigeon_detached( + width: 3840, + height: 2160, + pigeon_instanceManager: testInstanceManager, + ); + case ResolutionPreset.max: + expectedPreferredResolution = null; + } + + if (expectedPreferredResolution == null) { + expect(camera.preview!.resolutionSelector!.resolutionFilter, isNull); + expect( + camera.imageCapture!.resolutionSelector!.resolutionFilter, + isNull, + ); + expect( + camera.imageAnalysis!.resolutionSelector!.resolutionFilter, + isNull, + ); + continue; + } - if (expectedPreferredResolution == null) { - expect(camera.preview!.resolutionSelector!.resolutionFilter, isNull); expect( - camera.imageCapture!.resolutionSelector!.resolutionFilter, isNull); + lastSetPreferredSize?.width, + equals(expectedPreferredResolution.width), + ); expect( - camera.imageAnalysis!.resolutionSelector!.resolutionFilter, isNull); - continue; - } + lastSetPreferredSize?.height, + equals(expectedPreferredResolution.height), + ); - expect( - camera.preview!.resolutionSelector!.resolutionFilter! - .preferredResolution, - equals(expectedPreferredResolution)); - expect( - camera - .imageCapture!.resolutionSelector!.resolutionStrategy!.boundSize, - equals(expectedPreferredResolution)); - expect( - camera - .imageAnalysis!.resolutionSelector!.resolutionStrategy!.boundSize, - equals(expectedPreferredResolution)); - } + final CameraSize? imageCaptureSize = await camera + .imageCapture!.resolutionSelector!.resolutionStrategy! + .getBoundSize(); + expect( + imageCaptureSize?.width, + equals(expectedPreferredResolution.width), + ); + expect( + imageCaptureSize?.height, + equals(expectedPreferredResolution.height), + ); - // Test null case. - await camera.createCamera(testCameraDescription, null); - expect(camera.preview!.resolutionSelector, isNull); - expect(camera.imageCapture!.resolutionSelector, isNull); - expect(camera.imageAnalysis!.resolutionSelector, isNull); - }); + final CameraSize? imageAnalysisSize = await camera + .imageAnalysis!.resolutionSelector!.resolutionStrategy! + .getBoundSize(); + expect( + imageAnalysisSize?.width, + equals(expectedPreferredResolution.width), + ); + expect( + imageAnalysisSize?.height, + equals(expectedPreferredResolution.height), + ); + } + + // Test null case. + await camera.createCamera(testCameraDescription, null); + expect(camera.preview!.resolutionSelector, isNull); + expect(camera.imageCapture!.resolutionSelector, isNull); + expect(camera.imageAnalysis!.resolutionSelector, isNull); + }, + ); test( - 'createCamera properly sets aspect ratio based on preset resolution for non-video capture use cases', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const CameraLensDirection testLensDirection = CameraLensDirection.back; - const int testSensorOrientation = 90; - const CameraDescription testCameraDescription = CameraDescription( + 'createCamera properly sets aspect ratio based on preset resolution for non-video capture use cases', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const CameraLensDirection testLensDirection = CameraLensDirection.back; + const int testSensorOrientation = 90; + const CameraDescription testCameraDescription = CameraDescription( name: 'cameraName', lensDirection: testLensDirection, - sensorOrientation: testSensorOrientation); - const bool enableAudio = true; - final MockCamera mockCamera = MockCamera(); + sensorOrientation: testSensorOrientation, + ); + const bool enableAudio = true; + final MockCamera mockCamera = MockCamera(); - // Mock/Detached objects for (typically attached) objects created by - // createCamera. - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); + // Mock/Detached objects for (typically attached) objects created by + // createCamera. + final MockProcessCameraProvider mockProcessCameraProvider = + MockProcessCameraProvider(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); - // Tell plugin to create mock/detached objects for testing createCamera - // as needed. - camera.proxy = - getProxyForTestingResolutionPreset(mockProcessCameraProvider); - when(mockProcessCameraProvider.bindToLifecycle(any, any)) - .thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => MockLiveCameraState()); - camera.processCameraProvider = mockProcessCameraProvider; - - // Test non-null resolution presets. - for (final ResolutionPreset resolutionPreset in ResolutionPreset.values) { - await camera.createCamera(testCameraDescription, resolutionPreset, - enableAudio: enableAudio); - - int? expectedAspectRatio; - AspectRatioStrategy? expectedAspectRatioStrategy; - switch (resolutionPreset) { - case ResolutionPreset.low: - expectedAspectRatio = AspectRatio.ratio4To3; - case ResolutionPreset.high: - case ResolutionPreset.veryHigh: - case ResolutionPreset.ultraHigh: - expectedAspectRatio = AspectRatio.ratio16To9; - case ResolutionPreset.medium: - // Medium resolution preset uses aspect ratio 3:2 which is unsupported - // by CameraX. - case ResolutionPreset.max: - expectedAspectRatioStrategy = null; - } + // Tell plugin to create mock/detached objects for testing createCamera + // as needed. + camera.proxy = getProxyForTestingResolutionPreset( + mockProcessCameraProvider, + ); + when( + mockProcessCameraProvider.bindToLifecycle(any, any), + ).thenAnswer((_) async => mockCamera); + when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => MockLiveCameraState()); + camera.processCameraProvider = mockProcessCameraProvider; - expectedAspectRatioStrategy = expectedAspectRatio == null - ? null - : AspectRatioStrategy.detached( - preferredAspectRatio: expectedAspectRatio, - fallbackRule: AspectRatioStrategy.fallbackRuleAuto); - - if (expectedAspectRatio == null) { - expect(camera.preview!.resolutionSelector!.aspectRatioStrategy, isNull); - expect(camera.imageCapture!.resolutionSelector!.aspectRatioStrategy, - isNull); - expect(camera.imageAnalysis!.resolutionSelector!.aspectRatioStrategy, - isNull); - continue; - } + // Test non-null resolution presets. + for (final ResolutionPreset resolutionPreset in ResolutionPreset.values) { + await camera.createCamera( + testCameraDescription, + resolutionPreset, + enableAudio: enableAudio, + ); + + AspectRatio? expectedAspectRatio; + AspectRatioStrategyFallbackRule? expectedFallbackRule; + switch (resolutionPreset) { + case ResolutionPreset.low: + expectedAspectRatio = AspectRatio.ratio4To3; + expectedFallbackRule = AspectRatioStrategyFallbackRule.auto; + case ResolutionPreset.high: + case ResolutionPreset.veryHigh: + case ResolutionPreset.ultraHigh: + expectedAspectRatio = AspectRatio.ratio16To9; + expectedFallbackRule = AspectRatioStrategyFallbackRule.auto; + case ResolutionPreset.medium: + // Medium resolution preset uses aspect ratio 3:2 which is unsupported + // by CameraX. + case ResolutionPreset.max: + } - // Check aspect ratio. - expect( - camera.preview!.resolutionSelector!.aspectRatioStrategy! - .preferredAspectRatio, - equals(expectedAspectRatioStrategy!.preferredAspectRatio)); - expect( - camera.imageCapture!.resolutionSelector!.aspectRatioStrategy! - .preferredAspectRatio, - equals(expectedAspectRatioStrategy.preferredAspectRatio)); - expect( - camera.imageAnalysis!.resolutionSelector!.aspectRatioStrategy! - .preferredAspectRatio, - equals(expectedAspectRatioStrategy.preferredAspectRatio)); + if (expectedAspectRatio == null) { + expect( + await camera.preview!.resolutionSelector!.getAspectRatioStrategy(), + equals( + camera.proxy.ratio_4_3FallbackAutoStrategyAspectRatioStrategy(), + ), + ); + expect( + await camera.imageCapture!.resolutionSelector! + .getAspectRatioStrategy(), + equals( + camera.proxy.ratio_4_3FallbackAutoStrategyAspectRatioStrategy(), + ), + ); + expect( + await camera.imageAnalysis!.resolutionSelector! + .getAspectRatioStrategy(), + equals( + camera.proxy.ratio_4_3FallbackAutoStrategyAspectRatioStrategy(), + ), + ); + continue; + } - // Check fallback rule. - expect( - camera.preview!.resolutionSelector!.aspectRatioStrategy!.fallbackRule, - equals(expectedAspectRatioStrategy.fallbackRule)); - expect( - camera.imageCapture!.resolutionSelector!.aspectRatioStrategy! - .fallbackRule, - equals(expectedAspectRatioStrategy.fallbackRule)); - expect( - camera.imageAnalysis!.resolutionSelector!.aspectRatioStrategy! - .fallbackRule, - equals(expectedAspectRatioStrategy.fallbackRule)); - } + final AspectRatioStrategy previewStrategy = + await camera.preview!.resolutionSelector!.getAspectRatioStrategy(); + final AspectRatioStrategy imageCaptureStrategy = await camera + .imageCapture!.resolutionSelector! + .getAspectRatioStrategy(); + final AspectRatioStrategy imageAnalysisStrategy = await camera + .imageCapture!.resolutionSelector! + .getAspectRatioStrategy(); - // Test null case. - await camera.createCamera(testCameraDescription, null); - expect(camera.preview!.resolutionSelector, isNull); - expect(camera.imageCapture!.resolutionSelector, isNull); - expect(camera.imageAnalysis!.resolutionSelector, isNull); - }); + // Check aspect ratio. + expect( + await previewStrategy.getPreferredAspectRatio(), + equals(expectedAspectRatio), + ); + expect( + await imageCaptureStrategy.getPreferredAspectRatio(), + equals(expectedAspectRatio), + ); + expect( + await imageAnalysisStrategy.getPreferredAspectRatio(), + equals(expectedAspectRatio), + ); + + // Check fallback rule. + expect( + await previewStrategy.getFallbackRule(), + equals(expectedFallbackRule), + ); + expect( + await imageCaptureStrategy.getFallbackRule(), + equals(expectedFallbackRule), + ); + expect( + await imageAnalysisStrategy.getFallbackRule(), + equals(expectedFallbackRule), + ); + } + + // Test null case. + await camera.createCamera(testCameraDescription, null); + expect(camera.preview!.resolutionSelector, isNull); + expect(camera.imageCapture!.resolutionSelector, isNull); + expect(camera.imageAnalysis!.resolutionSelector, isNull); + }, + ); test( - 'createCamera properly sets preset resolution for video capture use case', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const CameraLensDirection testLensDirection = CameraLensDirection.back; - const int testSensorOrientation = 90; - const CameraDescription testCameraDescription = CameraDescription( + 'createCamera properly sets preset resolution for video capture use case', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const CameraLensDirection testLensDirection = CameraLensDirection.back; + const int testSensorOrientation = 90; + const CameraDescription testCameraDescription = CameraDescription( name: 'cameraName', lensDirection: testLensDirection, - sensorOrientation: testSensorOrientation); - const bool enableAudio = true; - final MockCamera mockCamera = MockCamera(); + sensorOrientation: testSensorOrientation, + ); + const bool enableAudio = true; + final MockCamera mockCamera = MockCamera(); - // Mock/Detached objects for (typically attached) objects created by - // createCamera. - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); + // Mock/Detached objects for (typically attached) objects created by + // createCamera. + final MockProcessCameraProvider mockProcessCameraProvider = + MockProcessCameraProvider(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); - // Tell plugin to create mock/detached objects for testing createCamera - // as needed. - camera.proxy = - getProxyForTestingResolutionPreset(mockProcessCameraProvider); + // Tell plugin to create mock/detached objects for testing createCamera + // as needed. + VideoQuality? fallbackStrategyVideoQuality; + VideoQuality? qualitySelectorVideoQuality; + FallbackStrategy? setFallbackStrategy; + final MockFallbackStrategy mockFallbackStrategy = MockFallbackStrategy(); + final MockQualitySelector mockQualitySelector = MockQualitySelector(); + camera.proxy = getProxyForTestingResolutionPreset( + mockProcessCameraProvider, + lowerQualityOrHigherThanFallbackStrategy: ({ + required VideoQuality quality, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + fallbackStrategyVideoQuality = quality; + return mockFallbackStrategy; + }, + fromQualitySelector: ({ + required VideoQuality quality, + FallbackStrategy? fallbackStrategy, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + qualitySelectorVideoQuality = quality; + setFallbackStrategy = fallbackStrategy; + return mockQualitySelector; + }, + ); - when(mockProcessCameraProvider.bindToLifecycle(any, any)) - .thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => MockLiveCameraState()); - - // Test non-null resolution presets. - for (final ResolutionPreset resolutionPreset in ResolutionPreset.values) { - await camera.createCamera(testCameraDescription, resolutionPreset, - enableAudio: enableAudio); - - VideoQuality? expectedVideoQuality; - switch (resolutionPreset) { - case ResolutionPreset.low: - // 240p is not supported by CameraX. - case ResolutionPreset.medium: - expectedVideoQuality = VideoQuality.SD; - case ResolutionPreset.high: - expectedVideoQuality = VideoQuality.HD; - case ResolutionPreset.veryHigh: - expectedVideoQuality = VideoQuality.FHD; - case ResolutionPreset.ultraHigh: - expectedVideoQuality = VideoQuality.UHD; - case ResolutionPreset.max: - expectedVideoQuality = VideoQuality.highest; + when( + mockProcessCameraProvider.bindToLifecycle(any, any), + ).thenAnswer((_) async => mockCamera); + when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => MockLiveCameraState()); + + // Test non-null resolution presets. + for (final ResolutionPreset resolutionPreset in ResolutionPreset.values) { + await camera.createCamera( + testCameraDescription, + resolutionPreset, + enableAudio: enableAudio, + ); + + VideoQuality? expectedVideoQuality; + switch (resolutionPreset) { + case ResolutionPreset.low: + // 240p is not supported by CameraX. + case ResolutionPreset.medium: + expectedVideoQuality = VideoQuality.SD; + case ResolutionPreset.high: + expectedVideoQuality = VideoQuality.HD; + case ResolutionPreset.veryHigh: + expectedVideoQuality = VideoQuality.FHD; + case ResolutionPreset.ultraHigh: + expectedVideoQuality = VideoQuality.UHD; + case ResolutionPreset.max: + expectedVideoQuality = VideoQuality.highest; + } + + expect( + await camera.recorder!.getQualitySelector(), + mockQualitySelector, + ); + expect(qualitySelectorVideoQuality, equals(expectedVideoQuality)); + expect(fallbackStrategyVideoQuality, equals(expectedVideoQuality)); + expect(setFallbackStrategy, equals(mockFallbackStrategy)); } - const VideoResolutionFallbackRule expectedFallbackRule = - VideoResolutionFallbackRule.lowerQualityOrHigherThan; - final FallbackStrategy expectedFallbackStrategy = - FallbackStrategy.detached( - quality: expectedVideoQuality, - fallbackRule: expectedFallbackRule); - - expect(camera.recorder!.qualitySelector!.qualityList.length, equals(1)); - expect(camera.recorder!.qualitySelector!.qualityList.first.quality, - equals(expectedVideoQuality)); - expect(camera.recorder!.qualitySelector!.fallbackStrategy!.quality, - equals(expectedFallbackStrategy.quality)); - expect(camera.recorder!.qualitySelector!.fallbackStrategy!.fallbackRule, - equals(expectedFallbackStrategy.fallbackRule)); - } + qualitySelectorVideoQuality = null; + setFallbackStrategy = null; - // Test null case. - await camera.createCamera(testCameraDescription, null); - expect(camera.recorder!.qualitySelector, isNull); - }); + // Test null case. + await camera.createCamera(testCameraDescription, null); + expect( + await camera.recorder!.getQualitySelector(), + isNot(equals(mockQualitySelector)), + ); + }, + ); test( - 'createCamera sets sensor orientation, handlesCropAndRotation, initialDeviceOrientation as expected', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const CameraLensDirection testLensDirection = CameraLensDirection.back; - const int testSensorOrientation = 270; - const CameraDescription testCameraDescription = CameraDescription( + 'createCamera sets sensor orientation, handlesCropAndRotation, initialDeviceOrientation as expected', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const CameraLensDirection testLensDirection = CameraLensDirection.back; + const int testSensorOrientation = 90; + const CameraDescription testCameraDescription = CameraDescription( name: 'cameraName', lensDirection: testLensDirection, - sensorOrientation: testSensorOrientation); - const bool enableAudio = true; - const ResolutionPreset testResolutionPreset = ResolutionPreset.veryHigh; - const bool testHandlesCropAndRotation = true; - const DeviceOrientation testUiOrientation = DeviceOrientation.portraitDown; - - // Mock/Detached objects for (typically attached) objects created by - // createCamera. - final MockCamera mockCamera = MockCamera(); - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final TestSystemServicesHostApi mockSystemServicesApi = - MockTestSystemServicesHostApi(); - TestSystemServicesHostApi.setup(mockSystemServicesApi); - - // The proxy needed for this test is the same as testing resolution - // presets except for mocking the retrievall of the sensor and current - // UI orientation. - camera.proxy = - getProxyForTestingResolutionPreset(mockProcessCameraProvider); - camera.proxy.getSensorOrientation = - (_) async => Future.value(testSensorOrientation); - camera.proxy.previewSurfaceProducerHandlesCropAndRotation = - (_) async => Future.value(testHandlesCropAndRotation); - camera.proxy.getUiOrientation = - () async => Future.value(testUiOrientation); - - when(mockProcessCameraProvider.bindToLifecycle(any, any)) - .thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => MockLiveCameraState()); + sensorOrientation: testSensorOrientation, + ); + const bool enableAudio = true; + const ResolutionPreset testResolutionPreset = ResolutionPreset.veryHigh; + const bool testHandlesCropAndRotation = true; + + // Mock/Detached objects for (typically attached) objects created by + // createCamera. + final MockCamera mockCamera = MockCamera(); + final MockProcessCameraProvider mockProcessCameraProvider = + MockProcessCameraProvider(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); - await camera.createCamera(testCameraDescription, testResolutionPreset, - enableAudio: enableAudio); + // The proxy needed for this test is the same as testing resolution + // presets except for mocking the retrieval of the sensor and current + // UI orientation. + camera.proxy = getProxyForTestingResolutionPreset( + mockProcessCameraProvider, + newPreview: ({ + int? targetRotation, + ResolutionSelector? resolutionSelector, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockPreview mockPreview = MockPreview(); + when( + mockPreview.surfaceProducerHandlesCropAndRotation(), + ).thenAnswer((_) async => testHandlesCropAndRotation); + when(mockPreview.resolutionSelector).thenReturn(resolutionSelector); + return mockPreview; + }, + ); - expect(camera.sensorOrientationDegrees, testSensorOrientation); - }); + when( + mockProcessCameraProvider.bindToLifecycle(any, any), + ).thenAnswer((_) async => mockCamera); + when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => MockLiveCameraState()); + + await camera.createCamera( + testCameraDescription, + testResolutionPreset, + enableAudio: enableAudio, + ); + + expect(camera.sensorOrientationDegrees, testSensorOrientation); + }, + ); test( - 'initializeCamera throws a CameraException when createCamera has not been called before initializedCamera', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - await expectLater(() async { - await camera.initializeCamera(3); - }, throwsA(isA())); - }); + 'initializeCamera throws a CameraException when createCamera has not been called before initializedCamera', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + await expectLater(() async { + await camera.initializeCamera(3); + }, throwsA(isA())); + }, + ); test('initializeCamera sends expected CameraInitializedEvent', () async { final AndroidCameraCameraX camera = AndroidCameraCameraX(); @@ -986,14 +1935,24 @@ void main() { const CameraLensDirection testLensDirection = CameraLensDirection.back; const int testSensorOrientation = 90; const CameraDescription testCameraDescription = CameraDescription( - name: 'cameraName', - lensDirection: testLensDirection, - sensorOrientation: testSensorOrientation); + name: 'cameraName', + lensDirection: testLensDirection, + sensorOrientation: testSensorOrientation, + ); const int resolutionWidth = 350; const int resolutionHeight = 750; final Camera mockCamera = MockCamera(); - final ResolutionInfo testResolutionInfo = - ResolutionInfo(width: resolutionWidth, height: resolutionHeight); + final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); + final ResolutionInfo testResolutionInfo = ResolutionInfo.pigeon_detached( + resolution: CameraSize.pigeon_detached( + width: resolutionWidth, + height: resolutionHeight, + pigeon_instanceManager: testInstanceManager, + ), + pigeon_instanceManager: testInstanceManager, + ); // Mocks for (typically attached) objects created by createCamera. final MockProcessCameraProvider mockProcessCameraProvider = @@ -1004,76 +1963,221 @@ void main() { final MockPreview mockPreview = MockPreview(); final MockImageCapture mockImageCapture = MockImageCapture(); final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); - final TestSystemServicesHostApi mockSystemServicesApi = - MockTestSystemServicesHostApi(); - TestSystemServicesHostApi.setup(mockSystemServicesApi); // Tell plugin to create mock/detached objects for testing createCamera // as needed. camera.proxy = CameraXProxy( - getProcessCameraProvider: () => + getInstanceProcessCameraProvider: ({ + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => Future.value(mockProcessCameraProvider), - createCameraSelector: (int cameraSelectorLensDirection) { - switch (cameraSelectorLensDirection) { - case CameraSelector.lensFacingFront: + newCameraSelector: ({ + LensFacing? requireLensFacing, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + switch (requireLensFacing) { + case LensFacing.front: return mockFrontCameraSelector; - case CameraSelector.lensFacingBack: - default: + case _: return mockBackCameraSelector; } }, - createPreview: (_, __) => mockPreview, - createImageCapture: (_, __) => mockImageCapture, - createRecorder: (QualitySelector? qualitySelector) => MockRecorder(), - createVideoCapture: (_) => Future.value(MockVideoCapture()), - createImageAnalysis: (_, __) => mockImageAnalysis, - createResolutionStrategy: ( - {bool highestAvailable = false, - Size? boundSize, - int? fallbackRule}) => + newPreview: ({ + int? targetRotation, + ResolutionSelector? resolutionSelector, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + mockPreview, + newImageCapture: ({ + int? targetRotation, + CameraXFlashMode? flashMode, + ResolutionSelector? resolutionSelector, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + mockImageCapture, + newRecorder: ({ + int? aspectRatio, + int? targetVideoEncodingBitRate, + QualitySelector? qualitySelector, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + MockRecorder(), + withOutputVideoCapture: ({ + required VideoOutput videoOutput, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + MockVideoCapture(), + newImageAnalysis: ({ + int? targetRotation, + ResolutionSelector? resolutionSelector, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + mockImageAnalysis, + newResolutionStrategy: ({ + required CameraSize boundSize, + required ResolutionStrategyFallbackRule fallbackRule, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => MockResolutionStrategy(), - createResolutionSelector: (_, __, ___) => MockResolutionSelector(), - createFallbackStrategy: ( - {required VideoQuality quality, - required VideoResolutionFallbackRule fallbackRule}) => + newResolutionSelector: ({ + AspectRatioStrategy? aspectRatioStrategy, + ResolutionStrategy? resolutionStrategy, + ResolutionFilter? resolutionFilter, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + MockResolutionSelector(), + lowerQualityOrHigherThanFallbackStrategy: ({ + required VideoQuality quality, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => MockFallbackStrategy(), - createQualitySelector: ( - {required VideoQuality videoQuality, - required FallbackStrategy fallbackStrategy}) => + fromQualitySelector: ({ + required VideoQuality quality, + FallbackStrategy? fallbackStrategy, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => MockQualitySelector(), - createCameraStateObserver: (void Function(Object) onChanged) => - Observer.detached(onChanged: onChanged), - requestCameraPermissions: (_) => Future.value(), - startListeningForDeviceOrientationChange: (_, __) {}, - createAspectRatioStrategy: (_, __) => MockAspectRatioStrategy(), - createResolutionFilterWithOnePreferredSize: (_) => MockResolutionFilter(), - getCamera2CameraInfo: (_) => - Future.value(MockCamera2CameraInfo()), - getUiOrientation: () => - Future.value(DeviceOrientation.portraitUp), + newObserver: ({ + required void Function(Observer, T) onChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Observer.detached( + onChanged: onChanged, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + newSystemServicesManager: ({ + required void Function(SystemServicesManager, String) onCameraError, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + MockSystemServicesManager(), + newDeviceOrientationManager: ({ + required void Function(DeviceOrientationManager, String) + onDeviceOrientationChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockDeviceOrientationManager manager = + MockDeviceOrientationManager(); + when(manager.getUiOrientation()).thenAnswer((_) async { + return 'PORTRAIT_UP'; + }); + return manager; + }, + newAspectRatioStrategy: ({ + required AspectRatio preferredAspectRatio, + required AspectRatioStrategyFallbackRule fallbackRule, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + MockAspectRatioStrategy(), + createWithOnePreferredSizeResolutionFilter: ({ + required CameraSize preferredSize, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + MockResolutionFilter(), + fromCamera2CameraInfo: ({ + required CameraInfo cameraInfo, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockCamera2CameraInfo mockCamera2CameraInfo = + MockCamera2CameraInfo(); + when( + mockCamera2CameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => 90); + return mockCamera2CameraInfo; + }, + newCameraSize: ({ + required int width, + required int height, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + MockCameraSize(), + sensorOrientationCameraCharacteristics: () => + MockCameraCharacteristicsKey(), ); final CameraInitializedEvent testCameraInitializedEvent = CameraInitializedEvent( - cameraId, - resolutionWidth.toDouble(), - resolutionHeight.toDouble(), - ExposureMode.auto, - true, - FocusMode.auto, - true); + cameraId, + resolutionWidth.toDouble(), + resolutionHeight.toDouble(), + ExposureMode.auto, + true, + FocusMode.auto, + true, + ); // Call createCamera. - when(mockPreview.setSurfaceProvider()).thenAnswer((_) async => cameraId); + when(mockPreview.setSurfaceProvider(any)).thenAnswer((_) async => cameraId); - when(mockProcessCameraProvider.bindToLifecycle(mockBackCameraSelector, - [mockPreview, mockImageCapture, mockImageAnalysis])) - .thenAnswer((_) async => mockCamera); + when( + mockProcessCameraProvider.bindToLifecycle( + mockBackCameraSelector, + [mockPreview, mockImageCapture, mockImageAnalysis], + ), + ).thenAnswer((_) async => mockCamera); when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => MockLiveCameraState()); - when(mockPreview.getResolutionInfo()) - .thenAnswer((_) async => testResolutionInfo); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => MockLiveCameraState()); + when( + mockPreview.getResolutionInfo(), + ).thenAnswer((_) async => testResolutionInfo); await camera.createCameraWithSettings( testCameraDescription, @@ -1099,22 +2203,23 @@ void main() { }); test( - 'dispose releases Flutter surface texture, removes camera state observers, and unbinds all use cases', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); + 'dispose releases Flutter surface texture, removes camera state observers, and unbinds all use cases', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); - camera.preview = MockPreview(); - camera.processCameraProvider = MockProcessCameraProvider(); - camera.liveCameraState = MockLiveCameraState(); - camera.imageAnalysis = MockImageAnalysis(); + camera.preview = MockPreview(); + camera.processCameraProvider = MockProcessCameraProvider(); + camera.liveCameraState = MockLiveCameraState(); + camera.imageAnalysis = MockImageAnalysis(); - await camera.dispose(3); + await camera.dispose(3); - verify(camera.preview!.releaseFlutterSurfaceTexture()); - verify(camera.liveCameraState!.removeObservers()); - verify(camera.processCameraProvider!.unbindAll()); - verify(camera.imageAnalysis!.clearAnalyzer()); - }); + verify(camera.preview!.releaseSurfaceProvider()); + verify(camera.liveCameraState!.removeObservers()); + verify(camera.processCameraProvider!.unbindAll()); + verify(camera.imageAnalysis!.clearAnalyzer()); + }, + ); test('onCameraInitialized stream emits CameraInitializedEvents', () async { final AndroidCameraCameraX camera = AndroidCameraCameraX(); @@ -1124,7 +2229,14 @@ void main() { final StreamQueue streamQueue = StreamQueue(eventStream); const CameraInitializedEvent testEvent = CameraInitializedEvent( - cameraId, 320, 80, ExposureMode.auto, false, FocusMode.auto, false); + cameraId, + 320, + 80, + ExposureMode.auto, + false, + FocusMode.auto, + false, + ); camera.cameraEventStreamController.add(testEvent); @@ -1133,529 +2245,930 @@ void main() { }); test( - 'onCameraClosing stream emits camera closing event when cameraEventStreamController emits a camera closing event', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 99; - const CameraClosingEvent cameraClosingEvent = CameraClosingEvent(cameraId); - final Stream eventStream = - camera.onCameraClosing(cameraId); - final StreamQueue streamQueue = - StreamQueue(eventStream); + 'onCameraClosing stream emits camera closing event when cameraEventStreamController emits a camera closing event', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 99; + const CameraClosingEvent cameraClosingEvent = CameraClosingEvent( + cameraId, + ); + final Stream eventStream = camera.onCameraClosing( + cameraId, + ); + final StreamQueue streamQueue = + StreamQueue(eventStream); - camera.cameraEventStreamController.add(cameraClosingEvent); + camera.cameraEventStreamController.add(cameraClosingEvent); - expect(await streamQueue.next, equals(cameraClosingEvent)); - await streamQueue.cancel(); - }); + expect(await streamQueue.next, equals(cameraClosingEvent)); + await streamQueue.cancel(); + }, + ); test( - 'onCameraError stream emits errors caught by system services or added to stream within plugin', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 27; - const String firstTestErrorDescription = 'Test error description 1!'; - const String secondTestErrorDescription = 'Test error description 2!'; - const CameraErrorEvent secondCameraErrorEvent = - CameraErrorEvent(cameraId, secondTestErrorDescription); - final Stream eventStream = camera.onCameraError(cameraId); - final StreamQueue streamQueue = - StreamQueue(eventStream); - - SystemServices.cameraErrorStreamController.add(firstTestErrorDescription); - expect(await streamQueue.next, - equals(const CameraErrorEvent(cameraId, firstTestErrorDescription))); - - camera.cameraEventStreamController.add(secondCameraErrorEvent); - expect(await streamQueue.next, equals(secondCameraErrorEvent)); + 'onCameraError stream emits errors caught by system services or added to stream within plugin', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 27; + const String firstTestErrorDescription = 'Test error description 1!'; + const String secondTestErrorDescription = 'Test error description 2!'; + const CameraErrorEvent secondCameraErrorEvent = CameraErrorEvent( + cameraId, + secondTestErrorDescription, + ); + final Stream eventStream = camera.onCameraError( + cameraId, + ); + final StreamQueue streamQueue = + StreamQueue(eventStream); - await streamQueue.cancel(); - }); + camera.proxy = CameraXProxy( + newSystemServicesManager: ({ + required void Function(SystemServicesManager, String) onCameraError, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockSystemServicesManager mockSystemServicesManager = + MockSystemServicesManager(); + when( + mockSystemServicesManager.onCameraError, + ).thenReturn(onCameraError); + return mockSystemServicesManager; + }, + ); - test( - 'onDeviceOrientationChanged stream emits changes in device orientation detected by system services', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final Stream eventStream = - camera.onDeviceOrientationChanged(); - final StreamQueue streamQueue = - StreamQueue(eventStream); - const DeviceOrientationChangedEvent testEvent = - DeviceOrientationChangedEvent(DeviceOrientation.portraitDown); + camera.systemServicesManager.onCameraError( + camera.systemServicesManager, + firstTestErrorDescription, + ); + expect( + await streamQueue.next, + equals(const CameraErrorEvent(cameraId, firstTestErrorDescription)), + ); - DeviceOrientationManager.deviceOrientationChangedStreamController - .add(testEvent); + camera.cameraEventStreamController.add(secondCameraErrorEvent); + expect(await streamQueue.next, equals(secondCameraErrorEvent)); - expect(await streamQueue.next, testEvent); - await streamQueue.cancel(); - }); + await streamQueue.cancel(); + }, + ); test( - 'pausePreview unbinds preview from lifecycle when preview is nonnull and has been bound to lifecycle', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - - // Set directly for test versus calling createCamera. - camera.processCameraProvider = MockProcessCameraProvider(); - camera.preview = MockPreview(); + 'onDeviceOrientationChanged stream emits changes in device orientation detected by system services', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final Stream eventStream = + camera.onDeviceOrientationChanged(); + final StreamQueue streamQueue = + StreamQueue(eventStream); + const DeviceOrientationChangedEvent testEvent = + DeviceOrientationChangedEvent(DeviceOrientation.portraitDown); - when(camera.processCameraProvider!.isBound(camera.preview!)) - .thenAnswer((_) async => true); + camera.proxy = CameraXProxy( + newDeviceOrientationManager: ({ + required void Function(DeviceOrientationManager, String) + onDeviceOrientationChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockDeviceOrientationManager mockDeviceOrientationManager = + MockDeviceOrientationManager(); + when( + mockDeviceOrientationManager.onDeviceOrientationChanged, + ).thenReturn(onDeviceOrientationChanged); + return mockDeviceOrientationManager; + }, + ); - await camera.pausePreview(579); + camera.deviceOrientationManager.onDeviceOrientationChanged( + camera.deviceOrientationManager, + 'PORTRAIT_DOWN', + ); - verify(camera.processCameraProvider!.unbind([camera.preview!])); - }); + expect(await streamQueue.next, testEvent); + await streamQueue.cancel(); + }, + ); test( - 'pausePreview does not unbind preview from lifecycle when preview has not been bound to lifecycle', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - - // Set directly for test versus calling createCamera. - camera.processCameraProvider = MockProcessCameraProvider(); - camera.preview = MockPreview(); + 'pausePreview unbinds preview from lifecycle when preview is nonnull and has been bound to lifecycle', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); - await camera.pausePreview(632); + // Set directly for test versus calling createCamera. + camera.processCameraProvider = MockProcessCameraProvider(); + camera.preview = MockPreview(); - verifyNever( - camera.processCameraProvider!.unbind([camera.preview!])); - }); + when( + camera.processCameraProvider!.isBound(camera.preview!), + ).thenAnswer((_) async => true); - test( - 'resumePreview does not bind preview to lifecycle or update camera state observers if already bound', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockCamera mockCamera = MockCamera(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final MockLiveCameraState mockLiveCameraState = MockLiveCameraState(); + await camera.pausePreview(579); - // Set directly for test versus calling createCamera. - camera.processCameraProvider = mockProcessCameraProvider; - camera.cameraSelector = MockCameraSelector(); - camera.preview = MockPreview(); + verify(camera.processCameraProvider!.unbind([camera.preview!])); + }, + ); - when(camera.processCameraProvider!.isBound(camera.preview!)) - .thenAnswer((_) async => true); + test( + 'pausePreview does not unbind preview from lifecycle when preview has not been bound to lifecycle', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); - when(mockProcessCameraProvider - .bindToLifecycle(camera.cameraSelector, [camera.preview!])) - .thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => mockLiveCameraState); + // Set directly for test versus calling createCamera. + camera.processCameraProvider = MockProcessCameraProvider(); + camera.preview = MockPreview(); - await camera.resumePreview(78); + await camera.pausePreview(632); - verifyNever(camera.processCameraProvider! - .bindToLifecycle(camera.cameraSelector!, [camera.preview!])); - verifyNever(mockLiveCameraState.observe(any)); - expect(camera.cameraInfo, isNot(mockCameraInfo)); - }); + verifyNever( + camera.processCameraProvider!.unbind([camera.preview!]), + ); + }, + ); test( - 'resumePreview binds preview to lifecycle and updates camera state observers if not already bound', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockCamera mockCamera = MockCamera(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final MockCameraControl mockCameraControl = MockCameraControl(); - final MockLiveCameraState mockLiveCameraState = MockLiveCameraState(); - - // Set directly for test versus calling createCamera. - camera.processCameraProvider = mockProcessCameraProvider; - camera.cameraSelector = MockCameraSelector(); - camera.preview = MockPreview(); - - // Tell plugin to create a detached Observer, that is created to - // track camera state once preview is bound to the lifecycle and needed to - // test for expected updates. - camera.proxy = CameraXProxy( - createCameraStateObserver: - (void Function(Object stateAsObject) onChanged) => - Observer.detached(onChanged: onChanged)); + 'resumePreview does not bind preview to lifecycle or update camera state observers if already bound', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final MockProcessCameraProvider mockProcessCameraProvider = + MockProcessCameraProvider(); + final MockCamera mockCamera = MockCamera(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final MockLiveCameraState mockLiveCameraState = MockLiveCameraState(); - when(mockProcessCameraProvider - .bindToLifecycle(camera.cameraSelector, [camera.preview!])) - .thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => mockLiveCameraState); - when(mockCamera.getCameraControl()) - .thenAnswer((_) async => mockCameraControl); + // Set directly for test versus calling createCamera. + camera.processCameraProvider = mockProcessCameraProvider; + camera.cameraSelector = MockCameraSelector(); + camera.preview = MockPreview(); - await camera.resumePreview(78); + when( + camera.processCameraProvider!.isBound(camera.preview!), + ).thenAnswer((_) async => true); - verify(camera.processCameraProvider! - .bindToLifecycle(camera.cameraSelector!, [camera.preview!])); - expect( - await testCameraClosingObserver( - camera, - 78, - verify(mockLiveCameraState.observe(captureAny)).captured.single - as Observer), - isTrue); - expect(camera.cameraInfo, equals(mockCameraInfo)); - expect(camera.cameraControl, equals(mockCameraControl)); - }); + when( + mockProcessCameraProvider.bindToLifecycle( + camera.cameraSelector, + [camera.preview!], + ), + ).thenAnswer((_) async => mockCamera); + when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => mockLiveCameraState); + + await camera.resumePreview(78); + + verifyNever( + camera.processCameraProvider!.bindToLifecycle( + camera.cameraSelector!, + [camera.preview!], + ), + ); + verifyNever(mockLiveCameraState.observe(any)); + expect(camera.cameraInfo, isNot(mockCameraInfo)); + }, + ); - // Further `buildPreview` testing concerning the Widget that it returns is - // located in preview_rotation_test.dart. test( - 'buildPreview throws an exception if the preview is not bound to the lifecycle', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 73; - - // Tell camera that createCamera has not been called and thus, preview has - // not been bound to the lifecycle of the camera. - camera.previewInitiallyBound = false; - - expect( - () => camera.buildPreview(cameraId), throwsA(isA())); - }); - - group('video recording', () { - test( - 'startVideoCapturing binds video capture use case, updates saved camera instance and its properties, and starts the recording', - () async { - // Set up mocks and constants. + 'resumePreview binds preview to lifecycle and updates camera state observers if not already bound', + () async { final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockPendingRecording mockPendingRecording = MockPendingRecording(); - final MockRecording mockRecording = MockRecording(); + final MockProcessCameraProvider mockProcessCameraProvider = + MockProcessCameraProvider(); final MockCamera mockCamera = MockCamera(); - final MockCamera newMockCamera = MockCamera(); final MockCameraInfo mockCameraInfo = MockCameraInfo(); final MockCameraControl mockCameraControl = MockCameraControl(); final MockLiveCameraState mockLiveCameraState = MockLiveCameraState(); - final MockLiveCameraState newMockLiveCameraState = MockLiveCameraState(); - final MockCamera2CameraInfo mockCamera2CameraInfo = - MockCamera2CameraInfo(); - final TestSystemServicesHostApi mockSystemServicesApi = - MockTestSystemServicesHostApi(); - TestSystemServicesHostApi.setup(mockSystemServicesApi); // Set directly for test versus calling createCamera. - camera.processCameraProvider = MockProcessCameraProvider(); - camera.camera = mockCamera; - camera.recorder = MockRecorder(); - camera.videoCapture = MockVideoCapture(); + camera.processCameraProvider = mockProcessCameraProvider; camera.cameraSelector = MockCameraSelector(); - camera.liveCameraState = mockLiveCameraState; - camera.cameraInfo = MockCameraInfo(); - camera.imageAnalysis = MockImageAnalysis(); - - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; + camera.preview = MockPreview(); - // Tell plugin to create detached Observer when camera info updated. + // Tell plugin to create a detached Observer, that is created to + // track camera state once preview is bound to the lifecycle and needed to + // test for expected updates. camera.proxy = CameraXProxy( - createCameraStateObserver: (void Function(Object) onChanged) => - Observer.detached(onChanged: onChanged), - getCamera2CameraInfo: (CameraInfo cameraInfo) => - Future.value(mockCamera2CameraInfo)); - - const int cameraId = 17; - const String outputPath = '/temp/REC123.temp'; - - // Mock method calls. - when(mockSystemServicesApi.getTempFilePath(camera.videoPrefix, '.temp')) - .thenReturn(outputPath); - when(camera.recorder!.prepareRecording(outputPath)) - .thenAnswer((_) async => mockPendingRecording); - when(mockPendingRecording.start()).thenAnswer((_) async => mockRecording); - when(camera.processCameraProvider!.isBound(camera.videoCapture!)) - .thenAnswer((_) async => false); - when(camera.processCameraProvider!.bindToLifecycle( - camera.cameraSelector!, [camera.videoCapture!])) - .thenAnswer((_) async => newMockCamera); - when(newMockCamera.getCameraInfo()) - .thenAnswer((_) async => mockCameraInfo); - when(newMockCamera.getCameraControl()) - .thenAnswer((_) async => mockCameraControl); - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => newMockLiveCameraState); - when(mockCamera2CameraInfo.getSupportedHardwareLevel()).thenAnswer( - (_) async => CameraMetadata.infoSupportedHardwareLevelLimited); - - // Simulate video recording being started so startVideoRecording completes. - PendingRecording.videoRecordingEventStreamController - .add(VideoRecordEvent.start); - - await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); + newObserver: ({ + required void Function(Observer, T) onChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Observer.detached( + onChanged: onChanged, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + ); - // Verify VideoCapture UseCase is bound and camera & its properties - // are updated. - verify(camera.processCameraProvider!.bindToLifecycle( - camera.cameraSelector!, [camera.videoCapture!])); - expect(camera.camera, equals(newMockCamera)); + when( + mockProcessCameraProvider.bindToLifecycle( + camera.cameraSelector, + [camera.preview!], + ), + ).thenAnswer((_) async => mockCamera); + when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => mockLiveCameraState); + when(mockCamera.cameraControl).thenReturn(mockCameraControl); + + await camera.resumePreview(78); + + verify( + camera.processCameraProvider!.bindToLifecycle( + camera.cameraSelector!, + [camera.preview!], + ), + ); + expect( + await testCameraClosingObserver( + camera, + 78, + verify(mockLiveCameraState.observe(captureAny)).captured.single + as Observer, + ), + isTrue, + ); expect(camera.cameraInfo, equals(mockCameraInfo)); expect(camera.cameraControl, equals(mockCameraControl)); - verify(mockLiveCameraState.removeObservers()); - expect( - await testCameraClosingObserver( - camera, - cameraId, - verify(newMockLiveCameraState.observe(captureAny)).captured.single - as Observer), - isTrue); - - // Verify recording is started. - expect(camera.pendingRecording, equals(mockPendingRecording)); - expect(camera.recording, mockRecording); - }); + }, + ); - test( - 'startVideoCapturing binds video capture use case and starts the recording' - ' on first call, and does nothing on second call', () async { - // Set up mocks and constants. + // Further `buildPreview` testing concerning the Widget that it returns is + // located in preview_rotation_test.dart. + test( + 'buildPreview throws an exception if the preview is not bound to the lifecycle', + () async { final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockPendingRecording mockPendingRecording = MockPendingRecording(); - final MockRecording mockRecording = MockRecording(); - final MockCamera mockCamera = MockCamera(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final MockCamera2CameraInfo mockCamera2CameraInfo = - MockCamera2CameraInfo(); - final TestSystemServicesHostApi mockSystemServicesApi = - MockTestSystemServicesHostApi(); - TestSystemServicesHostApi.setup(mockSystemServicesApi); - - // Set directly for test versus calling createCamera. - camera.processCameraProvider = MockProcessCameraProvider(); - camera.recorder = MockRecorder(); - camera.videoCapture = MockVideoCapture(); - camera.cameraSelector = MockCameraSelector(); - camera.cameraInfo = MockCameraInfo(); - camera.imageAnalysis = MockImageAnalysis(); - - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; - - // Tell plugin to create detached Observer when camera info updated. - camera.proxy = CameraXProxy( - createCameraStateObserver: (void Function(Object) onChanged) => - Observer.detached(onChanged: onChanged), - getCamera2CameraInfo: (CameraInfo cameraInfo) => - Future.value(mockCamera2CameraInfo)); + const int cameraId = 73; - const int cameraId = 17; - const String outputPath = '/temp/REC123.temp'; + // Tell camera that createCamera has not been called and thus, preview has + // not been bound to the lifecycle of the camera. + camera.previewInitiallyBound = false; - // Mock method calls. - when(mockSystemServicesApi.getTempFilePath(camera.videoPrefix, '.temp')) - .thenReturn(outputPath); - when(camera.recorder!.prepareRecording(outputPath)) - .thenAnswer((_) async => mockPendingRecording); - when(mockPendingRecording.start()).thenAnswer((_) async => mockRecording); - when(camera.processCameraProvider!.isBound(camera.videoCapture!)) - .thenAnswer((_) async => false); - when(camera.processCameraProvider!.bindToLifecycle( - camera.cameraSelector!, [camera.videoCapture!])) - .thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()) - .thenAnswer((_) => Future.value(mockCameraInfo)); - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => MockLiveCameraState()); - when(mockCamera2CameraInfo.getSupportedHardwareLevel()).thenAnswer( - (_) async => CameraMetadata.infoSupportedHardwareLevelLimited); + expect( + () => camera.buildPreview(cameraId), + throwsA(isA()), + ); + }, + ); - // Simulate video recording being started so startVideoRecording completes. - PendingRecording.videoRecordingEventStreamController - .add(VideoRecordEvent.start); + group('video recording', () { + test( + 'startVideoCapturing binds video capture use case, updates saved camera instance and its properties, and starts the recording', + () async { + // Set up mocks and constants. + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final MockPendingRecording mockPendingRecording = + MockPendingRecording(); + final MockRecording mockRecording = MockRecording(); + final MockCamera mockCamera = MockCamera(); + final MockCamera newMockCamera = MockCamera(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final MockCameraControl mockCameraControl = MockCameraControl(); + final MockLiveCameraState mockLiveCameraState = MockLiveCameraState(); + final MockLiveCameraState newMockLiveCameraState = + MockLiveCameraState(); + final MockCamera2CameraInfo mockCamera2CameraInfo = + MockCamera2CameraInfo(); + + // Set directly for test versus calling createCamera. + camera.processCameraProvider = MockProcessCameraProvider(); + camera.camera = mockCamera; + camera.recorder = MockRecorder(); + camera.videoCapture = MockVideoCapture(); + camera.cameraSelector = MockCameraSelector(); + camera.liveCameraState = mockLiveCameraState; + camera.cameraInfo = MockCameraInfo(); + camera.imageAnalysis = MockImageAnalysis(); + + // Ignore setting target rotation for this test; tested separately. + camera.captureOrientationLocked = true; + + // Tell plugin to create detached Observer when camera info updated. + const String outputPath = '/temp/REC123.temp'; + camera.proxy = CameraXProxy( + newObserver: ({ + required void Function(Observer, T) onChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Observer.detached( + onChanged: onChanged, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + fromCamera2CameraInfo: ({ + required CameraInfo cameraInfo, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + mockCamera2CameraInfo, + newSystemServicesManager: ({ + required void Function(SystemServicesManager, String) onCameraError, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockSystemServicesManager mockSystemServicesManager = + MockSystemServicesManager(); + when( + mockSystemServicesManager.getTempFilePath( + camera.videoPrefix, + '.temp', + ), + ).thenAnswer((_) async => outputPath); + return mockSystemServicesManager; + }, + newVideoRecordEventListener: ({ + required void Function(VideoRecordEventListener, VideoRecordEvent) + onEvent, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return VideoRecordEventListener.pigeon_detached( + onEvent: onEvent, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + infoSupportedHardwareLevelCameraCharacteristics: () { + return MockCameraCharacteristicsKey(); + }, + ); + + const int cameraId = 17; + + // Mock method calls. + when( + camera.recorder!.prepareRecording(outputPath), + ).thenAnswer((_) async => mockPendingRecording); + when( + mockPendingRecording.start(any), + ).thenAnswer((_) async => mockRecording); + when( + camera.processCameraProvider!.isBound(camera.videoCapture!), + ).thenAnswer((_) async => false); + when( + camera.processCameraProvider!.bindToLifecycle( + camera.cameraSelector!, + [camera.videoCapture!], + ), + ).thenAnswer((_) async => newMockCamera); + when( + newMockCamera.getCameraInfo(), + ).thenAnswer((_) async => mockCameraInfo); + when(newMockCamera.cameraControl).thenReturn(mockCameraControl); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => newMockLiveCameraState); + when( + mockCamera2CameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => InfoSupportedHardwareLevel.limited); + + // Simulate video recording being started so startVideoRecording completes. + AndroidCameraCameraX.videoRecordingEventStreamController.add( + VideoRecordEventStart.pigeon_detached( + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ), + ); - await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); + await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); - verify(camera.processCameraProvider!.bindToLifecycle( - camera.cameraSelector!, [camera.videoCapture!])); - expect(camera.pendingRecording, equals(mockPendingRecording)); - expect(camera.recording, mockRecording); + // Verify VideoCapture UseCase is bound and camera & its properties + // are updated. + verify( + camera.processCameraProvider!.bindToLifecycle( + camera.cameraSelector!, + [camera.videoCapture!], + ), + ); + expect(camera.camera, equals(newMockCamera)); + expect(camera.cameraInfo, equals(mockCameraInfo)); + expect(camera.cameraControl, equals(mockCameraControl)); + verify(mockLiveCameraState.removeObservers()); + expect( + await testCameraClosingObserver( + camera, + cameraId, + verify(newMockLiveCameraState.observe(captureAny)).captured.single + as Observer, + ), + isTrue, + ); - await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); - // Verify that each of these calls happened only once. - verify(mockSystemServicesApi.getTempFilePath(camera.videoPrefix, '.temp')) - .called(1); - verifyNoMoreInteractions(mockSystemServicesApi); - verify(camera.recorder!.prepareRecording(outputPath)).called(1); - verifyNoMoreInteractions(camera.recorder); - verify(mockPendingRecording.start()).called(1); - verifyNoMoreInteractions(mockPendingRecording); - }); + // Verify recording is started. + expect(camera.pendingRecording, equals(mockPendingRecording)); + expect(camera.recording, mockRecording); + }, + ); test( - 'startVideoCapturing called with stream options starts image streaming', - () async { - // Set up mocks and constants. - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final Recorder mockRecorder = MockRecorder(); - final MockPendingRecording mockPendingRecording = MockPendingRecording(); - final MockCameraInfo initialCameraInfo = MockCameraInfo(); - final MockCamera2CameraInfo mockCamera2CameraInfo = - MockCamera2CameraInfo(); - final TestSystemServicesHostApi mockSystemServicesApi = - MockTestSystemServicesHostApi(); - TestSystemServicesHostApi.setup(mockSystemServicesApi); - - // Set directly for test versus calling createCamera. - - camera.processCameraProvider = mockProcessCameraProvider; - camera.cameraSelector = MockCameraSelector(); - camera.videoCapture = MockVideoCapture(); - camera.imageAnalysis = MockImageAnalysis(); - camera.camera = MockCamera(); - camera.recorder = mockRecorder; - camera.cameraInfo = initialCameraInfo; - camera.imageCapture = MockImageCapture(); + 'startVideoCapturing binds video capture use case and starts the recording' + ' on first call, and does nothing on second call', + () async { + // Set up mocks and constants. + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final MockPendingRecording mockPendingRecording = + MockPendingRecording(); + final MockRecording mockRecording = MockRecording(); + final MockCamera mockCamera = MockCamera(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final MockCamera2CameraInfo mockCamera2CameraInfo = + MockCamera2CameraInfo(); + + // Set directly for test versus calling createCamera. + camera.processCameraProvider = MockProcessCameraProvider(); + camera.recorder = MockRecorder(); + camera.videoCapture = MockVideoCapture(); + camera.cameraSelector = MockCameraSelector(); + camera.cameraInfo = MockCameraInfo(); + camera.imageAnalysis = MockImageAnalysis(); + + // Ignore setting target rotation for this test; tested seprately. + camera.captureOrientationLocked = true; + + // Tell plugin to create detached Observer when camera info updated. + const String outputPath = '/temp/REC123.temp'; + camera.proxy = CameraXProxy( + newObserver: ({ + required void Function(Observer, T) onChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Observer.detached( + onChanged: onChanged, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + fromCamera2CameraInfo: ({ + required CameraInfo cameraInfo, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + mockCamera2CameraInfo, + newSystemServicesManager: ({ + required void Function(SystemServicesManager, String) onCameraError, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockSystemServicesManager mockSystemServicesManager = + MockSystemServicesManager(); + when( + mockSystemServicesManager.getTempFilePath( + camera.videoPrefix, + '.temp', + ), + ).thenAnswer((_) async => outputPath); + return mockSystemServicesManager; + }, + newVideoRecordEventListener: ({ + required void Function(VideoRecordEventListener, VideoRecordEvent) + onEvent, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return VideoRecordEventListener.pigeon_detached( + onEvent: onEvent, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + infoSupportedHardwareLevelCameraCharacteristics: () { + return MockCameraCharacteristicsKey(); + }, + ); + + const int cameraId = 17; + + // Mock method calls. + when( + camera.recorder!.prepareRecording(outputPath), + ).thenAnswer((_) async => mockPendingRecording); + when( + mockPendingRecording.start(any), + ).thenAnswer((_) async => mockRecording); + when( + camera.processCameraProvider!.isBound(camera.videoCapture!), + ).thenAnswer((_) async => false); + when( + camera.processCameraProvider!.bindToLifecycle( + camera.cameraSelector!, + [camera.videoCapture!], + ), + ).thenAnswer((_) async => mockCamera); + when( + mockCamera.getCameraInfo(), + ).thenAnswer((_) => Future.value(mockCameraInfo)); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => MockLiveCameraState()); + when( + mockCamera2CameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => InfoSupportedHardwareLevel.limited); + + // Simulate video recording being started so startVideoRecording completes. + AndroidCameraCameraX.videoRecordingEventStreamController.add( + VideoRecordEventStart.pigeon_detached( + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ), + ); - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; + await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); - // Tell plugin to create detached Analyzer for testing. - camera.proxy = CameraXProxy( - createAnalyzer: - (Future Function(ImageProxy imageProxy) analyze) => - Analyzer.detached(analyze: analyze), - getCamera2CameraInfo: (CameraInfo cameraInfo) async => - cameraInfo == initialCameraInfo - ? mockCamera2CameraInfo - : MockCamera2CameraInfo()); + verify( + camera.processCameraProvider!.bindToLifecycle( + camera.cameraSelector!, + [camera.videoCapture!], + ), + ); + expect(camera.pendingRecording, equals(mockPendingRecording)); + expect(camera.recording, mockRecording); + + await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); + // Verify that each of these calls happened only once. + verify( + camera.systemServicesManager.getTempFilePath( + camera.videoPrefix, + '.temp', + ), + ).called(1); + verifyNoMoreInteractions(camera.systemServicesManager); + verify(camera.recorder!.prepareRecording(outputPath)).called(1); + verifyNoMoreInteractions(camera.recorder); + verify(mockPendingRecording.start(any)).called(1); + verifyNoMoreInteractions(mockPendingRecording); + }, + ); - const int cameraId = 17; - const String outputPath = '/temp/REC123.temp'; - final Completer imageDataCompleter = - Completer(); - final VideoCaptureOptions videoCaptureOptions = VideoCaptureOptions( + test( + 'startVideoCapturing called with stream options starts image streaming', + () async { + // Set up mocks and constants. + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final MockProcessCameraProvider mockProcessCameraProvider = + MockProcessCameraProvider(); + final Recorder mockRecorder = MockRecorder(); + final MockPendingRecording mockPendingRecording = + MockPendingRecording(); + final MockCameraInfo initialCameraInfo = MockCameraInfo(); + final MockCamera2CameraInfo mockCamera2CameraInfo = + MockCamera2CameraInfo(); + + // Set directly for test versus calling createCamera. + + camera.processCameraProvider = mockProcessCameraProvider; + camera.cameraSelector = MockCameraSelector(); + camera.videoCapture = MockVideoCapture(); + camera.imageAnalysis = MockImageAnalysis(); + camera.camera = MockCamera(); + camera.recorder = mockRecorder; + camera.cameraInfo = initialCameraInfo; + camera.imageCapture = MockImageCapture(); + + // Ignore setting target rotation for this test; tested seprately. + camera.captureOrientationLocked = true; + + // Tell plugin to create detached Analyzer for testing. + const String outputPath = '/temp/REC123.temp'; + camera.proxy = CameraXProxy( + newObserver: ({ + required void Function(Observer, T) onChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Observer.detached( + onChanged: onChanged, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + fromCamera2CameraInfo: ({ + required CameraInfo cameraInfo, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + mockCamera2CameraInfo, + newSystemServicesManager: ({ + required void Function(SystemServicesManager, String) onCameraError, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockSystemServicesManager mockSystemServicesManager = + MockSystemServicesManager(); + when( + mockSystemServicesManager.getTempFilePath( + camera.videoPrefix, + '.temp', + ), + ).thenAnswer((_) async => outputPath); + return mockSystemServicesManager; + }, + newVideoRecordEventListener: ({ + required void Function(VideoRecordEventListener, VideoRecordEvent) + onEvent, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return VideoRecordEventListener.pigeon_detached( + onEvent: onEvent, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + infoSupportedHardwareLevelCameraCharacteristics: () { + return MockCameraCharacteristicsKey(); + }, + newAnalyzer: ({ + required void Function(Analyzer, ImageProxy) analyze, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockAnalyzer(); + }, + ); + + const int cameraId = 17; + final Completer imageDataCompleter = + Completer(); + final VideoCaptureOptions videoCaptureOptions = VideoCaptureOptions( cameraId, streamCallback: (CameraImageData imageData) => - imageDataCompleter.complete(imageData)); - - // Mock method calls. - when(camera.processCameraProvider!.isBound(camera.videoCapture!)) - .thenAnswer((_) async => true); - when(camera.processCameraProvider!.isBound(camera.imageAnalysis!)) - .thenAnswer((_) async => true); - when(mockSystemServicesApi.getTempFilePath(camera.videoPrefix, '.temp')) - .thenReturn(outputPath); - when(camera.recorder!.prepareRecording(outputPath)) - .thenAnswer((_) async => mockPendingRecording); - when(mockProcessCameraProvider.bindToLifecycle(any, any)) - .thenAnswer((_) => Future.value(camera.camera)); - when(camera.camera!.getCameraInfo()) - .thenAnswer((_) => Future.value(MockCameraInfo())); - when(mockCamera2CameraInfo.getSupportedHardwareLevel()) - .thenAnswer((_) async => CameraMetadata.infoSupportedHardwareLevel3); - - // Simulate video recording being started so startVideoRecording completes. - PendingRecording.videoRecordingEventStreamController - .add(VideoRecordEvent.start); + imageDataCompleter.complete(imageData), + ); + + // Mock method calls. + when( + camera.processCameraProvider!.isBound(camera.videoCapture!), + ).thenAnswer((_) async => true); + when( + camera.processCameraProvider!.isBound(camera.imageAnalysis!), + ).thenAnswer((_) async => true); + when( + camera.recorder!.prepareRecording(outputPath), + ).thenAnswer((_) async => mockPendingRecording); + when( + mockProcessCameraProvider.bindToLifecycle(any, any), + ).thenAnswer((_) => Future.value(camera.camera)); + when( + camera.camera!.getCameraInfo(), + ).thenAnswer((_) => Future.value(MockCameraInfo())); + when( + mockCamera2CameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => InfoSupportedHardwareLevel.level3); + + // Simulate video recording being started so startVideoRecording completes. + AndroidCameraCameraX.videoRecordingEventStreamController.add( + VideoRecordEventStart.pigeon_detached( + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ), + ); - await camera.startVideoCapturing(videoCaptureOptions); + await camera.startVideoCapturing(videoCaptureOptions); - final CameraImageData mockCameraImageData = MockCameraImageData(); - camera.cameraImageDataStreamController!.add(mockCameraImageData); + final CameraImageData mockCameraImageData = MockCameraImageData(); + camera.cameraImageDataStreamController!.add(mockCameraImageData); - expect(imageDataCompleter.future, isNotNull); - await camera.cameraImageDataStreamController!.close(); - }); + expect(imageDataCompleter.future, isNotNull); + await camera.cameraImageDataStreamController!.close(); + }, + ); test( - 'startVideoCapturing sets VideoCapture target rotation to current video orientation if orientation unlocked', - () async { - // Set up mocks and constants. - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockPendingRecording mockPendingRecording = MockPendingRecording(); - final MockRecording mockRecording = MockRecording(); - final MockVideoCapture mockVideoCapture = MockVideoCapture(); - final MockCameraInfo initialCameraInfo = MockCameraInfo(); - final MockCamera2CameraInfo mockCamera2CameraInfo = - MockCamera2CameraInfo(); - final TestSystemServicesHostApi mockSystemServicesApi = - MockTestSystemServicesHostApi(); - TestSystemServicesHostApi.setup(mockSystemServicesApi); - const int defaultTargetRotation = Surface.rotation270; - - // Set directly for test versus calling createCamera. - camera.processCameraProvider = MockProcessCameraProvider(); - camera.camera = MockCamera(); - camera.recorder = MockRecorder(); - camera.videoCapture = mockVideoCapture; - camera.cameraSelector = MockCameraSelector(); - camera.imageAnalysis = MockImageAnalysis(); - camera.cameraInfo = initialCameraInfo; - - // Tell plugin to mock call to get current video orientation and mock Camera2CameraInfo retrieval. - camera.proxy = CameraXProxy( - getDefaultDisplayRotation: () => - Future.value(defaultTargetRotation), - getCamera2CameraInfo: (CameraInfo cameraInfo) async => + 'startVideoCapturing sets VideoCapture target rotation to current video orientation if orientation unlocked', + () async { + // Set up mocks and constants. + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final MockPendingRecording mockPendingRecording = + MockPendingRecording(); + final MockRecording mockRecording = MockRecording(); + final MockVideoCapture mockVideoCapture = MockVideoCapture(); + final MockCameraInfo initialCameraInfo = MockCameraInfo(); + final MockCamera2CameraInfo mockCamera2CameraInfo = + MockCamera2CameraInfo(); + const int defaultTargetRotation = Surface.rotation270; + + // Set directly for test versus calling createCamera. + camera.processCameraProvider = MockProcessCameraProvider(); + camera.camera = MockCamera(); + camera.recorder = MockRecorder(); + camera.videoCapture = mockVideoCapture; + camera.cameraSelector = MockCameraSelector(); + camera.imageAnalysis = MockImageAnalysis(); + camera.cameraInfo = initialCameraInfo; + + // Tell plugin to mock call to get current video orientation and mock Camera2CameraInfo retrieval. + const String outputPath = '/temp/REC123.temp'; + camera.proxy = CameraXProxy( + newObserver: ({ + required void Function(Observer, T) onChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Observer.detached( + onChanged: onChanged, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + fromCamera2CameraInfo: ({ + required CameraInfo cameraInfo, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => cameraInfo == initialCameraInfo ? mockCamera2CameraInfo - : MockCamera2CameraInfo()); - - const int cameraId = 87; - const String outputPath = '/temp/REC123.temp'; - - // Mock method calls. - when(mockSystemServicesApi.getTempFilePath(camera.videoPrefix, '.temp')) - .thenReturn(outputPath); - when(camera.recorder!.prepareRecording(outputPath)) - .thenAnswer((_) async => mockPendingRecording); - when(mockPendingRecording.start()).thenAnswer((_) async => mockRecording); - when(camera.processCameraProvider!.isBound(camera.videoCapture!)) - .thenAnswer((_) async => true); - when(camera.processCameraProvider!.isBound(camera.imageAnalysis!)) - .thenAnswer((_) async => false); - - // Simulate video recording being started so startVideoRecording completes. - PendingRecording.videoRecordingEventStreamController - .add(VideoRecordEvent.start); - - // Orientation is unlocked and plugin does not need to set default target - // rotation manually. - camera.recording = null; - await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); - verifyNever(mockVideoCapture.setTargetRotation(any)); - - // Simulate video recording being started so startVideoRecording completes. - PendingRecording.videoRecordingEventStreamController - .add(VideoRecordEvent.start); - - // Orientation is locked and plugin does not need to set default target - // rotation manually. - camera.recording = null; - camera.captureOrientationLocked = true; - await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); - verifyNever(mockVideoCapture.setTargetRotation(any)); - - // Simulate video recording being started so startVideoRecording completes. - PendingRecording.videoRecordingEventStreamController - .add(VideoRecordEvent.start); - - // Orientation is locked and plugin does need to set default target - // rotation manually. - camera.recording = null; - camera.captureOrientationLocked = true; - camera.shouldSetDefaultRotation = true; - await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); - verifyNever(mockVideoCapture.setTargetRotation(any)); - - // Simulate video recording being started so startVideoRecording completes. - PendingRecording.videoRecordingEventStreamController - .add(VideoRecordEvent.start); - - // Orientation is unlocked and plugin does need to set default target - // rotation manually. - camera.recording = null; - camera.captureOrientationLocked = false; - camera.shouldSetDefaultRotation = true; - await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); - verify(mockVideoCapture.setTargetRotation(defaultTargetRotation)); - }); + : MockCamera2CameraInfo(), + newSystemServicesManager: ({ + required void Function(SystemServicesManager, String) onCameraError, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockSystemServicesManager mockSystemServicesManager = + MockSystemServicesManager(); + when( + mockSystemServicesManager.getTempFilePath( + camera.videoPrefix, + '.temp', + ), + ).thenAnswer((_) async => outputPath); + return mockSystemServicesManager; + }, + newDeviceOrientationManager: ({ + required void Function(DeviceOrientationManager, String) + onDeviceOrientationChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockDeviceOrientationManager mockDeviceOrientationManager = + MockDeviceOrientationManager(); + when( + mockDeviceOrientationManager.getDefaultDisplayRotation(), + ).thenAnswer((_) async => defaultTargetRotation); + return mockDeviceOrientationManager; + }, + newVideoRecordEventListener: ({ + required void Function(VideoRecordEventListener, VideoRecordEvent) + onEvent, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return VideoRecordEventListener.pigeon_detached( + onEvent: onEvent, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + infoSupportedHardwareLevelCameraCharacteristics: () { + return MockCameraCharacteristicsKey(); + }, + ); + + const int cameraId = 87; + + // Mock method calls. + when( + camera.recorder!.prepareRecording(outputPath), + ).thenAnswer((_) async => mockPendingRecording); + when( + mockPendingRecording.start(any), + ).thenAnswer((_) async => mockRecording); + when( + camera.processCameraProvider!.isBound(camera.videoCapture!), + ).thenAnswer((_) async => true); + when( + camera.processCameraProvider!.isBound(camera.imageAnalysis!), + ).thenAnswer((_) async => false); + when( + mockCamera2CameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => InfoSupportedHardwareLevel.limited); + + // Simulate video recording being started so startVideoRecording completes. + AndroidCameraCameraX.videoRecordingEventStreamController.add( + VideoRecordEventStart.pigeon_detached( + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ), + ); + + // Orientation is unlocked and plugin does not need to set default target + // rotation manually. + camera.recording = null; + await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); + verifyNever(mockVideoCapture.setTargetRotation(any)); + + // Simulate video recording being started so startVideoRecording completes. + AndroidCameraCameraX.videoRecordingEventStreamController.add( + VideoRecordEventStart.pigeon_detached( + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ), + ); + + // Orientation is locked and plugin does not need to set default target + // rotation manually. + camera.recording = null; + camera.captureOrientationLocked = true; + await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); + verifyNever(mockVideoCapture.setTargetRotation(any)); + + // Simulate video recording being started so startVideoRecording completes. + AndroidCameraCameraX.videoRecordingEventStreamController.add( + VideoRecordEventStart.pigeon_detached( + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ), + ); + + // Orientation is locked and plugin does need to set default target + // rotation manually. + camera.recording = null; + camera.captureOrientationLocked = true; + camera.shouldSetDefaultRotation = true; + await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); + verifyNever(mockVideoCapture.setTargetRotation(any)); + + // Simulate video recording being started so startVideoRecording completes. + AndroidCameraCameraX.videoRecordingEventStreamController.add( + VideoRecordEventStart.pigeon_detached( + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ), + ); + + // Orientation is unlocked and plugin does need to set default target + // rotation manually. + camera.recording = null; + camera.captureOrientationLocked = false; + camera.shouldSetDefaultRotation = true; + await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); + verify(mockVideoCapture.setTargetRotation(defaultTargetRotation)); + }, + ); test('pauseVideoRecording pauses the recording', () async { final AndroidCameraCameraX camera = AndroidCameraCameraX(); @@ -1696,12 +3209,18 @@ void main() { camera.videoOutputPath = videoOutputPath; // Tell plugin that videoCapture use case was bound to start recording. - when(camera.processCameraProvider!.isBound(videoCapture)) - .thenAnswer((_) async => true); + when( + camera.processCameraProvider!.isBound(videoCapture), + ).thenAnswer((_) async => true); // Simulate video recording being finalized so stopVideoRecording completes. - PendingRecording.videoRecordingEventStreamController - .add(VideoRecordEvent.finalize); + AndroidCameraCameraX.videoRecordingEventStreamController.add( + VideoRecordEventFinalize.pigeon_detached( + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ), + ); final XFile file = await camera.stopVideoRecording(0); expect(file.path, videoOutputPath); @@ -1740,13 +3259,19 @@ void main() { camera.videoCapture = mockVideoCapture; // Tell plugin that videoCapture use case was bound to start recording. - when(camera.processCameraProvider!.isBound(mockVideoCapture)) - .thenAnswer((_) async => true); + when( + camera.processCameraProvider!.isBound(mockVideoCapture), + ).thenAnswer((_) async => true); await expectLater(() async { // Simulate video recording being finalized so stopVideoRecording completes. - PendingRecording.videoRecordingEventStreamController - .add(VideoRecordEvent.finalize); + AndroidCameraCameraX.videoRecordingEventStreamController.add( + VideoRecordEventFinalize.pigeon_detached( + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ), + ); await camera.stopVideoRecording(0); }, throwsA(isA())); expect(camera.recording, null); @@ -1769,8 +3294,13 @@ void main() { camera.videoOutputPath = videoOutputPath; // Simulate video recording being finalized so stopVideoRecording completes. - PendingRecording.videoRecordingEventStreamController - .add(VideoRecordEvent.finalize); + AndroidCameraCameraX.videoRecordingEventStreamController.add( + VideoRecordEventFinalize.pigeon_detached( + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ), + ); final XFile file = await camera.stopVideoRecording(0); expect(file.path, videoOutputPath); @@ -1781,219 +3311,272 @@ void main() { }); test( - 'VideoCapture use case is unbound from lifecycle when video recording stops', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockRecording recording = MockRecording(); - final MockProcessCameraProvider processCameraProvider = - MockProcessCameraProvider(); - final MockVideoCapture videoCapture = MockVideoCapture(); - const String videoOutputPath = '/test/output/path'; - - // Set directly for test versus calling createCamera and startVideoCapturing. - camera.processCameraProvider = processCameraProvider; - camera.recording = recording; - camera.videoCapture = videoCapture; - camera.videoOutputPath = videoOutputPath; - - // Tell plugin that videoCapture use case was bound to start recording. - when(camera.processCameraProvider!.isBound(videoCapture)) - .thenAnswer((_) async => true); + 'VideoCapture use case is unbound from lifecycle when video recording stops', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final MockRecording recording = MockRecording(); + final MockProcessCameraProvider processCameraProvider = + MockProcessCameraProvider(); + final MockVideoCapture videoCapture = MockVideoCapture(); + const String videoOutputPath = '/test/output/path'; + + // Set directly for test versus calling createCamera and startVideoCapturing. + camera.processCameraProvider = processCameraProvider; + camera.recording = recording; + camera.videoCapture = videoCapture; + camera.videoOutputPath = videoOutputPath; + + // Tell plugin that videoCapture use case was bound to start recording. + when( + camera.processCameraProvider!.isBound(videoCapture), + ).thenAnswer((_) async => true); - // Simulate video recording being finalized so stopVideoRecording completes. - PendingRecording.videoRecordingEventStreamController - .add(VideoRecordEvent.finalize); + // Simulate video recording being finalized so stopVideoRecording completes. + AndroidCameraCameraX.videoRecordingEventStreamController.add( + VideoRecordEventFinalize.pigeon_detached( + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ), + ); - await camera.stopVideoRecording(90); - verify(processCameraProvider.unbind([videoCapture])); + await camera.stopVideoRecording(90); + verify(processCameraProvider.unbind([videoCapture])); - // Verify that recording stops. - verify(recording.close()); - verifyNoMoreInteractions(recording); - }); + // Verify that recording stops. + verify(recording.close()); + verifyNoMoreInteractions(recording); + }, + ); test( - 'setDescriptionWhileRecording does not make any calls involving starting video recording', - () async { - // TODO(camsim99): Modify test when implemented, see https://github.com/flutter/flutter/issues/148013. + 'setDescriptionWhileRecording does not make any calls involving starting video recording', + () async { + // TODO(camsim99): Modify test when implemented, see https://github.com/flutter/flutter/issues/148013. + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + + // Set directly for test versus calling createCamera. + camera.processCameraProvider = MockProcessCameraProvider(); + camera.recorder = MockRecorder(); + camera.videoCapture = MockVideoCapture(); + camera.camera = MockCamera(); + + await camera.setDescriptionWhileRecording( + const CameraDescription( + name: 'fakeCameraName', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ); + verifyNoMoreInteractions(camera.processCameraProvider); + verifyNoMoreInteractions(camera.recorder); + verifyNoMoreInteractions(camera.videoCapture); + verifyNoMoreInteractions(camera.camera); + }, + ); + }); + + test( + 'takePicture binds ImageCapture to lifecycle and makes call to take a picture', + () async { final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final MockProcessCameraProvider mockProcessCameraProvider = + MockProcessCameraProvider(); + final MockCamera mockCamera = MockCamera(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); + const String testPicturePath = 'test/absolute/path/to/picture'; // Set directly for test versus calling createCamera. - camera.processCameraProvider = MockProcessCameraProvider(); - camera.recorder = MockRecorder(); - camera.videoCapture = MockVideoCapture(); - camera.camera = MockCamera(); + camera.imageCapture = MockImageCapture(); + camera.processCameraProvider = mockProcessCameraProvider; + camera.cameraSelector = MockCameraSelector(); - await camera.setDescriptionWhileRecording(const CameraDescription( - name: 'fakeCameraName', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90)); - verifyNoMoreInteractions(camera.processCameraProvider); - verifyNoMoreInteractions(camera.recorder); - verifyNoMoreInteractions(camera.videoCapture); - verifyNoMoreInteractions(camera.camera); - }); - }); + // Ignore setting target rotation for this test; tested seprately. + camera.captureOrientationLocked = true; - test( - 'takePicture binds ImageCapture to lifecycle and makes call to take a picture', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockCamera mockCamera = MockCamera(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - const String testPicturePath = 'test/absolute/path/to/picture'; + // Tell plugin to create detached camera state observers. + camera.proxy = CameraXProxy( + newObserver: ({ + required void Function(Observer, T) onChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Observer.detached( + onChanged: onChanged, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + ); - // Set directly for test versus calling createCamera. - camera.imageCapture = MockImageCapture(); - camera.processCameraProvider = mockProcessCameraProvider; - camera.cameraSelector = MockCameraSelector(); + when( + mockProcessCameraProvider.isBound(camera.imageCapture), + ).thenAnswer((_) async => false); + when( + mockProcessCameraProvider.bindToLifecycle( + camera.cameraSelector, + [camera.imageCapture!], + ), + ).thenAnswer((_) async => mockCamera); + when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => MockLiveCameraState()); + when( + camera.imageCapture!.takePicture(), + ).thenAnswer((_) async => testPicturePath); - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; + final XFile imageFile = await camera.takePicture(3); - // Tell plugin to create detached camera state observers. - camera.proxy = CameraXProxy( - createCameraStateObserver: (void Function(Object) onChanged) => - Observer.detached(onChanged: onChanged)); - - when(mockProcessCameraProvider.isBound(camera.imageCapture)) - .thenAnswer((_) async => false); - when(mockProcessCameraProvider.bindToLifecycle( - camera.cameraSelector, [camera.imageCapture!])) - .thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => MockLiveCameraState()); - when(camera.imageCapture!.takePicture()) - .thenAnswer((_) async => testPicturePath); + expect(imageFile.path, equals(testPicturePath)); + }, + ); - final XFile imageFile = await camera.takePicture(3); + test( + 'takePicture sets ImageCapture target rotation to currrent photo rotation when orientation unlocked', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final MockImageCapture mockImageCapture = MockImageCapture(); + final MockProcessCameraProvider mockProcessCameraProvider = + MockProcessCameraProvider(); - expect(imageFile.path, equals(testPicturePath)); - }); + const int cameraId = 3; + const int defaultTargetRotation = Surface.rotation180; - test( - 'takePicture sets ImageCapture target rotation to currrent photo rotation when orientation unlocked', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockImageCapture mockImageCapture = MockImageCapture(); - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); + // Set directly for test versus calling createCamera. + camera.imageCapture = mockImageCapture; + camera.processCameraProvider = mockProcessCameraProvider; - const int cameraId = 3; - const int defaultTargetRotation = Surface.rotation180; + // Tell plugin to mock call to get current photo orientation. + camera.proxy = CameraXProxy( + newDeviceOrientationManager: ({ + required void Function(DeviceOrientationManager, String) + onDeviceOrientationChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockDeviceOrientationManager mockDeviceOrientationManager = + MockDeviceOrientationManager(); + when( + mockDeviceOrientationManager.getDefaultDisplayRotation(), + ).thenAnswer((_) async => defaultTargetRotation); + return mockDeviceOrientationManager; + }, + ); - // Set directly for test versus calling createCamera. - camera.imageCapture = mockImageCapture; - camera.processCameraProvider = mockProcessCameraProvider; + when( + mockProcessCameraProvider.isBound(camera.imageCapture), + ).thenAnswer((_) async => true); + when( + camera.imageCapture!.takePicture(), + ).thenAnswer((_) async => 'test/absolute/path/to/picture'); - // Tell plugin to mock call to get current photo orientation. - camera.proxy = CameraXProxy( - getDefaultDisplayRotation: () => - Future.value(defaultTargetRotation)); - - when(mockProcessCameraProvider.isBound(camera.imageCapture)) - .thenAnswer((_) async => true); - when(camera.imageCapture!.takePicture()) - .thenAnswer((_) async => 'test/absolute/path/to/picture'); - - // Orientation is unlocked and plugin does not need to set default target - // rotation manually. - await camera.takePicture(cameraId); - verifyNever(mockImageCapture.setTargetRotation(any)); - - // Orientation is locked and plugin does not need to set default target - // rotation manually. - camera.captureOrientationLocked = true; - await camera.takePicture(cameraId); - verifyNever(mockImageCapture.setTargetRotation(any)); - - // Orientation is locked and plugin does need to set default target - // rotation manually. - camera.captureOrientationLocked = true; - camera.shouldSetDefaultRotation = true; - await camera.takePicture(cameraId); - verifyNever(mockImageCapture.setTargetRotation(any)); - - // Orientation is unlocked and plugin does need to set default target - // rotation manually. - camera.captureOrientationLocked = false; - camera.shouldSetDefaultRotation = true; - await camera.takePicture(cameraId); - verify(mockImageCapture.setTargetRotation(defaultTargetRotation)); - }); + // Orientation is unlocked and plugin does not need to set default target + // rotation manually. + await camera.takePicture(cameraId); + verifyNever(mockImageCapture.setTargetRotation(any)); - test('takePicture turns non-torch flash mode off when torch mode enabled', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - const int cameraId = 77; + // Orientation is locked and plugin does not need to set default target + // rotation manually. + camera.captureOrientationLocked = true; + await camera.takePicture(cameraId); + verifyNever(mockImageCapture.setTargetRotation(any)); - // Set directly for test versus calling createCamera. - camera.imageCapture = MockImageCapture(); - camera.cameraControl = MockCameraControl(); - camera.processCameraProvider = mockProcessCameraProvider; + // Orientation is locked and plugin does need to set default target + // rotation manually. + camera.captureOrientationLocked = true; + camera.shouldSetDefaultRotation = true; + await camera.takePicture(cameraId); + verifyNever(mockImageCapture.setTargetRotation(any)); + + // Orientation is unlocked and plugin does need to set default target + // rotation manually. + camera.captureOrientationLocked = false; + camera.shouldSetDefaultRotation = true; + await camera.takePicture(cameraId); + verify(mockImageCapture.setTargetRotation(defaultTargetRotation)); + }, + ); - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; + test( + 'takePicture turns non-torch flash mode off when torch mode enabled', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final MockProcessCameraProvider mockProcessCameraProvider = + MockProcessCameraProvider(); + const int cameraId = 77; - when(mockProcessCameraProvider.isBound(camera.imageCapture)) - .thenAnswer((_) async => true); + // Set directly for test versus calling createCamera. + camera.imageCapture = MockImageCapture(); + camera.cameraControl = MockCameraControl(); + camera.processCameraProvider = mockProcessCameraProvider; - await camera.setFlashMode(cameraId, FlashMode.torch); - await camera.takePicture(cameraId); - verify(camera.imageCapture!.setFlashMode(ImageCapture.flashModeOff)); - }); + // Ignore setting target rotation for this test; tested seprately. + camera.captureOrientationLocked = true; + + when( + mockProcessCameraProvider.isBound(camera.imageCapture), + ).thenAnswer((_) async => true); + + await camera.setFlashMode(cameraId, FlashMode.torch); + await camera.takePicture(cameraId); + verify(camera.imageCapture!.setFlashMode(CameraXFlashMode.off)); + }, + ); test( - 'setFlashMode configures ImageCapture with expected non-torch flash mode', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 22; - final MockCameraControl mockCameraControl = MockCameraControl(); - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); + 'setFlashMode configures ImageCapture with expected non-torch flash mode', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 22; + final MockCameraControl mockCameraControl = MockCameraControl(); + final MockProcessCameraProvider mockProcessCameraProvider = + MockProcessCameraProvider(); - // Set directly for test versus calling createCamera. - camera.imageCapture = MockImageCapture(); - camera.cameraControl = mockCameraControl; + // Set directly for test versus calling createCamera. + camera.imageCapture = MockImageCapture(); + camera.cameraControl = mockCameraControl; - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; - camera.processCameraProvider = mockProcessCameraProvider; - - when(mockProcessCameraProvider.isBound(camera.imageCapture)) - .thenAnswer((_) async => true); - - for (final FlashMode flashMode in FlashMode.values) { - await camera.setFlashMode(cameraId, flashMode); - - int? expectedFlashMode; - switch (flashMode) { - case FlashMode.off: - expectedFlashMode = ImageCapture.flashModeOff; - case FlashMode.auto: - expectedFlashMode = ImageCapture.flashModeAuto; - case FlashMode.always: - expectedFlashMode = ImageCapture.flashModeOn; - case FlashMode.torch: - expectedFlashMode = null; - } + // Ignore setting target rotation for this test; tested seprately. + camera.captureOrientationLocked = true; + camera.processCameraProvider = mockProcessCameraProvider; - if (expectedFlashMode == null) { - // Torch mode enabled and won't be used for configuring image capture. - continue; - } + when( + mockProcessCameraProvider.isBound(camera.imageCapture), + ).thenAnswer((_) async => true); + + for (final FlashMode flashMode in FlashMode.values) { + await camera.setFlashMode(cameraId, flashMode); + + CameraXFlashMode? expectedFlashMode; + switch (flashMode) { + case FlashMode.off: + expectedFlashMode = CameraXFlashMode.off; + case FlashMode.auto: + expectedFlashMode = CameraXFlashMode.auto; + case FlashMode.always: + expectedFlashMode = CameraXFlashMode.on; + case FlashMode.torch: + expectedFlashMode = null; + } - verifyNever(mockCameraControl.enableTorch(true)); - expect(camera.torchEnabled, isFalse); - await camera.takePicture(cameraId); - verify(camera.imageCapture!.setFlashMode(expectedFlashMode)); - } - }); + if (expectedFlashMode == null) { + // Torch mode enabled and won't be used for configuring image capture. + continue; + } + + verifyNever(mockCameraControl.enableTorch(true)); + expect(camera.torchEnabled, isFalse); + await camera.takePicture(cameraId); + verify(camera.imageCapture!.setFlashMode(expectedFlashMode)); + } + }, + ); test('setFlashMode turns on torch mode as expected', () async { final AndroidCameraCameraX camera = AndroidCameraCameraX(); @@ -2009,45 +3592,54 @@ void main() { expect(camera.torchEnabled, isTrue); }); - test('setFlashMode turns off torch mode when non-torch flash modes set', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 33; - final MockCameraControl mockCameraControl = MockCameraControl(); - - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; + test( + 'setFlashMode turns off torch mode when non-torch flash modes set', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 33; + final MockCameraControl mockCameraControl = MockCameraControl(); - for (final FlashMode flashMode in FlashMode.values) { - camera.torchEnabled = true; - await camera.setFlashMode(cameraId, flashMode); - - switch (flashMode) { - case FlashMode.off: - case FlashMode.auto: - case FlashMode.always: - verify(mockCameraControl.enableTorch(false)); - expect(camera.torchEnabled, isFalse); - case FlashMode.torch: - verifyNever(mockCameraControl.enableTorch(true)); - expect(camera.torchEnabled, true); + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; + + for (final FlashMode flashMode in FlashMode.values) { + camera.torchEnabled = true; + await camera.setFlashMode(cameraId, flashMode); + + switch (flashMode) { + case FlashMode.off: + case FlashMode.auto: + case FlashMode.always: + verify(mockCameraControl.enableTorch(false)); + expect(camera.torchEnabled, isFalse); + case FlashMode.torch: + verifyNever(mockCameraControl.enableTorch(true)); + expect(camera.torchEnabled, true); + } } - } - }); + }, + ); test('getMinExposureOffset returns expected exposure offset', () async { final AndroidCameraCameraX camera = AndroidCameraCameraX(); final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final ExposureState exposureState = ExposureState.detached( - exposureCompensationRange: - ExposureCompensationRange(minCompensation: 3, maxCompensation: 4), - exposureCompensationStep: 0.2); + final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); + final ExposureState exposureState = ExposureState.pigeon_detached( + exposureCompensationRange: CameraIntegerRange.pigeon_detached( + lower: 3, + upper: 4, + pigeon_instanceManager: testInstanceManager, + ), + exposureCompensationStep: 0.2, + pigeon_instanceManager: testInstanceManager, + ); // Set directly for test versus calling createCamera. camera.cameraInfo = mockCameraInfo; - when(mockCameraInfo.getExposureState()) - .thenAnswer((_) async => exposureState); + when(mockCameraInfo.exposureState).thenReturn(exposureState); // We expect the minimum exposure to be the minimum exposure compensation * exposure compensation step. // Delta is included due to avoid catching rounding errors. @@ -2057,16 +3649,23 @@ void main() { test('getMaxExposureOffset returns expected exposure offset', () async { final AndroidCameraCameraX camera = AndroidCameraCameraX(); final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final ExposureState exposureState = ExposureState.detached( - exposureCompensationRange: - ExposureCompensationRange(minCompensation: 3, maxCompensation: 4), - exposureCompensationStep: 0.2); + final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); + final ExposureState exposureState = ExposureState.pigeon_detached( + exposureCompensationRange: CameraIntegerRange.pigeon_detached( + lower: 3, + upper: 4, + pigeon_instanceManager: testInstanceManager, + ), + exposureCompensationStep: 0.2, + pigeon_instanceManager: testInstanceManager, + ); // Set directly for test versus calling createCamera. camera.cameraInfo = mockCameraInfo; - when(mockCameraInfo.getExposureState()) - .thenAnswer((_) async => exposureState); + when(mockCameraInfo.exposureState).thenReturn(exposureState); // We expect the maximum exposure to be the maximum exposure compensation * exposure compensation step. expect(await camera.getMaxExposureOffset(35), 0.8); @@ -2075,52 +3674,73 @@ void main() { test('getExposureOffsetStepSize returns expected exposure offset', () async { final AndroidCameraCameraX camera = AndroidCameraCameraX(); final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final ExposureState exposureState = ExposureState.detached( - exposureCompensationRange: - ExposureCompensationRange(minCompensation: 3, maxCompensation: 4), - exposureCompensationStep: 0.2); + final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); + final ExposureState exposureState = ExposureState.pigeon_detached( + exposureCompensationRange: CameraIntegerRange.pigeon_detached( + lower: 3, + upper: 4, + pigeon_instanceManager: testInstanceManager, + ), + exposureCompensationStep: 0.2, + pigeon_instanceManager: testInstanceManager, + ); // Set directly for test versus calling createCamera. camera.cameraInfo = mockCameraInfo; - when(mockCameraInfo.getExposureState()) - .thenAnswer((_) async => exposureState); + when(mockCameraInfo.exposureState).thenReturn(exposureState); expect(await camera.getExposureOffsetStepSize(55), 0.2); }); test( - 'getExposureOffsetStepSize returns -1 when exposure compensation not supported on device', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final ExposureState exposureState = ExposureState.detached( - exposureCompensationRange: - ExposureCompensationRange(minCompensation: 0, maxCompensation: 0), - exposureCompensationStep: 0); + 'getExposureOffsetStepSize returns -1 when exposure compensation not supported on device', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); + final ExposureState exposureState = ExposureState.pigeon_detached( + exposureCompensationRange: CameraIntegerRange.pigeon_detached( + lower: 0, + upper: 0, + pigeon_instanceManager: testInstanceManager, + ), + exposureCompensationStep: 0, + pigeon_instanceManager: testInstanceManager, + ); - // Set directly for test versus calling createCamera. - camera.cameraInfo = mockCameraInfo; + // Set directly for test versus calling createCamera. + camera.cameraInfo = mockCameraInfo; - when(mockCameraInfo.getExposureState()) - .thenAnswer((_) async => exposureState); + when(mockCameraInfo.exposureState).thenReturn(exposureState); - expect(await camera.getExposureOffsetStepSize(55), -1); - }); + expect(await camera.getExposureOffsetStepSize(55), -1); + }, + ); test('getMaxZoomLevel returns expected exposure offset', () async { final AndroidCameraCameraX camera = AndroidCameraCameraX(); final MockCameraInfo mockCameraInfo = MockCameraInfo(); const double maxZoomRatio = 1; final LiveData mockLiveZoomState = MockLiveZoomState(); - final ZoomState zoomState = - ZoomState.detached(maxZoomRatio: maxZoomRatio, minZoomRatio: 0); + final ZoomState zoomState = ZoomState.pigeon_detached( + maxZoomRatio: maxZoomRatio, + minZoomRatio: 0, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); // Set directly for test versus calling createCamera. camera.cameraInfo = mockCameraInfo; - when(mockCameraInfo.getZoomState()) - .thenAnswer((_) async => mockLiveZoomState); + when( + mockCameraInfo.getZoomState(), + ).thenAnswer((_) async => mockLiveZoomState); when(mockLiveZoomState.getValue()).thenAnswer((_) async => zoomState); expect(await camera.getMaxZoomLevel(55), maxZoomRatio); @@ -2131,14 +3751,20 @@ void main() { final MockCameraInfo mockCameraInfo = MockCameraInfo(); const double minZoomRatio = 0; final LiveData mockLiveZoomState = MockLiveZoomState(); - final ZoomState zoomState = - ZoomState.detached(maxZoomRatio: 1, minZoomRatio: minZoomRatio); + final ZoomState zoomState = ZoomState.pigeon_detached( + maxZoomRatio: 1, + minZoomRatio: minZoomRatio, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); // Set directly for test versus calling createCamera. camera.cameraInfo = mockCameraInfo; - when(mockCameraInfo.getZoomState()) - .thenAnswer((_) async => mockLiveZoomState); + when( + mockCameraInfo.getZoomState(), + ).thenAnswer((_) async => mockLiveZoomState); when(mockLiveZoomState.getValue()).thenAnswer((_) async => zoomState); expect(await camera.getMinZoomLevel(55), minZoomRatio); @@ -2164,2063 +3790,3121 @@ void main() { }); test( - 'onStreamedFrameAvailable emits CameraImageData when picked up from CameraImageData stream controller', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockCamera mockCamera = MockCamera(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - const int cameraId = 22; + 'onStreamedFrameAvailable emits CameraImageData when picked up from CameraImageData stream controller', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final MockProcessCameraProvider mockProcessCameraProvider = + MockProcessCameraProvider(); + final MockCamera mockCamera = MockCamera(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); + const int cameraId = 22; - // Tell plugin to create detached Analyzer for testing. - camera.proxy = CameraXProxy( - createAnalyzer: - (Future Function(ImageProxy imageProxy) analyze) => - Analyzer.detached(analyze: analyze)); + // Tell plugin to create detached Analyzer for testing. + camera.proxy = CameraXProxy( + newAnalyzer: ({ + required void Function(Analyzer, ImageProxy) analyze, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Analyzer.pigeon_detached( + analyze: analyze, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + ); - // Set directly for test versus calling createCamera. - camera.processCameraProvider = mockProcessCameraProvider; - camera.cameraSelector = MockCameraSelector(); - camera.imageAnalysis = MockImageAnalysis(); - - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; - - when(mockProcessCameraProvider.bindToLifecycle(any, any)) - .thenAnswer((_) => Future.value(mockCamera)); - when(mockProcessCameraProvider.isBound(camera.imageAnalysis)) - .thenAnswer((_) async => true); - when(mockCamera.getCameraInfo()) - .thenAnswer((_) => Future.value(mockCameraInfo)); - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => MockLiveCameraState()); - - final CameraImageData mockCameraImageData = MockCameraImageData(); - final Stream imageStream = - camera.onStreamedFrameAvailable(cameraId); - final StreamQueue streamQueue = - StreamQueue(imageStream); - - camera.cameraImageDataStreamController!.add(mockCameraImageData); - - expect(await streamQueue.next, equals(mockCameraImageData)); - await streamQueue.cancel(); - }); + // Set directly for test versus calling createCamera. + camera.processCameraProvider = mockProcessCameraProvider; + camera.cameraSelector = MockCameraSelector(); + camera.imageAnalysis = MockImageAnalysis(); + + // Ignore setting target rotation for this test; tested seprately. + camera.captureOrientationLocked = true; + + when( + mockProcessCameraProvider.bindToLifecycle(any, any), + ).thenAnswer((_) => Future.value(mockCamera)); + when( + mockProcessCameraProvider.isBound(camera.imageAnalysis), + ).thenAnswer((_) async => true); + when( + mockCamera.getCameraInfo(), + ).thenAnswer((_) => Future.value(mockCameraInfo)); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => MockLiveCameraState()); + + final CameraImageData mockCameraImageData = MockCameraImageData(); + final Stream imageStream = + camera.onStreamedFrameAvailable(cameraId); + final StreamQueue streamQueue = + StreamQueue(imageStream); + + camera.cameraImageDataStreamController!.add(mockCameraImageData); + + expect(await streamQueue.next, equals(mockCameraImageData)); + await streamQueue.cancel(); + }, + ); test( - 'onStreamedFrameAvailable emits CameraImageData when listened to after cancelation', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - const int cameraId = 22; + 'onStreamedFrameAvailable emits CameraImageData when listened to after cancelation', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final MockProcessCameraProvider mockProcessCameraProvider = + MockProcessCameraProvider(); + const int cameraId = 22; - // Tell plugin to create detached Analyzer for testing. - camera.proxy = CameraXProxy( - createAnalyzer: - (Future Function(ImageProxy imageProxy) analyze) => - Analyzer.detached(analyze: analyze)); + // Tell plugin to create detached Analyzer for testing. + camera.proxy = CameraXProxy( + newAnalyzer: ({ + required void Function(Analyzer, ImageProxy) analyze, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Analyzer.pigeon_detached( + analyze: analyze, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + ); - // Set directly for test versus calling createCamera. - camera.processCameraProvider = mockProcessCameraProvider; - camera.cameraSelector = MockCameraSelector(); - camera.imageAnalysis = MockImageAnalysis(); + // Set directly for test versus calling createCamera. + camera.processCameraProvider = mockProcessCameraProvider; + camera.cameraSelector = MockCameraSelector(); + camera.imageAnalysis = MockImageAnalysis(); - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; + // Ignore setting target rotation for this test; tested seprately. + camera.captureOrientationLocked = true; - when(mockProcessCameraProvider.isBound(camera.imageAnalysis)) - .thenAnswer((_) async => true); + when( + mockProcessCameraProvider.isBound(camera.imageAnalysis), + ).thenAnswer((_) async => true); - final CameraImageData mockCameraImageData = MockCameraImageData(); - final Stream imageStream = - camera.onStreamedFrameAvailable(cameraId); + final CameraImageData mockCameraImageData = MockCameraImageData(); + final Stream imageStream = + camera.onStreamedFrameAvailable(cameraId); - // Listen to image stream. - final StreamSubscription imageStreamSubscription = - imageStream.listen((CameraImageData data) {}); + // Listen to image stream. + final StreamSubscription imageStreamSubscription = + imageStream.listen((CameraImageData data) {}); - // Cancel subscription to image stream. - await imageStreamSubscription.cancel(); - final Stream imageStream2 = - camera.onStreamedFrameAvailable(cameraId); + // Cancel subscription to image stream. + await imageStreamSubscription.cancel(); + final Stream imageStream2 = + camera.onStreamedFrameAvailable(cameraId); - // Listen to image stream again. - final StreamQueue streamQueue = - StreamQueue(imageStream2); - camera.cameraImageDataStreamController!.add(mockCameraImageData); + // Listen to image stream again. + final StreamQueue streamQueue = + StreamQueue(imageStream2); + camera.cameraImageDataStreamController!.add(mockCameraImageData); - expect(await streamQueue.next, equals(mockCameraImageData)); - await streamQueue.cancel(); - }); + expect(await streamQueue.next, equals(mockCameraImageData)); + await streamQueue.cancel(); + }, + ); test( - 'onStreamedFrameAvailable returns stream that responds expectedly to being listened to', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 33; - final ProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final CameraSelector mockCameraSelector = MockCameraSelector(); - final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); - final Camera mockCamera = MockCamera(); - final CameraInfo mockCameraInfo = MockCameraInfo(); - final MockImageProxy mockImageProxy = MockImageProxy(); - final MockPlaneProxy mockPlane = MockPlaneProxy(); - final List mockPlanes = [mockPlane]; - final Uint8List buffer = Uint8List(0); - const int pixelStride = 27; - const int rowStride = 58; - const int imageFormat = 582; - const int imageHeight = 100; - const int imageWidth = 200; - - // Tell plugin to create detached Analyzer for testing. - camera.proxy = CameraXProxy( - createAnalyzer: - (Future Function(ImageProxy imageProxy) analyze) => - Analyzer.detached(analyze: analyze), - createCameraStateObserver: (void Function(Object) onChanged) => - Observer.detached(onChanged: onChanged)); - - // Set directly for test versus calling createCamera. - camera.processCameraProvider = mockProcessCameraProvider; - camera.cameraSelector = mockCameraSelector; - camera.imageAnalysis = mockImageAnalysis; - - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; - - when(mockProcessCameraProvider.isBound(mockImageAnalysis)) - .thenAnswer((_) async => false); - when(mockProcessCameraProvider - .bindToLifecycle(mockCameraSelector, [mockImageAnalysis])) - .thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => MockLiveCameraState()); - when(mockImageProxy.getPlanes()) - .thenAnswer((_) async => Future>.value(mockPlanes)); - when(mockPlane.buffer).thenReturn(buffer); - when(mockPlane.rowStride).thenReturn(rowStride); - when(mockPlane.pixelStride).thenReturn(pixelStride); - when(mockImageProxy.format).thenReturn(imageFormat); - when(mockImageProxy.height).thenReturn(imageHeight); - when(mockImageProxy.width).thenReturn(imageWidth); - - final Completer imageDataCompleter = - Completer(); - final StreamSubscription - onStreamedFrameAvailableSubscription = camera - .onStreamedFrameAvailable(cameraId) - .listen((CameraImageData imageData) { - imageDataCompleter.complete(imageData); - }); + 'onStreamedFrameAvailable returns stream that responds expectedly to being listened to', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 33; + final ProcessCameraProvider mockProcessCameraProvider = + MockProcessCameraProvider(); + final CameraSelector mockCameraSelector = MockCameraSelector(); + final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); + final Camera mockCamera = MockCamera(); + final CameraInfo mockCameraInfo = MockCameraInfo(); + final MockImageProxy mockImageProxy = MockImageProxy(); + final MockPlaneProxy mockPlane = MockPlaneProxy(); + final List mockPlanes = [mockPlane]; + final Uint8List buffer = Uint8List(0); + const int pixelStride = 27; + const int rowStride = 58; + const int imageFormat = 582; + const int imageHeight = 100; + const int imageWidth = 200; - // Test ImageAnalysis use case is bound to ProcessCameraProvider. - await untilCalled(mockImageAnalysis.setAnalyzer(any)); - final Analyzer capturedAnalyzer = - verify(mockImageAnalysis.setAnalyzer(captureAny)).captured.single - as Analyzer; + // Tell plugin to create detached Analyzer for testing. + camera.proxy = CameraXProxy( + newAnalyzer: ({ + required void Function(Analyzer, ImageProxy) analyze, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Analyzer.pigeon_detached( + analyze: analyze, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + newObserver: ({ + required void Function(Observer, T) onChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Observer.detached( + onChanged: onChanged, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + ); - await capturedAnalyzer.analyze(mockImageProxy); + // Set directly for test versus calling createCamera. + camera.processCameraProvider = mockProcessCameraProvider; + camera.cameraSelector = mockCameraSelector; + camera.imageAnalysis = mockImageAnalysis; - final CameraImageData imageData = await imageDataCompleter.future; + // Ignore setting target rotation for this test; tested seprately. + camera.captureOrientationLocked = true; - // Test Analyzer correctly process ImageProxy instances. - expect(imageData.planes.length, equals(1)); - expect(imageData.planes[0].bytes, equals(buffer)); - expect(imageData.planes[0].bytesPerRow, equals(rowStride)); - expect(imageData.planes[0].bytesPerPixel, equals(pixelStride)); - expect(imageData.format.raw, equals(imageFormat)); - expect(imageData.height, equals(imageHeight)); - expect(imageData.width, equals(imageWidth)); + when( + mockProcessCameraProvider.isBound(mockImageAnalysis), + ).thenAnswer((_) async => false); + when( + mockProcessCameraProvider.bindToLifecycle(mockCameraSelector, [ + mockImageAnalysis, + ]), + ).thenAnswer((_) async => mockCamera); + when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => MockLiveCameraState()); + when( + mockImageProxy.getPlanes(), + ).thenAnswer((_) async => Future>.value(mockPlanes)); + when(mockPlane.buffer).thenReturn(buffer); + when(mockPlane.rowStride).thenReturn(rowStride); + when(mockPlane.pixelStride).thenReturn(pixelStride); + when(mockImageProxy.format).thenReturn(imageFormat); + when(mockImageProxy.height).thenReturn(imageHeight); + when(mockImageProxy.width).thenReturn(imageWidth); - await onStreamedFrameAvailableSubscription.cancel(); - }); + final Completer imageDataCompleter = + Completer(); + final StreamSubscription + onStreamedFrameAvailableSubscription = camera + .onStreamedFrameAvailable(cameraId) + .listen((CameraImageData imageData) { + imageDataCompleter.complete(imageData); + }); + + // Test ImageAnalysis use case is bound to ProcessCameraProvider. + await untilCalled(mockImageAnalysis.setAnalyzer(any)); + final Analyzer capturedAnalyzer = + verify(mockImageAnalysis.setAnalyzer(captureAny)).captured.single + as Analyzer; + + capturedAnalyzer.analyze(MockAnalyzer(), mockImageProxy); + + final CameraImageData imageData = await imageDataCompleter.future; + + // Test Analyzer correctly process ImageProxy instances. + expect(imageData.planes.length, equals(1)); + expect(imageData.planes[0].bytes, equals(buffer)); + expect(imageData.planes[0].bytesPerRow, equals(rowStride)); + expect(imageData.planes[0].bytesPerPixel, equals(pixelStride)); + expect(imageData.format.raw, equals(imageFormat)); + expect(imageData.height, equals(imageHeight)); + expect(imageData.width, equals(imageWidth)); + + await onStreamedFrameAvailableSubscription.cancel(); + }, + ); test( - 'onStreamedFrameAvailable returns stream that responds expectedly to being canceled', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 32; - final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); + 'onStreamedFrameAvailable returns stream that responds expectedly to being canceled', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 32; + final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); + final MockProcessCameraProvider mockProcessCameraProvider = + MockProcessCameraProvider(); - // Set directly for test versus calling createCamera. - camera.imageAnalysis = mockImageAnalysis; - camera.processCameraProvider = mockProcessCameraProvider; + // Set directly for test versus calling createCamera. + camera.imageAnalysis = mockImageAnalysis; + camera.processCameraProvider = mockProcessCameraProvider; - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; + // Ignore setting target rotation for this test; tested seprately. + camera.captureOrientationLocked = true; - // Tell plugin to create a detached analyzer for testing purposes. - camera.proxy = CameraXProxy(createAnalyzer: (_) => MockAnalyzer()); + // Tell plugin to create a detached analyzer for testing purposes. + camera.proxy = CameraXProxy( + newAnalyzer: ({ + required void Function(Analyzer, ImageProxy) analyze, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + MockAnalyzer(), + ); - when(mockProcessCameraProvider.isBound(mockImageAnalysis)) - .thenAnswer((_) async => true); + when( + mockProcessCameraProvider.isBound(mockImageAnalysis), + ).thenAnswer((_) async => true); - final StreamSubscription imageStreamSubscription = camera - .onStreamedFrameAvailable(cameraId) - .listen((CameraImageData data) {}); + final StreamSubscription imageStreamSubscription = camera + .onStreamedFrameAvailable(cameraId) + .listen((CameraImageData data) {}); - await imageStreamSubscription.cancel(); + await imageStreamSubscription.cancel(); - verify(mockImageAnalysis.clearAnalyzer()); - }); + verify(mockImageAnalysis.clearAnalyzer()); + }, + ); test( - 'onStreamedFrameAvailable sets ImageAnalysis target rotation to current photo orientation when orientation unlocked', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 35; - const int defaultTargetRotation = Surface.rotation90; - final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - - // Set directly for test versus calling createCamera. - camera.imageAnalysis = mockImageAnalysis; - camera.processCameraProvider = mockProcessCameraProvider; + 'onStreamedFrameAvailable sets ImageAnalysis target rotation to current photo orientation when orientation unlocked', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 35; + const int defaultTargetRotation = Surface.rotation90; + final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); + final MockProcessCameraProvider mockProcessCameraProvider = + MockProcessCameraProvider(); - // Tell plugin to create a detached analyzer for testing purposes and mock - // call to get current photo orientation. - camera.proxy = CameraXProxy( - createAnalyzer: (_) => MockAnalyzer(), - getDefaultDisplayRotation: () => - Future.value(defaultTargetRotation)); - - when(mockProcessCameraProvider.isBound(mockImageAnalysis)) - .thenAnswer((_) async => true); - - // Orientation is unlocked and plugin does not need to set default target - // rotation manually. - StreamSubscription imageStreamSubscription = camera - .onStreamedFrameAvailable(cameraId) - .listen((CameraImageData data) {}); - await untilCalled(mockImageAnalysis.setAnalyzer(any)); - verifyNever(mockImageAnalysis.setTargetRotation(any)); - await imageStreamSubscription.cancel(); - - // Orientation is locked and plugin does not need to set default target - // rotation manually. - camera.captureOrientationLocked = true; - imageStreamSubscription = camera - .onStreamedFrameAvailable(cameraId) - .listen((CameraImageData data) {}); - await untilCalled(mockImageAnalysis.setAnalyzer(any)); - verifyNever(mockImageAnalysis.setTargetRotation(any)); - await imageStreamSubscription.cancel(); - - // Orientation is locked and plugin does need to set default target - // rotation manually. - camera.captureOrientationLocked = true; - camera.shouldSetDefaultRotation = true; - imageStreamSubscription = camera - .onStreamedFrameAvailable(cameraId) - .listen((CameraImageData data) {}); - await untilCalled(mockImageAnalysis.setAnalyzer(any)); - verifyNever(mockImageAnalysis.setTargetRotation(any)); - await imageStreamSubscription.cancel(); - - // Orientation is unlocked and plugin does need to set default target - // rotation manually. - camera.captureOrientationLocked = false; - camera.shouldSetDefaultRotation = true; - imageStreamSubscription = camera - .onStreamedFrameAvailable(cameraId) - .listen((CameraImageData data) {}); - await untilCalled( - mockImageAnalysis.setTargetRotation(defaultTargetRotation)); - await imageStreamSubscription.cancel(); - }); + // Set directly for test versus calling createCamera. + camera.imageAnalysis = mockImageAnalysis; + camera.processCameraProvider = mockProcessCameraProvider; - test( - 'lockCaptureOrientation sets capture-related use case target rotations to correct orientation', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 44; + // Tell plugin to create a detached analyzer for testing purposes and mock + // call to get current photo orientation. + camera.proxy = CameraXProxy( + newAnalyzer: ({ + required void Function(Analyzer, ImageProxy) analyze, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + MockAnalyzer(), + newDeviceOrientationManager: ({ + required void Function(DeviceOrientationManager, String) + onDeviceOrientationChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockDeviceOrientationManager manager = + MockDeviceOrientationManager(); + when(manager.getDefaultDisplayRotation()).thenAnswer((_) async { + return defaultTargetRotation; + }); + return manager; + }, + ); - final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); - final MockImageCapture mockImageCapture = MockImageCapture(); - final MockVideoCapture mockVideoCapture = MockVideoCapture(); + when( + mockProcessCameraProvider.isBound(mockImageAnalysis), + ).thenAnswer((_) async => true); - // Set directly for test versus calling createCamera. - camera.imageAnalysis = mockImageAnalysis; - camera.imageCapture = mockImageCapture; - camera.videoCapture = mockVideoCapture; - - for (final DeviceOrientation orientation in DeviceOrientation.values) { - int? expectedTargetRotation; - switch (orientation) { - case DeviceOrientation.portraitUp: - expectedTargetRotation = Surface.rotation0; - case DeviceOrientation.landscapeLeft: - expectedTargetRotation = Surface.rotation90; - case DeviceOrientation.portraitDown: - expectedTargetRotation = Surface.rotation180; - case DeviceOrientation.landscapeRight: - expectedTargetRotation = Surface.rotation270; - } + // Orientation is unlocked and plugin does not need to set default target + // rotation manually. + StreamSubscription imageStreamSubscription = camera + .onStreamedFrameAvailable(cameraId) + .listen((CameraImageData data) {}); + await untilCalled(mockImageAnalysis.setAnalyzer(any)); + verifyNever(mockImageAnalysis.setTargetRotation(any)); + await imageStreamSubscription.cancel(); - await camera.lockCaptureOrientation(cameraId, orientation); + // Orientation is locked and plugin does not need to set default target + // rotation manually. + camera.captureOrientationLocked = true; + imageStreamSubscription = camera + .onStreamedFrameAvailable(cameraId) + .listen((CameraImageData data) {}); + await untilCalled(mockImageAnalysis.setAnalyzer(any)); + verifyNever(mockImageAnalysis.setTargetRotation(any)); + await imageStreamSubscription.cancel(); - verify(mockImageAnalysis.setTargetRotation(expectedTargetRotation)); - verify(mockImageCapture.setTargetRotation(expectedTargetRotation)); - verify(mockVideoCapture.setTargetRotation(expectedTargetRotation)); - expect(camera.captureOrientationLocked, isTrue); - expect(camera.shouldSetDefaultRotation, isTrue); + // Orientation is locked and plugin does need to set default target + // rotation manually. + camera.captureOrientationLocked = true; + camera.shouldSetDefaultRotation = true; + imageStreamSubscription = camera + .onStreamedFrameAvailable(cameraId) + .listen((CameraImageData data) {}); + await untilCalled(mockImageAnalysis.setAnalyzer(any)); + verifyNever(mockImageAnalysis.setTargetRotation(any)); + await imageStreamSubscription.cancel(); - // Reset flags for testing. + // Orientation is unlocked and plugin does need to set default target + // rotation manually. camera.captureOrientationLocked = false; - camera.shouldSetDefaultRotation = false; - } - }); + camera.shouldSetDefaultRotation = true; + imageStreamSubscription = camera + .onStreamedFrameAvailable(cameraId) + .listen((CameraImageData data) {}); + await untilCalled( + mockImageAnalysis.setTargetRotation(defaultTargetRotation), + ); + await imageStreamSubscription.cancel(); + }, + ); test( - 'unlockCaptureOrientation sets capture-related use case target rotations to current photo/video orientation', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 57; + 'lockCaptureOrientation sets capture-related use case target rotations to correct orientation', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 44; - camera.captureOrientationLocked = true; - await camera.unlockCaptureOrientation(cameraId); - expect(camera.captureOrientationLocked, isFalse); - }); + final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); + final MockImageCapture mockImageCapture = MockImageCapture(); + final MockVideoCapture mockVideoCapture = MockVideoCapture(); - test('setExposureMode sets expected controlAeLock value via Camera2 interop', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 78; - final MockCameraControl mockCameraControl = MockCameraControl(); - final MockCamera2CameraControl mockCamera2CameraControl = - MockCamera2CameraControl(); + // Set directly for test versus calling createCamera. + camera.imageAnalysis = mockImageAnalysis; + camera.imageCapture = mockImageCapture; + camera.videoCapture = mockVideoCapture; - // Set directly for test versus calling createCamera. - camera.camera = MockCamera(); - camera.cameraControl = mockCameraControl; + for (final DeviceOrientation orientation in DeviceOrientation.values) { + int? expectedTargetRotation; + switch (orientation) { + case DeviceOrientation.portraitUp: + expectedTargetRotation = Surface.rotation0; + case DeviceOrientation.landscapeLeft: + expectedTargetRotation = Surface.rotation90; + case DeviceOrientation.portraitDown: + expectedTargetRotation = Surface.rotation180; + case DeviceOrientation.landscapeRight: + expectedTargetRotation = Surface.rotation270; + } - // Tell plugin to create detached Camera2CameraControl and - // CaptureRequestOptions instances for testing. - camera.proxy = CameraXProxy( - getCamera2CameraControl: (CameraControl cameraControl) => - cameraControl == mockCameraControl - ? mockCamera2CameraControl - : Camera2CameraControl.detached(cameraControl: cameraControl), - createCaptureRequestOptions: - (List<(CaptureRequestKeySupportedType, Object?)> options) => - CaptureRequestOptions.detached(requestedOptions: options), - ); + await camera.lockCaptureOrientation(cameraId, orientation); - // Test auto mode. - await camera.setExposureMode(cameraId, ExposureMode.auto); - - VerificationResult verificationResult = - verify(mockCamera2CameraControl.addCaptureRequestOptions(captureAny)); - CaptureRequestOptions capturedCaptureRequestOptions = - verificationResult.captured.single as CaptureRequestOptions; - List<(CaptureRequestKeySupportedType, Object?)> requestedOptions = - capturedCaptureRequestOptions.requestedOptions; - expect(requestedOptions.length, equals(1)); - expect(requestedOptions.first.$1, - equals(CaptureRequestKeySupportedType.controlAeLock)); - expect(requestedOptions.first.$2, equals(false)); - - // Test locked mode. - clearInteractions(mockCamera2CameraControl); - await camera.setExposureMode(cameraId, ExposureMode.locked); - - verificationResult = - verify(mockCamera2CameraControl.addCaptureRequestOptions(captureAny)); - capturedCaptureRequestOptions = - verificationResult.captured.single as CaptureRequestOptions; - requestedOptions = capturedCaptureRequestOptions.requestedOptions; - expect(requestedOptions.length, equals(1)); - expect(requestedOptions.first.$1, - equals(CaptureRequestKeySupportedType.controlAeLock)); - expect(requestedOptions.first.$2, equals(true)); - }); + verify(mockImageAnalysis.setTargetRotation(expectedTargetRotation)); + verify(mockImageCapture.setTargetRotation(expectedTargetRotation)); + verify(mockVideoCapture.setTargetRotation(expectedTargetRotation)); + expect(camera.captureOrientationLocked, isTrue); + expect(camera.shouldSetDefaultRotation, isTrue); + + // Reset flags for testing. + camera.captureOrientationLocked = false; + camera.shouldSetDefaultRotation = false; + } + }, + ); test( - 'setExposurePoint clears current auto-exposure metering point as expected', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 93; - final MockCameraControl mockCameraControl = MockCameraControl(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); + 'unlockCaptureOrientation sets capture-related use case target rotations to current photo/video orientation', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 57; - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; - camera.cameraInfo = mockCameraInfo; + camera.captureOrientationLocked = true; + await camera.unlockCaptureOrientation(cameraId); + expect(camera.captureOrientationLocked, isFalse); + }, + ); - camera.proxy = getProxyForExposureAndFocus(); + test( + 'setExposureMode sets expected controlAeLock value via Camera2 interop', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 78; + final MockCameraControl mockCameraControl = MockCameraControl(); + final MockCamera2CameraControl mockCamera2CameraControl = + MockCamera2CameraControl(); - // Verify nothing happens if no current focus and metering action has been - // enabled. - await camera.setExposurePoint(cameraId, null); - verifyNever(mockCameraControl.startFocusAndMetering(any)); - verifyNever(mockCameraControl.cancelFocusAndMetering()); + // Set directly for test versus calling createCamera. + camera.camera = MockCamera(); + camera.cameraControl = mockCameraControl; - // Verify current auto-exposure metering point is removed if previously set. - final (MeteringPoint, int?) autofocusMeteringPointInfo = ( - MeteringPoint.detached(x: 0.3, y: 0.7, cameraInfo: mockCameraInfo), - FocusMeteringAction.flagAf - ); - List<(MeteringPoint, int?)> meteringPointInfos = <(MeteringPoint, int?)>[ - ( - MeteringPoint.detached(x: 0.2, y: 0.5, cameraInfo: mockCameraInfo), - FocusMeteringAction.flagAe - ), - autofocusMeteringPointInfo - ]; - - camera.currentFocusMeteringAction = - FocusMeteringAction.detached(meteringPointInfos: meteringPointInfos); - - await camera.setExposurePoint(cameraId, null); - - final VerificationResult verificationResult = - verify(mockCameraControl.startFocusAndMetering(captureAny)); - final FocusMeteringAction capturedAction = - verificationResult.captured.single as FocusMeteringAction; - final List<(MeteringPoint, int?)> capturedMeteringPointInfos = - capturedAction.meteringPointInfos; - expect(capturedMeteringPointInfos.length, equals(1)); - expect( - capturedMeteringPointInfos.first, equals(autofocusMeteringPointInfo)); - - // Verify current focus and metering action is cleared if only previously - // set metering point was for auto-exposure. - meteringPointInfos = <(MeteringPoint, int?)>[ - ( - MeteringPoint.detached(x: 0.2, y: 0.5, cameraInfo: mockCameraInfo), - FocusMeteringAction.flagAe - ) - ]; - camera.currentFocusMeteringAction = - FocusMeteringAction.detached(meteringPointInfos: meteringPointInfos); - - await camera.setExposurePoint(cameraId, null); - - verify(mockCameraControl.cancelFocusAndMetering()); - }); + // Tell plugin to create detached Camera2CameraControl and + // CaptureRequestOptions instances for testing. + final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); + final CaptureRequestKey controlAELockKey = + CaptureRequestKey.pigeon_detached( + pigeon_instanceManager: testInstanceManager, + ); + camera.proxy = CameraXProxy( + fromCamera2CameraControl: ({ + required CameraControl cameraControl, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + cameraControl == mockCameraControl + ? mockCamera2CameraControl + : Camera2CameraControl.pigeon_detached( + pigeon_instanceManager: testInstanceManager, + ), + newCaptureRequestOptions: ({ + required Map options, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockCaptureRequestOptions mockCaptureRequestOptions = + MockCaptureRequestOptions(); + options.forEach((CaptureRequestKey key, Object? value) { + when( + mockCaptureRequestOptions.getCaptureRequestOption(key), + ).thenAnswer((_) async => value); + }); + return mockCaptureRequestOptions; + }, + controlAELockCaptureRequest: () => controlAELockKey, + ); - test('setExposurePoint throws CameraException if invalid point specified', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 23; - final MockCameraControl mockCameraControl = MockCameraControl(); - const Point invalidExposurePoint = Point(3, -1); + // Test auto mode. + await camera.setExposureMode(cameraId, ExposureMode.auto); - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; - camera.cameraInfo = MockCameraInfo(); + VerificationResult verificationResult = verify( + mockCamera2CameraControl.addCaptureRequestOptions(captureAny), + ); + CaptureRequestOptions capturedCaptureRequestOptions = + verificationResult.captured.single as CaptureRequestOptions; + expect( + await capturedCaptureRequestOptions.getCaptureRequestOption( + controlAELockKey, + ), + isFalse, + ); - camera.proxy = getProxyForExposureAndFocus(); + // Test locked mode. + clearInteractions(mockCamera2CameraControl); + await camera.setExposureMode(cameraId, ExposureMode.locked); - expect(() => camera.setExposurePoint(cameraId, invalidExposurePoint), - throwsA(isA())); - }); + verificationResult = verify( + mockCamera2CameraControl.addCaptureRequestOptions(captureAny), + ); + capturedCaptureRequestOptions = + verificationResult.captured.single as CaptureRequestOptions; + expect( + await capturedCaptureRequestOptions.getCaptureRequestOption( + controlAELockKey, + ), + isTrue, + ); + }, + ); test( - 'setExposurePoint adds new exposure point to focus metering action to start as expected when previous metering points have been set', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 9; - final MockCameraControl mockCameraControl = MockCameraControl(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); + 'setExposurePoint clears current auto-exposure metering point as expected', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 93; + final MockCameraControl mockCameraControl = MockCameraControl(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; - camera.cameraInfo = mockCameraInfo; + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; + camera.cameraInfo = mockCameraInfo; - camera.proxy = getProxyForExposureAndFocus(); + final MockFocusMeteringActionBuilder mockActionBuilder = + MockFocusMeteringActionBuilder(); + final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); + when(mockActionBuilder.build()).thenAnswer( + (_) async => FocusMeteringAction.pigeon_detached( + meteringPointsAe: const [], + meteringPointsAf: const [], + meteringPointsAwb: const [], + isAutoCancelEnabled: false, + pigeon_instanceManager: testInstanceManager, + ), + ); + MeteringMode? actionBuilderMeteringMode; + MeteringPoint? actionBuilderMeteringPoint; + camera.proxy = getProxyForExposureAndFocus( + withModeFocusMeteringActionBuilder: ({ + required MeteringMode mode, + required MeteringPoint point, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + actionBuilderMeteringMode = mode; + actionBuilderMeteringPoint = point; + return mockActionBuilder; + }, + ); - // Verify current auto-exposure metering point is removed if previously set. - double exposurePointX = 0.8; - double exposurePointY = 0.1; - Point exposurePoint = Point(exposurePointX, exposurePointY); - final (MeteringPoint, int?) autofocusMeteringPointInfo = ( - MeteringPoint.detached(x: 0.3, y: 0.7, cameraInfo: mockCameraInfo), - FocusMeteringAction.flagAf - ); - List<(MeteringPoint, int?)> meteringPointInfos = <(MeteringPoint, int?)>[ - ( - MeteringPoint.detached(x: 0.2, y: 0.5, cameraInfo: mockCameraInfo), - FocusMeteringAction.flagAe - ), - autofocusMeteringPointInfo - ]; - - camera.currentFocusMeteringAction = - FocusMeteringAction.detached(meteringPointInfos: meteringPointInfos); - - await camera.setExposurePoint(cameraId, exposurePoint); - - VerificationResult verificationResult = - verify(mockCameraControl.startFocusAndMetering(captureAny)); - FocusMeteringAction capturedAction = - verificationResult.captured.single as FocusMeteringAction; - List<(MeteringPoint, int?)> capturedMeteringPointInfos = - capturedAction.meteringPointInfos; - expect(capturedMeteringPointInfos.length, equals(2)); - expect( - capturedMeteringPointInfos.first, equals(autofocusMeteringPointInfo)); - expect(capturedMeteringPointInfos[1].$1.x, equals(exposurePointX)); - expect(capturedMeteringPointInfos[1].$1.y, equals(exposurePointY)); - expect( - capturedMeteringPointInfos[1].$2, equals(FocusMeteringAction.flagAe)); - - // Verify exposure point is set when no auto-exposure metering point - // previously set, but an auto-focus point metering point has been. - exposurePointX = 0.2; - exposurePointY = 0.9; - exposurePoint = Point(exposurePointX, exposurePointY); - meteringPointInfos = <(MeteringPoint, int?)>[autofocusMeteringPointInfo]; - - camera.currentFocusMeteringAction = - FocusMeteringAction.detached(meteringPointInfos: meteringPointInfos); - - await camera.setExposurePoint(cameraId, exposurePoint); - - verificationResult = - verify(mockCameraControl.startFocusAndMetering(captureAny)); - capturedAction = verificationResult.captured.single as FocusMeteringAction; - capturedMeteringPointInfos = capturedAction.meteringPointInfos; - expect(capturedMeteringPointInfos.length, equals(2)); - expect( - capturedMeteringPointInfos.first, equals(autofocusMeteringPointInfo)); - expect(capturedMeteringPointInfos[1].$1.x, equals(exposurePointX)); - expect(capturedMeteringPointInfos[1].$1.y, equals(exposurePointY)); - expect( - capturedMeteringPointInfos[1].$2, equals(FocusMeteringAction.flagAe)); - }); + // Verify nothing happens if no current focus and metering action has been + // enabled. + await camera.setExposurePoint(cameraId, null); + verifyNever(mockCameraControl.startFocusAndMetering(any)); + verifyNever(mockCameraControl.cancelFocusAndMetering()); + + // Verify current auto-exposure metering point is removed if previously set. + final FocusMeteringAction originalMeteringAction = + FocusMeteringAction.pigeon_detached( + meteringPointsAe: [ + MeteringPoint.pigeon_detached( + pigeon_instanceManager: testInstanceManager, + ), + ], + meteringPointsAf: [ + MeteringPoint.pigeon_detached( + pigeon_instanceManager: testInstanceManager, + ), + ], + meteringPointsAwb: const [], + isAutoCancelEnabled: false, + pigeon_instanceManager: testInstanceManager, + ); + camera.currentFocusMeteringAction = originalMeteringAction; - test( - 'setExposurePoint adds new exposure point to focus metering action to start as expected when no previous metering points have been set', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 19; - final MockCameraControl mockCameraControl = MockCameraControl(); - const double exposurePointX = 0.8; - const double exposurePointY = 0.1; - const Point exposurePoint = - Point(exposurePointX, exposurePointY); + await camera.setExposurePoint(cameraId, null); - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; - camera.cameraInfo = MockCameraInfo(); - camera.currentFocusMeteringAction = null; - - camera.proxy = getProxyForExposureAndFocus(); - - await camera.setExposurePoint(cameraId, exposurePoint); - - final VerificationResult verificationResult = - verify(mockCameraControl.startFocusAndMetering(captureAny)); - final FocusMeteringAction capturedAction = - verificationResult.captured.single as FocusMeteringAction; - final List<(MeteringPoint, int?)> capturedMeteringPointInfos = - capturedAction.meteringPointInfos; - expect(capturedMeteringPointInfos.length, equals(1)); - expect(capturedMeteringPointInfos.first.$1.x, equals(exposurePointX)); - expect(capturedMeteringPointInfos.first.$1.y, equals(exposurePointY)); - expect(capturedMeteringPointInfos.first.$2, - equals(FocusMeteringAction.flagAe)); - }); + expect(actionBuilderMeteringMode, MeteringMode.af); + expect( + actionBuilderMeteringPoint, + originalMeteringAction.meteringPointsAf.single, + ); + verifyNever(mockActionBuilder.addPoint(any)); + verifyNever(mockActionBuilder.addPointWithMode(any, any)); + + // Verify current focus and metering action is cleared if only previously + // set metering point was for auto-exposure. + camera.currentFocusMeteringAction = FocusMeteringAction.pigeon_detached( + meteringPointsAe: [ + MeteringPoint.pigeon_detached( + pigeon_instanceManager: testInstanceManager, + ), + ], + meteringPointsAf: const [], + meteringPointsAwb: const [], + isAutoCancelEnabled: false, + pigeon_instanceManager: testInstanceManager, + ); - test( - 'setExposurePoint disables auto-cancel for focus and metering as expected', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 2; - final MockCameraControl mockCameraControl = MockCameraControl(); - final FocusMeteringResult mockFocusMeteringResult = - MockFocusMeteringResult(); - const Point exposurePoint = Point(0.1, 0.2); + await camera.setExposurePoint(cameraId, null); - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; - camera.cameraInfo = MockCameraInfo(); - - camera.proxy = getProxyForSettingFocusandExposurePoints( - mockCameraControl, MockCamera2CameraControl()); - - // Make setting focus and metering action successful for test. - when(mockFocusMeteringResult.isFocusSuccessful()) - .thenAnswer((_) async => Future.value(true)); - when(mockCameraControl.startFocusAndMetering(any)).thenAnswer((_) async => - Future.value(mockFocusMeteringResult)); - - // Test not disabling auto cancel. - await camera.setFocusMode(cameraId, FocusMode.auto); - clearInteractions(mockCameraControl); - await camera.setExposurePoint(cameraId, exposurePoint); - VerificationResult verificationResult = - verify(mockCameraControl.startFocusAndMetering(captureAny)); - FocusMeteringAction capturedAction = - verificationResult.captured.single as FocusMeteringAction; - expect(capturedAction.disableAutoCancel, isFalse); - - clearInteractions(mockCameraControl); - - // Test disabling auto cancel. - await camera.setFocusMode(cameraId, FocusMode.locked); - clearInteractions(mockCameraControl); - await camera.setExposurePoint(cameraId, exposurePoint); - verificationResult = - verify(mockCameraControl.startFocusAndMetering(captureAny)); - capturedAction = verificationResult.captured.single as FocusMeteringAction; - expect(capturedAction.disableAutoCancel, isTrue); - }); + verify(mockCameraControl.cancelFocusAndMetering()); + }, + ); test( - 'setExposureOffset throws exception if exposure compensation not supported', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 6; - const double offset = 2; - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final ExposureState exposureState = ExposureState.detached( - exposureCompensationRange: - ExposureCompensationRange(minCompensation: 3, maxCompensation: 4), - exposureCompensationStep: 0); + 'setExposurePoint throws CameraException if invalid point specified', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 23; + final MockCameraControl mockCameraControl = MockCameraControl(); + const Point invalidExposurePoint = Point(3, -1); - // Set directly for test versus calling createCamera. - camera.cameraInfo = mockCameraInfo; + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; + camera.cameraInfo = MockCameraInfo(); - when(mockCameraInfo.getExposureState()) - .thenAnswer((_) async => exposureState); + camera.proxy = getProxyForExposureAndFocus(); - expect(() => camera.setExposureOffset(cameraId, offset), - throwsA(isA())); - }); + expect( + () => camera.setExposurePoint(cameraId, invalidExposurePoint), + throwsA(isA()), + ); + }, + ); test( - 'setExposureOffset throws exception if exposure compensation could not be set for unknown reason', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 11; - const double offset = 3; - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final CameraControl mockCameraControl = MockCameraControl(); - final ExposureState exposureState = ExposureState.detached( - exposureCompensationRange: - ExposureCompensationRange(minCompensation: 3, maxCompensation: 4), - exposureCompensationStep: 0.2); - - // Set directly for test versus calling createCamera. - camera.cameraInfo = mockCameraInfo; - camera.cameraControl = mockCameraControl; + 'setExposurePoint adds new exposure point to focus metering action to start as expected when previous metering points have been set', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 9; + final MockCameraControl mockCameraControl = MockCameraControl(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); - when(mockCameraInfo.getExposureState()) - .thenAnswer((_) async => exposureState); - when(mockCameraControl.setExposureCompensationIndex(15)).thenThrow( - PlatformException( - code: 'TEST_ERROR', - message: - 'This is a test error message indicating exposure offset could not be set.')); + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; + camera.cameraInfo = mockCameraInfo; - expect(() => camera.setExposureOffset(cameraId, offset), - throwsA(isA())); - }); + final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); + double exposurePointX = 0.8; + double exposurePointY = 0.1; + final MeteringPoint createdMeteringPoint = MeteringPoint.pigeon_detached( + pigeon_instanceManager: testInstanceManager, + ); + MeteringMode? actionBuilderMeteringMode; + MeteringPoint? actionBuilderMeteringPoint; + final MockFocusMeteringActionBuilder mockActionBuilder = + MockFocusMeteringActionBuilder(); + when(mockActionBuilder.build()).thenAnswer( + (_) async => FocusMeteringAction.pigeon_detached( + meteringPointsAe: const [], + meteringPointsAf: const [], + meteringPointsAwb: const [], + isAutoCancelEnabled: false, + pigeon_instanceManager: testInstanceManager, + ), + ); + camera.proxy = getProxyForExposureAndFocus( + newDisplayOrientedMeteringPointFactory: ({ + required CameraInfo cameraInfo, + required double width, + required double height, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockDisplayOrientedMeteringPointFactory mockFactory = + MockDisplayOrientedMeteringPointFactory(); + when( + mockFactory.createPoint(exposurePointX, exposurePointY), + ).thenAnswer((_) async => createdMeteringPoint); + return mockFactory; + }, + withModeFocusMeteringActionBuilder: ({ + required MeteringMode mode, + required MeteringPoint point, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + actionBuilderMeteringMode = mode; + actionBuilderMeteringPoint = point; + return mockActionBuilder; + }, + ); - test( - 'setExposureOffset throws exception if exposure compensation could not be set due to camera being closed or newer value being set', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 21; - const double offset = 5; - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final CameraControl mockCameraControl = MockCameraControl(); - final ExposureState exposureState = ExposureState.detached( - exposureCompensationRange: - ExposureCompensationRange(minCompensation: 3, maxCompensation: 4), - exposureCompensationStep: 0.1); - final int expectedExposureCompensationIndex = - (offset / exposureState.exposureCompensationStep).round(); + // Verify current auto-exposure metering point is removed if previously set. + Point exposurePoint = Point( + exposurePointX, + exposurePointY, + ); + FocusMeteringAction originalMeteringAction = + FocusMeteringAction.pigeon_detached( + meteringPointsAe: [ + MeteringPoint.pigeon_detached( + pigeon_instanceManager: testInstanceManager, + ), + ], + meteringPointsAf: [ + MeteringPoint.pigeon_detached( + pigeon_instanceManager: testInstanceManager, + ), + ], + meteringPointsAwb: const [], + isAutoCancelEnabled: false, + pigeon_instanceManager: testInstanceManager, + ); + camera.currentFocusMeteringAction = originalMeteringAction; - // Set directly for test versus calling createCamera. - camera.cameraInfo = mockCameraInfo; - camera.cameraControl = mockCameraControl; + await camera.setExposurePoint(cameraId, exposurePoint); - when(mockCameraInfo.getExposureState()) - .thenAnswer((_) async => exposureState); - when(mockCameraControl - .setExposureCompensationIndex(expectedExposureCompensationIndex)) - .thenAnswer((_) async => Future.value()); + expect( + actionBuilderMeteringPoint, + originalMeteringAction.meteringPointsAf.single, + ); + expect(actionBuilderMeteringMode, MeteringMode.af); + verify( + mockActionBuilder.addPointWithMode( + createdMeteringPoint, + MeteringMode.ae, + ), + ); - expect(() => camera.setExposureOffset(cameraId, offset), - throwsA(isA())); - }); + // Verify exposure point is set when no auto-exposure metering point + // previously set, but an auto-focus point metering point has been. + exposurePointX = 0.2; + exposurePointY = 0.9; + exposurePoint = Point(exposurePointX, exposurePointY); + originalMeteringAction = FocusMeteringAction.pigeon_detached( + meteringPointsAe: const [], + meteringPointsAf: [ + MeteringPoint.pigeon_detached( + pigeon_instanceManager: testInstanceManager, + ), + ], + meteringPointsAwb: const [], + isAutoCancelEnabled: false, + pigeon_instanceManager: testInstanceManager, + ); + camera.currentFocusMeteringAction = originalMeteringAction; - test( - 'setExposureOffset behaves as expected to successful attempt to set exposure compensation index', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 11; - const double offset = 3; - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final CameraControl mockCameraControl = MockCameraControl(); - final ExposureState exposureState = ExposureState.detached( - exposureCompensationRange: - ExposureCompensationRange(minCompensation: 3, maxCompensation: 4), - exposureCompensationStep: 0.2); - final int expectedExposureCompensationIndex = - (offset / exposureState.exposureCompensationStep).round(); + await camera.setExposurePoint(cameraId, exposurePoint); - // Set directly for test versus calling createCamera. - camera.cameraInfo = mockCameraInfo; - camera.cameraControl = mockCameraControl; + expect( + actionBuilderMeteringPoint, + originalMeteringAction.meteringPointsAf.single, + ); + expect(actionBuilderMeteringMode, MeteringMode.af); + verify( + mockActionBuilder.addPointWithMode( + createdMeteringPoint, + MeteringMode.ae, + ), + ); + }, + ); - when(mockCameraInfo.getExposureState()) - .thenAnswer((_) async => exposureState); - when(mockCameraControl - .setExposureCompensationIndex(expectedExposureCompensationIndex)) - .thenAnswer((_) async => Future.value( - (expectedExposureCompensationIndex * - exposureState.exposureCompensationStep) - .round())); - - // Exposure index * exposure offset step size = exposure offset, i.e. - // 15 * 0.2 = 3. - expect(await camera.setExposureOffset(cameraId, offset), equals(3)); - }); + test( + 'setExposurePoint adds new exposure point to focus metering action to start as expected when no previous metering points have been set', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 19; + final MockCameraControl mockCameraControl = MockCameraControl(); + const double exposurePointX = 0.8; + const double exposurePointY = 0.1; + const Point exposurePoint = Point( + exposurePointX, + exposurePointY, + ); - test('setFocusPoint clears current auto-exposure metering point as expected', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 93; - final MockCameraControl mockCameraControl = MockCameraControl(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; + camera.cameraInfo = MockCameraInfo(); + camera.currentFocusMeteringAction = null; - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; - camera.cameraInfo = mockCameraInfo; + final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); + final MeteringPoint createdMeteringPoint = MeteringPoint.pigeon_detached( + pigeon_instanceManager: testInstanceManager, + ); + MeteringMode? actionBuilderMeteringMode; + MeteringPoint? actionBuilderMeteringPoint; + final MockFocusMeteringActionBuilder mockActionBuilder = + MockFocusMeteringActionBuilder(); + when(mockActionBuilder.build()).thenAnswer( + (_) async => FocusMeteringAction.pigeon_detached( + meteringPointsAe: const [], + meteringPointsAf: const [], + meteringPointsAwb: const [], + isAutoCancelEnabled: false, + pigeon_instanceManager: testInstanceManager, + ), + ); + camera.proxy = getProxyForExposureAndFocus( + newDisplayOrientedMeteringPointFactory: ({ + required CameraInfo cameraInfo, + required double width, + required double height, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockDisplayOrientedMeteringPointFactory mockFactory = + MockDisplayOrientedMeteringPointFactory(); + when( + mockFactory.createPoint(exposurePointX, exposurePointY), + ).thenAnswer((_) async => createdMeteringPoint); + return mockFactory; + }, + withModeFocusMeteringActionBuilder: ({ + required MeteringMode mode, + required MeteringPoint point, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + actionBuilderMeteringMode = mode; + actionBuilderMeteringPoint = point; + return mockActionBuilder; + }, + ); - camera.proxy = getProxyForExposureAndFocus(); + await camera.setExposurePoint(cameraId, exposurePoint); - // Verify nothing happens if no current focus and metering action has been - // enabled. - await camera.setFocusPoint(cameraId, null); - verifyNever(mockCameraControl.startFocusAndMetering(any)); - verifyNever(mockCameraControl.cancelFocusAndMetering()); + expect(actionBuilderMeteringPoint, createdMeteringPoint); + expect(actionBuilderMeteringMode, MeteringMode.ae); + }, + ); - // Verify current auto-exposure metering point is removed if previously set. - final (MeteringPoint, int?) autoexposureMeteringPointInfo = ( - MeteringPoint.detached(x: 0.3, y: 0.7, cameraInfo: mockCameraInfo), - FocusMeteringAction.flagAe - ); - List<(MeteringPoint, int?)> meteringPointInfos = <(MeteringPoint, int?)>[ - ( - MeteringPoint.detached(x: 0.2, y: 0.5, cameraInfo: mockCameraInfo), - FocusMeteringAction.flagAf - ), - autoexposureMeteringPointInfo - ]; - - camera.currentFocusMeteringAction = - FocusMeteringAction.detached(meteringPointInfos: meteringPointInfos); - - await camera.setFocusPoint(cameraId, null); - - final VerificationResult verificationResult = - verify(mockCameraControl.startFocusAndMetering(captureAny)); - final FocusMeteringAction capturedAction = - verificationResult.captured.single as FocusMeteringAction; - final List<(MeteringPoint, int?)> capturedMeteringPointInfos = - capturedAction.meteringPointInfos; - expect(capturedMeteringPointInfos.length, equals(1)); - expect(capturedMeteringPointInfos.first, - equals(autoexposureMeteringPointInfo)); - - // Verify current focus and metering action is cleared if only previously - // set metering point was for auto-exposure. - meteringPointInfos = <(MeteringPoint, int?)>[ - ( - MeteringPoint.detached(x: 0.2, y: 0.5, cameraInfo: mockCameraInfo), - FocusMeteringAction.flagAf - ) - ]; - camera.currentFocusMeteringAction = - FocusMeteringAction.detached(meteringPointInfos: meteringPointInfos); - - await camera.setFocusPoint(cameraId, null); - - verify(mockCameraControl.cancelFocusAndMetering()); - }); + test( + 'setExposurePoint disables auto-cancel for focus and metering as expected', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 2; + final MockCameraControl mockCameraControl = MockCameraControl(); + final FocusMeteringResult mockFocusMeteringResult = + MockFocusMeteringResult(); + const Point exposurePoint = Point(0.1, 0.2); - test('setFocusPoint throws CameraException if invalid point specified', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 23; - final MockCameraControl mockCameraControl = MockCameraControl(); - const Point invalidFocusPoint = Point(-3, 1); + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; + camera.cameraInfo = MockCameraInfo(); - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; - camera.cameraInfo = MockCameraInfo(); + camera.proxy = getProxyForSettingFocusandExposurePoints( + mockCameraControl, + MockCamera2CameraControl(), + ); - camera.proxy = getProxyForExposureAndFocus(); + // Make setting focus and metering action successful for test. + when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true); + when(mockCameraControl.startFocusAndMetering(any)).thenAnswer( + (_) async => Future.value(mockFocusMeteringResult), + ); - expect(() => camera.setFocusPoint(cameraId, invalidFocusPoint), - throwsA(isA())); - }); + // Test not disabling auto cancel. + await camera.setFocusMode(cameraId, FocusMode.auto); + clearInteractions(mockCameraControl); + await camera.setExposurePoint(cameraId, exposurePoint); + VerificationResult verificationResult = verify( + mockCameraControl.startFocusAndMetering(captureAny), + ); + FocusMeteringAction capturedAction = + verificationResult.captured.single as FocusMeteringAction; + expect(capturedAction.isAutoCancelEnabled, isTrue); + + clearInteractions(mockCameraControl); + + // Test disabling auto cancel. + await camera.setFocusMode(cameraId, FocusMode.locked); + clearInteractions(mockCameraControl); + await camera.setExposurePoint(cameraId, exposurePoint); + verificationResult = verify( + mockCameraControl.startFocusAndMetering(captureAny), + ); + capturedAction = + verificationResult.captured.single as FocusMeteringAction; + expect(capturedAction.isAutoCancelEnabled, isFalse); + }, + ); test( - 'setFocusPoint adds new exposure point to focus metering action to start as expected when previous metering points have been set', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 9; - final MockCameraControl mockCameraControl = MockCameraControl(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); + 'setExposureOffset throws exception if exposure compensation not supported', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 6; + const double offset = 2; + final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); + final ExposureState exposureState = ExposureState.pigeon_detached( + exposureCompensationRange: CameraIntegerRange.pigeon_detached( + lower: 3, + upper: 4, + pigeon_instanceManager: testInstanceManager, + ), + exposureCompensationStep: 0, + pigeon_instanceManager: testInstanceManager, + ); - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; - camera.cameraInfo = mockCameraInfo; + // Set directly for test versus calling createCamera. + camera.cameraInfo = mockCameraInfo; - camera.proxy = getProxyForExposureAndFocus(); + when(mockCameraInfo.exposureState).thenReturn(exposureState); - // Verify current auto-exposure metering point is removed if previously set. - double focusPointX = 0.8; - double focusPointY = 0.1; - Point exposurePoint = Point(focusPointX, focusPointY); - final (MeteringPoint, int?) autoExposureMeteringPointInfo = ( - MeteringPoint.detached(x: 0.3, y: 0.7, cameraInfo: mockCameraInfo), - FocusMeteringAction.flagAe - ); - List<(MeteringPoint, int?)> meteringPointInfos = <(MeteringPoint, int?)>[ - ( - MeteringPoint.detached(x: 0.2, y: 0.5, cameraInfo: mockCameraInfo), - FocusMeteringAction.flagAf - ), - autoExposureMeteringPointInfo - ]; - - camera.currentFocusMeteringAction = - FocusMeteringAction.detached(meteringPointInfos: meteringPointInfos); - - await camera.setFocusPoint(cameraId, exposurePoint); - - VerificationResult verificationResult = - verify(mockCameraControl.startFocusAndMetering(captureAny)); - FocusMeteringAction capturedAction = - verificationResult.captured.single as FocusMeteringAction; - List<(MeteringPoint, int?)> capturedMeteringPointInfos = - capturedAction.meteringPointInfos; - expect(capturedMeteringPointInfos.length, equals(2)); - expect(capturedMeteringPointInfos.first, - equals(autoExposureMeteringPointInfo)); - expect(capturedMeteringPointInfos[1].$1.x, equals(focusPointX)); - expect(capturedMeteringPointInfos[1].$1.y, equals(focusPointY)); - expect( - capturedMeteringPointInfos[1].$2, equals(FocusMeteringAction.flagAf)); - - // Verify exposure point is set when no auto-exposure metering point - // previously set, but an auto-focus point metering point has been. - focusPointX = 0.2; - focusPointY = 0.9; - exposurePoint = Point(focusPointX, focusPointY); - meteringPointInfos = <(MeteringPoint, int?)>[autoExposureMeteringPointInfo]; - - camera.currentFocusMeteringAction = - FocusMeteringAction.detached(meteringPointInfos: meteringPointInfos); - - await camera.setFocusPoint(cameraId, exposurePoint); - - verificationResult = - verify(mockCameraControl.startFocusAndMetering(captureAny)); - capturedAction = verificationResult.captured.single as FocusMeteringAction; - capturedMeteringPointInfos = capturedAction.meteringPointInfos; - expect(capturedMeteringPointInfos.length, equals(2)); - expect(capturedMeteringPointInfos.first, - equals(autoExposureMeteringPointInfo)); - expect(capturedMeteringPointInfos[1].$1.x, equals(focusPointX)); - expect(capturedMeteringPointInfos[1].$1.y, equals(focusPointY)); - expect( - capturedMeteringPointInfos[1].$2, equals(FocusMeteringAction.flagAf)); - }); + expect( + () => camera.setExposureOffset(cameraId, offset), + throwsA(isA()), + ); + }, + ); test( - 'setFocusPoint adds new exposure point to focus metering action to start as expected when no previous metering points have been set', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 19; - final MockCameraControl mockCameraControl = MockCameraControl(); - const double focusPointX = 0.8; - const double focusPointY = 0.1; - const Point exposurePoint = Point(focusPointX, focusPointY); + 'setExposureOffset throws exception if exposure compensation could not be set for unknown reason', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 11; + const double offset = 3; + final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final CameraControl mockCameraControl = MockCameraControl(); + final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); + final ExposureState exposureState = ExposureState.pigeon_detached( + exposureCompensationRange: CameraIntegerRange.pigeon_detached( + lower: 3, + upper: 4, + pigeon_instanceManager: testInstanceManager, + ), + exposureCompensationStep: 0.2, + pigeon_instanceManager: testInstanceManager, + ); - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; - camera.cameraInfo = MockCameraInfo(); - camera.currentFocusMeteringAction = null; - - camera.proxy = getProxyForExposureAndFocus(); - - await camera.setFocusPoint(cameraId, exposurePoint); - - final VerificationResult verificationResult = - verify(mockCameraControl.startFocusAndMetering(captureAny)); - final FocusMeteringAction capturedAction = - verificationResult.captured.single as FocusMeteringAction; - final List<(MeteringPoint, int?)> capturedMeteringPointInfos = - capturedAction.meteringPointInfos; - expect(capturedMeteringPointInfos.length, equals(1)); - expect(capturedMeteringPointInfos.first.$1.x, equals(focusPointX)); - expect(capturedMeteringPointInfos.first.$1.y, equals(focusPointY)); - expect(capturedMeteringPointInfos.first.$2, - equals(FocusMeteringAction.flagAf)); - }); + // Set directly for test versus calling createCamera. + camera.cameraInfo = mockCameraInfo; + camera.cameraControl = mockCameraControl; - test('setFocusPoint disables auto-cancel for focus and metering as expected', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 2; - final MockCameraControl mockCameraControl = MockCameraControl(); - final MockFocusMeteringResult mockFocusMeteringResult = - MockFocusMeteringResult(); - const Point exposurePoint = Point(0.1, 0.2); + when(mockCameraInfo.exposureState).thenReturn(exposureState); + when(mockCameraControl.setExposureCompensationIndex(15)).thenThrow( + PlatformException( + code: 'TEST_ERROR', + message: + 'This is a test error message indicating exposure offset could not be set.', + ), + ); - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; - camera.cameraInfo = MockCameraInfo(); - - camera.proxy = getProxyForSettingFocusandExposurePoints( - mockCameraControl, MockCamera2CameraControl()); - - // Make setting focus and metering action successful for test. - when(mockFocusMeteringResult.isFocusSuccessful()) - .thenAnswer((_) async => Future.value(true)); - when(mockCameraControl.startFocusAndMetering(any)).thenAnswer((_) async => - Future.value(mockFocusMeteringResult)); - - // Test not disabling auto cancel. - await camera.setFocusMode(cameraId, FocusMode.auto); - clearInteractions(mockCameraControl); - - await camera.setFocusPoint(cameraId, exposurePoint); - VerificationResult verificationResult = - verify(mockCameraControl.startFocusAndMetering(captureAny)); - FocusMeteringAction capturedAction = - verificationResult.captured.single as FocusMeteringAction; - expect(capturedAction.disableAutoCancel, isFalse); - - clearInteractions(mockCameraControl); - - // Test disabling auto cancel. - await camera.setFocusMode(cameraId, FocusMode.locked); - clearInteractions(mockCameraControl); - - await camera.setFocusPoint(cameraId, exposurePoint); - verificationResult = - verify(mockCameraControl.startFocusAndMetering(captureAny)); - capturedAction = verificationResult.captured.single as FocusMeteringAction; - expect(capturedAction.disableAutoCancel, isTrue); - }); + expect( + () => camera.setExposureOffset(cameraId, offset), + throwsA(isA()), + ); + }, + ); test( - 'setFocusMode does nothing if setting auto-focus mode and is already using auto-focus mode', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 4; - final MockCameraControl mockCameraControl = MockCameraControl(); - final MockFocusMeteringResult mockFocusMeteringResult = - MockFocusMeteringResult(); - - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; - camera.cameraInfo = MockCameraInfo(); - - camera.proxy = getProxyForSettingFocusandExposurePoints( - mockCameraControl, MockCamera2CameraControl()); + 'setExposureOffset throws exception if exposure compensation could not be set due to camera being closed or newer value being set', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 21; + const double offset = 5; + final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final CameraControl mockCameraControl = MockCameraControl(); + final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); + final ExposureState exposureState = ExposureState.pigeon_detached( + exposureCompensationRange: CameraIntegerRange.pigeon_detached( + lower: 3, + upper: 4, + pigeon_instanceManager: testInstanceManager, + ), + exposureCompensationStep: 0.1, + pigeon_instanceManager: testInstanceManager, + ); + final int expectedExposureCompensationIndex = + (offset / exposureState.exposureCompensationStep).round(); - // Make setting focus and metering action successful for test. - when(mockFocusMeteringResult.isFocusSuccessful()) - .thenAnswer((_) async => Future.value(true)); - when(mockCameraControl.startFocusAndMetering(any)).thenAnswer((_) async => - Future.value(mockFocusMeteringResult)); + // Set directly for test versus calling createCamera. + camera.cameraInfo = mockCameraInfo; + camera.cameraControl = mockCameraControl; - // Set locked focus mode and then try to re-set it. - await camera.setFocusMode(cameraId, FocusMode.locked); - clearInteractions(mockCameraControl); + when(mockCameraInfo.exposureState).thenReturn(exposureState); + when( + mockCameraControl.setExposureCompensationIndex( + expectedExposureCompensationIndex, + ), + ).thenAnswer((_) async => Future.value()); - await camera.setFocusMode(cameraId, FocusMode.locked); - verifyNoMoreInteractions(mockCameraControl); - }); + expect( + () => camera.setExposureOffset(cameraId, offset), + throwsA(isA()), + ); + }, + ); test( - 'setFocusMode does nothing if setting locked focus mode and is already using locked focus mode', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 4; - final MockCameraControl mockCameraControl = MockCameraControl(); - - // Camera uses auto-focus by default, so try setting auto mode again. - await camera.setFocusMode(cameraId, FocusMode.auto); + 'setExposureOffset behaves as expected to successful attempt to set exposure compensation index', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 11; + const double offset = 3; + final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final CameraControl mockCameraControl = MockCameraControl(); + final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); + final ExposureState exposureState = ExposureState.pigeon_detached( + exposureCompensationRange: CameraIntegerRange.pigeon_detached( + lower: 3, + upper: 4, + pigeon_instanceManager: testInstanceManager, + ), + exposureCompensationStep: 0.2, + pigeon_instanceManager: testInstanceManager, + ); + final int expectedExposureCompensationIndex = + (offset / exposureState.exposureCompensationStep).round(); - verifyNoMoreInteractions(mockCameraControl); - }); + // Set directly for test versus calling createCamera. + camera.cameraInfo = mockCameraInfo; + camera.cameraControl = mockCameraControl; - test( - 'setFocusMode removes default auto-focus point if previously set and setting auto-focus mode', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 5; - final MockCameraControl mockCameraControl = MockCameraControl(); - final MockFocusMeteringResult mockFocusMeteringResult = - MockFocusMeteringResult(); - final MockCamera2CameraControl mockCamera2CameraControl = - MockCamera2CameraControl(); - const double exposurePointX = 0.2; - const double exposurePointY = 0.7; - - // Set directly for test versus calling createCamera. - camera.cameraInfo = MockCameraInfo(); - camera.cameraControl = mockCameraControl; + when(mockCameraInfo.exposureState).thenReturn(exposureState); + when( + mockCameraControl.setExposureCompensationIndex( + expectedExposureCompensationIndex, + ), + ).thenAnswer( + (_) async => Future.value( + (expectedExposureCompensationIndex * + exposureState.exposureCompensationStep) + .round(), + ), + ); - when(mockCamera2CameraControl.addCaptureRequestOptions(any)) - .thenAnswer((_) async => Future.value()); - - camera.proxy = getProxyForSettingFocusandExposurePoints( - mockCameraControl, mockCamera2CameraControl); - - // Make setting focus and metering action successful for test. - when(mockFocusMeteringResult.isFocusSuccessful()) - .thenAnswer((_) async => Future.value(true)); - when(mockCameraControl.startFocusAndMetering(any)).thenAnswer((_) async => - Future.value(mockFocusMeteringResult)); - - // Set exposure points. - await camera.setExposurePoint( - cameraId, const Point(exposurePointX, exposurePointY)); - - // Lock focus default focus point. - await camera.setFocusMode(cameraId, FocusMode.locked); - - clearInteractions(mockCameraControl); - - // Test removal of default focus point. - await camera.setFocusMode(cameraId, FocusMode.auto); - - final VerificationResult verificationResult = - verify(mockCameraControl.startFocusAndMetering(captureAny)); - final FocusMeteringAction capturedAction = - verificationResult.captured.single as FocusMeteringAction; - expect(capturedAction.disableAutoCancel, isFalse); - - // We expect only the previously set exposure point to be re-set. - final List<(MeteringPoint, int?)> capturedMeteringPointInfos = - capturedAction.meteringPointInfos; - expect(capturedMeteringPointInfos.length, equals(1)); - expect(capturedMeteringPointInfos.first.$1.x, equals(exposurePointX)); - expect(capturedMeteringPointInfos.first.$1.y, equals(exposurePointY)); - expect(capturedMeteringPointInfos.first.$1.size, isNull); - expect(capturedMeteringPointInfos.first.$2, - equals(FocusMeteringAction.flagAe)); - }); + // Exposure index * exposure offset step size = exposure offset, i.e. + // 15 * 0.2 = 3. + expect(await camera.setExposureOffset(cameraId, offset), equals(3)); + }, + ); test( - 'setFocusMode cancels focus and metering if only focus point previously set is a focus point', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 5; - final MockCameraControl mockCameraControl = MockCameraControl(); - final FocusMeteringResult mockFocusMeteringResult = - MockFocusMeteringResult(); - final MockCamera2CameraControl mockCamera2CameraControl = - MockCamera2CameraControl(); + 'setFocusPoint clears current auto-exposure metering point as expected', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 93; + final MockCameraControl mockCameraControl = MockCameraControl(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); - // Set directly for test versus calling createCamera. - camera.cameraInfo = MockCameraInfo(); - camera.cameraControl = mockCameraControl; + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; + camera.cameraInfo = mockCameraInfo; - when(mockCamera2CameraControl.addCaptureRequestOptions(any)) - .thenAnswer((_) async => Future.value()); + final MockFocusMeteringActionBuilder mockActionBuilder = + MockFocusMeteringActionBuilder(); + final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); + when(mockActionBuilder.build()).thenAnswer( + (_) async => FocusMeteringAction.pigeon_detached( + meteringPointsAe: const [], + meteringPointsAf: const [], + meteringPointsAwb: const [], + isAutoCancelEnabled: false, + pigeon_instanceManager: testInstanceManager, + ), + ); + MeteringMode? actionBuilderMeteringMode; + MeteringPoint? actionBuilderMeteringPoint; + camera.proxy = getProxyForExposureAndFocus( + withModeFocusMeteringActionBuilder: ({ + required MeteringMode mode, + required MeteringPoint point, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + actionBuilderMeteringMode = mode; + actionBuilderMeteringPoint = point; + return mockActionBuilder; + }, + ); - camera.proxy = getProxyForSettingFocusandExposurePoints( - mockCameraControl, mockCamera2CameraControl); + // Verify nothing happens if no current focus and metering action has been + // enabled. + await camera.setFocusPoint(cameraId, null); + verifyNever(mockCameraControl.startFocusAndMetering(any)); + verifyNever(mockCameraControl.cancelFocusAndMetering()); + + final FocusMeteringAction originalMeteringAction = + FocusMeteringAction.pigeon_detached( + meteringPointsAe: [ + MeteringPoint.pigeon_detached( + pigeon_instanceManager: testInstanceManager, + ), + ], + meteringPointsAf: [ + MeteringPoint.pigeon_detached( + pigeon_instanceManager: testInstanceManager, + ), + ], + meteringPointsAwb: const [], + isAutoCancelEnabled: false, + pigeon_instanceManager: testInstanceManager, + ); + camera.currentFocusMeteringAction = originalMeteringAction; - // Make setting focus and metering action successful for test. - when(mockFocusMeteringResult.isFocusSuccessful()) - .thenAnswer((_) async => Future.value(true)); - when(mockCameraControl.startFocusAndMetering(any)).thenAnswer((_) async => - Future.value(mockFocusMeteringResult)); + await camera.setFocusPoint(cameraId, null); - // Lock focus default focus point. - await camera.setFocusMode(cameraId, FocusMode.locked); + expect(actionBuilderMeteringMode, MeteringMode.ae); + expect( + actionBuilderMeteringPoint, + originalMeteringAction.meteringPointsAe.single, + ); + verifyNever(mockActionBuilder.addPoint(any)); + verifyNever(mockActionBuilder.addPointWithMode(any, any)); + + // Verify current focus and metering action is cleared if only previously + // set metering point was for auto-exposure. + camera.currentFocusMeteringAction = FocusMeteringAction.pigeon_detached( + meteringPointsAe: const [], + meteringPointsAf: [ + MeteringPoint.pigeon_detached( + pigeon_instanceManager: testInstanceManager, + ), + ], + meteringPointsAwb: const [], + isAutoCancelEnabled: false, + pigeon_instanceManager: testInstanceManager, + ); - // Test removal of default focus point. - await camera.setFocusMode(cameraId, FocusMode.auto); + await camera.setFocusPoint(cameraId, null); - verify(mockCameraControl.cancelFocusAndMetering()); - }); + verify(mockCameraControl.cancelFocusAndMetering()); + }, + ); test( - 'setFocusMode re-focuses on previously set auto-focus point with auto-canceled enabled if setting auto-focus mode', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 6; - final MockCameraControl mockCameraControl = MockCameraControl(); - final FocusMeteringResult mockFocusMeteringResult = - MockFocusMeteringResult(); - final MockCamera2CameraControl mockCamera2CameraControl = - MockCamera2CameraControl(); - const double focusPointX = 0.1; - const double focusPointY = 0.2; + 'setFocusPoint throws CameraException if invalid point specified', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 23; + final MockCameraControl mockCameraControl = MockCameraControl(); + const Point invalidFocusPoint = Point(-3, 1); - // Set directly for test versus calling createCamera. - camera.cameraInfo = MockCameraInfo(); - camera.cameraControl = mockCameraControl; + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; + camera.cameraInfo = MockCameraInfo(); - when(mockCamera2CameraControl.addCaptureRequestOptions(any)) - .thenAnswer((_) async => Future.value()); - - camera.proxy = getProxyForSettingFocusandExposurePoints( - mockCameraControl, mockCamera2CameraControl); - - // Make setting focus and metering action successful for test. - when(mockFocusMeteringResult.isFocusSuccessful()) - .thenAnswer((_) async => Future.value(true)); - when(mockCameraControl.startFocusAndMetering(any)).thenAnswer((_) async => - Future.value(mockFocusMeteringResult)); - - // Lock a focus point. - await camera.setFocusPoint( - cameraId, const Point(focusPointX, focusPointY)); - await camera.setFocusMode(cameraId, FocusMode.locked); - - clearInteractions(mockCameraControl); - - // Test re-focusing on previously set auto-focus point with auto-cancel enabled. - await camera.setFocusMode(cameraId, FocusMode.auto); - - final VerificationResult verificationResult = - verify(mockCameraControl.startFocusAndMetering(captureAny)); - final FocusMeteringAction capturedAction = - verificationResult.captured.single as FocusMeteringAction; - expect(capturedAction.disableAutoCancel, isFalse); - final List<(MeteringPoint, int?)> capturedMeteringPointInfos = - capturedAction.meteringPointInfos; - expect(capturedMeteringPointInfos.length, equals(1)); - expect(capturedMeteringPointInfos.first.$1.x, equals(focusPointX)); - expect(capturedMeteringPointInfos.first.$1.y, equals(focusPointY)); - expect(capturedMeteringPointInfos.first.$1.size, isNull); - expect(capturedMeteringPointInfos.first.$2, - equals(FocusMeteringAction.flagAf)); - }); + camera.proxy = getProxyForExposureAndFocus(); + + expect( + () => camera.setFocusPoint(cameraId, invalidFocusPoint), + throwsA(isA()), + ); + }, + ); test( - 'setFocusMode starts expected focus and metering action with previously set auto-focus point if setting locked focus mode and current focus and metering action has auto-focus point', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 7; - final MockCameraControl mockCameraControl = MockCameraControl(); - final MockCamera2CameraControl mockCamera2CameraControl = - MockCamera2CameraControl(); - const double focusPointX = 0.88; - const double focusPointY = 0.33; + 'setFocusPoint adds new focus point to focus metering action to start as expected when previous metering points have been set', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 9; + final MockCameraControl mockCameraControl = MockCameraControl(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); - // Set directly for test versus calling createCamera. - camera.cameraInfo = MockCameraInfo(); - camera.cameraControl = mockCameraControl; + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; + camera.cameraInfo = mockCameraInfo; - when(mockCamera2CameraControl.addCaptureRequestOptions(any)) - .thenAnswer((_) async => Future.value()); - - camera.proxy = getProxyForSettingFocusandExposurePoints( - mockCameraControl, mockCamera2CameraControl); - - // Set a focus point. - await camera.setFocusPoint( - cameraId, const Point(focusPointX, focusPointY)); - clearInteractions(mockCameraControl); - - // Lock focus point. - await camera.setFocusMode(cameraId, FocusMode.locked); - - final VerificationResult verificationResult = - verify(mockCameraControl.startFocusAndMetering(captureAny)); - final FocusMeteringAction capturedAction = - verificationResult.captured.single as FocusMeteringAction; - expect(capturedAction.disableAutoCancel, isTrue); - - // We expect the set focus point to be locked. - final List<(MeteringPoint, int?)> capturedMeteringPointInfos = - capturedAction.meteringPointInfos; - expect(capturedMeteringPointInfos.length, equals(1)); - expect(capturedMeteringPointInfos.first.$1.x, equals(focusPointX)); - expect(capturedMeteringPointInfos.first.$1.y, equals(focusPointY)); - expect(capturedMeteringPointInfos.first.$1.size, isNull); - expect(capturedMeteringPointInfos.first.$2, - equals(FocusMeteringAction.flagAf)); - }); + final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); + double focusPointX = 0.8; + double focusPointY = 0.1; + Point focusPoint = Point(focusPointX, focusPointY); + final MeteringPoint createdMeteringPoint = MeteringPoint.pigeon_detached( + pigeon_instanceManager: testInstanceManager, + ); + MeteringMode? actionBuilderMeteringMode; + MeteringPoint? actionBuilderMeteringPoint; + final MockFocusMeteringActionBuilder mockActionBuilder = + MockFocusMeteringActionBuilder(); + when(mockActionBuilder.build()).thenAnswer( + (_) async => FocusMeteringAction.pigeon_detached( + meteringPointsAe: const [], + meteringPointsAf: const [], + meteringPointsAwb: const [], + isAutoCancelEnabled: false, + pigeon_instanceManager: testInstanceManager, + ), + ); + camera.proxy = getProxyForExposureAndFocus( + newDisplayOrientedMeteringPointFactory: ({ + required CameraInfo cameraInfo, + required double width, + required double height, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockDisplayOrientedMeteringPointFactory mockFactory = + MockDisplayOrientedMeteringPointFactory(); + when( + mockFactory.createPoint(focusPointX, focusPointY), + ).thenAnswer((_) async => createdMeteringPoint); + return mockFactory; + }, + withModeFocusMeteringActionBuilder: ({ + required MeteringMode mode, + required MeteringPoint point, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + actionBuilderMeteringMode = mode; + actionBuilderMeteringPoint = point; + return mockActionBuilder; + }, + ); - test( - 'setFocusMode starts expected focus and metering action with previously set auto-focus point if setting locked focus mode and current focus and metering action has auto-focus point amongst others', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 8; - final MockCameraControl mockCameraControl = MockCameraControl(); - final MockCamera2CameraControl mockCamera2CameraControl = - MockCamera2CameraControl(); - const double focusPointX = 0.38; - const double focusPointY = 0.38; - const double exposurePointX = 0.54; - const double exposurePointY = 0.45; + // Verify current auto-exposure metering point is removed if previously set. + FocusMeteringAction originalMeteringAction = + FocusMeteringAction.pigeon_detached( + meteringPointsAe: [ + MeteringPoint.pigeon_detached( + pigeon_instanceManager: testInstanceManager, + ), + ], + meteringPointsAf: [ + MeteringPoint.pigeon_detached( + pigeon_instanceManager: testInstanceManager, + ), + ], + meteringPointsAwb: const [], + isAutoCancelEnabled: false, + pigeon_instanceManager: testInstanceManager, + ); + camera.currentFocusMeteringAction = originalMeteringAction; - // Set directly for test versus calling createCamera. - camera.cameraInfo = MockCameraInfo(); - camera.cameraControl = mockCameraControl; + await camera.setFocusPoint(cameraId, focusPoint); - when(mockCamera2CameraControl.addCaptureRequestOptions(any)) - .thenAnswer((_) async => Future.value()); - - camera.proxy = getProxyForSettingFocusandExposurePoints( - mockCameraControl, mockCamera2CameraControl); - - // Set focus and exposure points. - await camera.setFocusPoint( - cameraId, const Point(focusPointX, focusPointY)); - await camera.setExposurePoint( - cameraId, const Point(exposurePointX, exposurePointY)); - clearInteractions(mockCameraControl); - - // Lock focus point. - await camera.setFocusMode(cameraId, FocusMode.locked); - - final VerificationResult verificationResult = - verify(mockCameraControl.startFocusAndMetering(captureAny)); - final FocusMeteringAction capturedAction = - verificationResult.captured.single as FocusMeteringAction; - expect(capturedAction.disableAutoCancel, isTrue); - - // We expect two MeteringPoints, the set focus point and the set exposure - // point. - final List<(MeteringPoint, int?)> capturedMeteringPointInfos = - capturedAction.meteringPointInfos; - expect(capturedMeteringPointInfos.length, equals(2)); - - final List<(MeteringPoint, int?)> focusPoints = capturedMeteringPointInfos - .where(((MeteringPoint, int?) meteringPointInfo) => - meteringPointInfo.$2 == FocusMeteringAction.flagAf) - .toList(); - expect(focusPoints.length, equals(1)); - expect(focusPoints.first.$1.x, equals(focusPointX)); - expect(focusPoints.first.$1.y, equals(focusPointY)); - expect(focusPoints.first.$1.size, isNull); - - final List<(MeteringPoint, int?)> exposurePoints = - capturedMeteringPointInfos - .where(((MeteringPoint, int?) meteringPointInfo) => - meteringPointInfo.$2 == FocusMeteringAction.flagAe) - .toList(); - expect(exposurePoints.length, equals(1)); - expect(exposurePoints.first.$1.x, equals(exposurePointX)); - expect(exposurePoints.first.$1.y, equals(exposurePointY)); - expect(exposurePoints.first.$1.size, isNull); - }); + expect( + actionBuilderMeteringPoint, + originalMeteringAction.meteringPointsAe.single, + ); + expect(actionBuilderMeteringMode, MeteringMode.ae); + verify( + mockActionBuilder.addPointWithMode( + createdMeteringPoint, + MeteringMode.af, + ), + ); - test( - 'setFocusMode starts expected focus and metering action if setting locked focus mode and current focus and metering action does not contain an auto-focus point', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 9; - final MockCameraControl mockCameraControl = MockCameraControl(); - final MockCamera2CameraControl mockCamera2CameraControl = - MockCamera2CameraControl(); - const double exposurePointX = 0.8; - const double exposurePointY = 0.3; - const double defaultFocusPointX = 0.5; - const double defaultFocusPointY = 0.5; - const double defaultFocusPointSize = 1; + // Verify exposure point is set when no auto-focus metering point + // previously set, but an auto-exposure point metering point has been. + focusPointX = 0.2; + focusPointY = 0.9; + focusPoint = Point(focusPointX, focusPointY); + originalMeteringAction = FocusMeteringAction.pigeon_detached( + meteringPointsAe: [ + MeteringPoint.pigeon_detached( + pigeon_instanceManager: testInstanceManager, + ), + ], + meteringPointsAf: const [], + meteringPointsAwb: const [], + isAutoCancelEnabled: false, + pigeon_instanceManager: testInstanceManager, + ); + camera.currentFocusMeteringAction = originalMeteringAction; - // Set directly for test versus calling createCamera. - camera.cameraInfo = MockCameraInfo(); - camera.cameraControl = mockCameraControl; + await camera.setFocusPoint(cameraId, focusPoint); - when(mockCamera2CameraControl.addCaptureRequestOptions(any)) - .thenAnswer((_) async => Future.value()); - - camera.proxy = getProxyForSettingFocusandExposurePoints( - mockCameraControl, mockCamera2CameraControl); - - // Set an exposure point (creates a current focus and metering action - // without a focus point). - await camera.setExposurePoint( - cameraId, const Point(exposurePointX, exposurePointY)); - clearInteractions(mockCameraControl); - - // Lock focus point. - await camera.setFocusMode(cameraId, FocusMode.locked); - - final VerificationResult verificationResult = - verify(mockCameraControl.startFocusAndMetering(captureAny)); - final FocusMeteringAction capturedAction = - verificationResult.captured.single as FocusMeteringAction; - expect(capturedAction.disableAutoCancel, isTrue); - - // We expect two MeteringPoints, the default focus point and the set - //exposure point. - final List<(MeteringPoint, int?)> capturedMeteringPointInfos = - capturedAction.meteringPointInfos; - expect(capturedMeteringPointInfos.length, equals(2)); - - final List<(MeteringPoint, int?)> focusPoints = capturedMeteringPointInfos - .where(((MeteringPoint, int?) meteringPointInfo) => - meteringPointInfo.$2 == FocusMeteringAction.flagAf) - .toList(); - expect(focusPoints.length, equals(1)); - expect(focusPoints.first.$1.x, equals(defaultFocusPointX)); - expect(focusPoints.first.$1.y, equals(defaultFocusPointY)); - expect(focusPoints.first.$1.size, equals(defaultFocusPointSize)); - - final List<(MeteringPoint, int?)> exposurePoints = - capturedMeteringPointInfos - .where(((MeteringPoint, int?) meteringPointInfo) => - meteringPointInfo.$2 == FocusMeteringAction.flagAe) - .toList(); - expect(exposurePoints.length, equals(1)); - expect(exposurePoints.first.$1.x, equals(exposurePointX)); - expect(exposurePoints.first.$1.y, equals(exposurePointY)); - expect(exposurePoints.first.$1.size, isNull); - }); + expect( + actionBuilderMeteringPoint, + originalMeteringAction.meteringPointsAe.single, + ); + expect(actionBuilderMeteringMode, MeteringMode.ae); + verify( + mockActionBuilder.addPointWithMode( + createdMeteringPoint, + MeteringMode.af, + ), + ); + }, + ); test( - 'setFocusMode starts expected focus and metering action if there is no current focus and metering action', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 10; - final MockCameraControl mockCameraControl = MockCameraControl(); - final MockCamera2CameraControl mockCamera2CameraControl = - MockCamera2CameraControl(); - const double defaultFocusPointX = 0.5; - const double defaultFocusPointY = 0.5; - const double defaultFocusPointSize = 1; + 'setFocusPoint adds new focus point to focus metering action to start as expected when no previous metering points have been set', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 19; + final MockCameraControl mockCameraControl = MockCameraControl(); + const double focusPointX = 0.8; + const double focusPointY = 0.1; + const Point focusPoint = Point(focusPointX, focusPointY); - // Set directly for test versus calling createCamera. - camera.cameraInfo = MockCameraInfo(); - camera.cameraControl = mockCameraControl; + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; + camera.cameraInfo = MockCameraInfo(); + camera.currentFocusMeteringAction = null; - when(mockCamera2CameraControl.addCaptureRequestOptions(any)) - .thenAnswer((_) async => Future.value()); - - camera.proxy = getProxyForSettingFocusandExposurePoints( - mockCameraControl, mockCamera2CameraControl); - - // Lock focus point. - await camera.setFocusMode(cameraId, FocusMode.locked); - - final VerificationResult verificationResult = - verify(mockCameraControl.startFocusAndMetering(captureAny)); - final FocusMeteringAction capturedAction = - verificationResult.captured.single as FocusMeteringAction; - expect(capturedAction.disableAutoCancel, isTrue); - - // We expect only the default focus point to be set. - final List<(MeteringPoint, int?)> capturedMeteringPointInfos = - capturedAction.meteringPointInfos; - expect(capturedMeteringPointInfos.length, equals(1)); - expect(capturedMeteringPointInfos.first.$1.x, equals(defaultFocusPointX)); - expect(capturedMeteringPointInfos.first.$1.y, equals(defaultFocusPointY)); - expect(capturedMeteringPointInfos.first.$1.size, - equals(defaultFocusPointSize)); - expect(capturedMeteringPointInfos.first.$2, - equals(FocusMeteringAction.flagAf)); - }); + final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); + final MeteringPoint createdMeteringPoint = MeteringPoint.pigeon_detached( + pigeon_instanceManager: testInstanceManager, + ); + MeteringMode? actionBuilderMeteringMode; + MeteringPoint? actionBuilderMeteringPoint; + final MockFocusMeteringActionBuilder mockActionBuilder = + MockFocusMeteringActionBuilder(); + when(mockActionBuilder.build()).thenAnswer( + (_) async => FocusMeteringAction.pigeon_detached( + meteringPointsAe: const [], + meteringPointsAf: const [], + meteringPointsAwb: const [], + isAutoCancelEnabled: false, + pigeon_instanceManager: testInstanceManager, + ), + ); + camera.proxy = getProxyForExposureAndFocus( + newDisplayOrientedMeteringPointFactory: ({ + required CameraInfo cameraInfo, + required double width, + required double height, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockDisplayOrientedMeteringPointFactory mockFactory = + MockDisplayOrientedMeteringPointFactory(); + when( + mockFactory.createPoint(focusPointX, focusPointY), + ).thenAnswer((_) async => createdMeteringPoint); + return mockFactory; + }, + withModeFocusMeteringActionBuilder: ({ + required MeteringMode mode, + required MeteringPoint point, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + actionBuilderMeteringMode = mode; + actionBuilderMeteringPoint = point; + return mockActionBuilder; + }, + ); + + await camera.setFocusPoint(cameraId, focusPoint); + + expect(actionBuilderMeteringPoint, createdMeteringPoint); + expect(actionBuilderMeteringMode, MeteringMode.af); + }, + ); test( - 'setFocusMode re-sets exposure mode if setting locked focus mode while using auto exposure mode', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 11; - final MockCameraControl mockCameraControl = MockCameraControl(); - final FocusMeteringResult mockFocusMeteringResult = - MockFocusMeteringResult(); - final MockCamera2CameraControl mockCamera2CameraControl = - MockCamera2CameraControl(); + 'setFocusPoint disables auto-cancel for focus and metering as expected', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 2; + final MockCameraControl mockCameraControl = MockCameraControl(); + final MockFocusMeteringResult mockFocusMeteringResult = + MockFocusMeteringResult(); + const Point exposurePoint = Point(0.1, 0.2); - // Set directly for test versus calling createCamera. - camera.cameraInfo = MockCameraInfo(); - camera.cameraControl = mockCameraControl; + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; + camera.cameraInfo = MockCameraInfo(); - when(mockCamera2CameraControl.addCaptureRequestOptions(any)) - .thenAnswer((_) async => Future.value()); - - camera.proxy = getProxyForSettingFocusandExposurePoints( - mockCameraControl, mockCamera2CameraControl); - - // Make setting focus and metering action successful for test. - when(mockFocusMeteringResult.isFocusSuccessful()) - .thenAnswer((_) async => Future.value(true)); - when(mockCameraControl.startFocusAndMetering(any)).thenAnswer((_) async => - Future.value(mockFocusMeteringResult)); - - // Set auto exposure mode. - await camera.setExposureMode(cameraId, ExposureMode.auto); - clearInteractions(mockCamera2CameraControl); - - // Lock focus point. - await camera.setFocusMode(cameraId, FocusMode.locked); - - final VerificationResult verificationResult = - verify(mockCamera2CameraControl.addCaptureRequestOptions(captureAny)); - final CaptureRequestOptions capturedCaptureRequestOptions = - verificationResult.captured.single as CaptureRequestOptions; - final List<(CaptureRequestKeySupportedType, Object?)> requestedOptions = - capturedCaptureRequestOptions.requestedOptions; - expect(requestedOptions.length, equals(1)); - expect(requestedOptions.first.$1, - equals(CaptureRequestKeySupportedType.controlAeLock)); - expect(requestedOptions.first.$2, equals(false)); - }); + camera.proxy = getProxyForSettingFocusandExposurePoints( + mockCameraControl, + MockCamera2CameraControl(), + ); - test( - 'setFocusPoint disables auto-cancel if auto focus mode fails to be set after locked focus mode is set', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 22; - final MockCameraControl mockCameraControl = MockCameraControl(); - final MockFocusMeteringResult mockFocusMeteringResult = - MockFocusMeteringResult(); - const Point focusPoint = Point(0.21, 0.21); + // Make setting focus and metering action successful for test. + when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true); + when(mockCameraControl.startFocusAndMetering(any)).thenAnswer( + (_) async => Future.value(mockFocusMeteringResult), + ); - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; - camera.cameraInfo = MockCameraInfo(); - - camera.proxy = getProxyForSettingFocusandExposurePoints( - mockCameraControl, MockCamera2CameraControl()); - - // Make setting focus and metering action successful to set locked focus - // mode. - when(mockFocusMeteringResult.isFocusSuccessful()) - .thenAnswer((_) async => Future.value(true)); - when(mockCameraControl.startFocusAndMetering(any)).thenAnswer((_) async => - Future.value(mockFocusMeteringResult)); - - // Set exposure point to later mock failed call to set an exposure point ( - // otherwise, focus and metering will be canceled altogether, which is - //considered a successful call). - await camera.setExposurePoint(cameraId, const Point(0.3, 0.4)); - - // Set locked focus mode so we can set auto mode (cannot set auto mode - // directly since it is the default). - await camera.setFocusMode(cameraId, FocusMode.locked); - clearInteractions(mockCameraControl); - - // Make setting focus and metering action fail to test that auto-cancel is - // still disabled. - reset(mockFocusMeteringResult); - when(mockFocusMeteringResult.isFocusSuccessful()) - .thenAnswer((_) async => Future.value(false)); - - // Test disabling auto cancel. - await camera.setFocusMode(cameraId, FocusMode.auto); - clearInteractions(mockCameraControl); - - await camera.setFocusPoint(cameraId, focusPoint); - final VerificationResult verificationResult = - verify(mockCameraControl.startFocusAndMetering(captureAny)); - final FocusMeteringAction capturedAction = - verificationResult.captured.single as FocusMeteringAction; - expect(capturedAction.disableAutoCancel, isTrue); - }); + // Test not disabling auto cancel. + await camera.setFocusMode(cameraId, FocusMode.auto); + clearInteractions(mockCameraControl); - test( - 'setExposurePoint disables auto-cancel if auto focus mode fails to be set after locked focus mode is set', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 342; - final MockCameraControl mockCameraControl = MockCameraControl(); - final MockFocusMeteringResult mockFocusMeteringResult = - MockFocusMeteringResult(); - const Point exposurePoint = Point(0.23, 0.32); + await camera.setFocusPoint(cameraId, exposurePoint); + VerificationResult verificationResult = verify( + mockCameraControl.startFocusAndMetering(captureAny), + ); + FocusMeteringAction capturedAction = + verificationResult.captured.single as FocusMeteringAction; + expect(capturedAction.isAutoCancelEnabled, isTrue); - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; - camera.cameraInfo = MockCameraInfo(); - - camera.proxy = getProxyForSettingFocusandExposurePoints( - mockCameraControl, MockCamera2CameraControl()); - - // Make setting focus and metering action successful to set locked focus - // mode. - when(mockFocusMeteringResult.isFocusSuccessful()) - .thenAnswer((_) async => Future.value(true)); - when(mockCameraControl.startFocusAndMetering(any)).thenAnswer((_) async => - Future.value(mockFocusMeteringResult)); - - // Set exposure point to later mock failed call to set an exposure point ( - // otherwise, focus and metering will be canceled altogether, which is - //considered a successful call). - await camera.setExposurePoint(cameraId, const Point(0.4, 0.3)); - - // Set locked focus mode so we can set auto mode (cannot set auto mode - // directly since it is the default). - await camera.setFocusMode(cameraId, FocusMode.locked); - clearInteractions(mockCameraControl); - - // Make setting focus and metering action fail to test that auto-cancel is - // still disabled. - when(mockFocusMeteringResult.isFocusSuccessful()) - .thenAnswer((_) async => Future.value(false)); - - // Test disabling auto cancel. - await camera.setFocusMode(cameraId, FocusMode.auto); - clearInteractions(mockCameraControl); - - await camera.setExposurePoint(cameraId, exposurePoint); - final VerificationResult verificationResult = - verify(mockCameraControl.startFocusAndMetering(captureAny)); - final FocusMeteringAction capturedAction = - verificationResult.captured.single as FocusMeteringAction; - expect(capturedAction.disableAutoCancel, isTrue); - }); + clearInteractions(mockCameraControl); + + // Test disabling auto cancel. + await camera.setFocusMode(cameraId, FocusMode.locked); + clearInteractions(mockCameraControl); + + await camera.setFocusPoint(cameraId, exposurePoint); + verificationResult = verify( + mockCameraControl.startFocusAndMetering(captureAny), + ); + capturedAction = + verificationResult.captured.single as FocusMeteringAction; + expect(capturedAction.isAutoCancelEnabled, isFalse); + }, + ); test( - 'setFocusPoint enables auto-cancel if locked focus mode fails to be set after auto focus mode is set', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 232; - final MockCameraControl mockCameraControl = MockCameraControl(); - final MockFocusMeteringResult mockFocusMeteringResult = - MockFocusMeteringResult(); - const Point focusPoint = Point(0.221, 0.211); + 'setFocusMode does nothing if setting auto-focus mode and is already using auto-focus mode', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 4; + final MockCameraControl mockCameraControl = MockCameraControl(); + final MockFocusMeteringResult mockFocusMeteringResult = + MockFocusMeteringResult(); - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; - camera.cameraInfo = MockCameraInfo(); - - camera.proxy = getProxyForSettingFocusandExposurePoints( - mockCameraControl, MockCamera2CameraControl()); - - // Make setting focus and metering action fail to test auto-cancel is not - // disabled. - when(mockFocusMeteringResult.isFocusSuccessful()) - .thenAnswer((_) async => Future.value(false)); - when(mockCameraControl.startFocusAndMetering(any)).thenAnswer((_) async => - Future.value(mockFocusMeteringResult)); - - // Set exposure point to later mock failed call to set an exposure point. - await camera.setExposurePoint(cameraId, const Point(0.43, 0.34)); - - // Test failing to set locked focus mode. - await camera.setFocusMode(cameraId, FocusMode.locked); - clearInteractions(mockCameraControl); - - await camera.setFocusPoint(cameraId, focusPoint); - final VerificationResult verificationResult = - verify(mockCameraControl.startFocusAndMetering(captureAny)); - final FocusMeteringAction capturedAction = - verificationResult.captured.single as FocusMeteringAction; - expect(capturedAction.disableAutoCancel, isFalse); - }); + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; + camera.cameraInfo = MockCameraInfo(); + + camera.proxy = getProxyForSettingFocusandExposurePoints( + mockCameraControl, + MockCamera2CameraControl(), + ); + + // Make setting focus and metering action successful for test. + when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true); + when(mockCameraControl.startFocusAndMetering(any)).thenAnswer( + (_) async => Future.value(mockFocusMeteringResult), + ); + + // Set locked focus mode and then try to re-set it. + await camera.setFocusMode(cameraId, FocusMode.locked); + clearInteractions(mockCameraControl); + + await camera.setFocusMode(cameraId, FocusMode.locked); + verifyNoMoreInteractions(mockCameraControl); + }, + ); test( - 'setExposurePoint enables auto-cancel if locked focus mode fails to be set after auto focus mode is set', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 323; - final MockCameraControl mockCameraControl = MockCameraControl(); - final MockFocusMeteringResult mockFocusMeteringResult = - MockFocusMeteringResult(); - const Point exposurePoint = Point(0.223, 0.332); + 'setFocusMode does nothing if setting locked focus mode and is already using locked focus mode', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 4; + final MockCameraControl mockCameraControl = MockCameraControl(); - // Set directly for test versus calling createCamera. - camera.cameraControl = mockCameraControl; - camera.cameraInfo = MockCameraInfo(); - - camera.proxy = getProxyForSettingFocusandExposurePoints( - mockCameraControl, MockCamera2CameraControl()); - - // Make setting focus and metering action fail to test auto-cancel is not - // disabled. - when(mockFocusMeteringResult.isFocusSuccessful()) - .thenAnswer((_) async => Future.value(false)); - when(mockCameraControl.startFocusAndMetering(any)).thenAnswer((_) async => - Future.value(mockFocusMeteringResult)); - - // Set exposure point to later mock failed call to set an exposure point. - await camera.setExposurePoint(cameraId, const Point(0.5, 0.2)); - - // Test failing to set locked focus mode. - await camera.setFocusMode(cameraId, FocusMode.locked); - clearInteractions(mockCameraControl); - - await camera.setExposurePoint(cameraId, exposurePoint); - final VerificationResult verificationResult = - verify(mockCameraControl.startFocusAndMetering(captureAny)); - final FocusMeteringAction capturedAction = - verificationResult.captured.single as FocusMeteringAction; - expect(capturedAction.disableAutoCancel, isFalse); - }); + // Camera uses auto-focus by default, so try setting auto mode again. + await camera.setFocusMode(cameraId, FocusMode.auto); + + verifyNoMoreInteractions(mockCameraControl); + }, + ); test( - 'onStreamedFrameAvailable binds ImageAnalysis use case when not already bound', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 22; - final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockCamera mockCamera = MockCamera(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); + 'setFocusMode removes default auto-focus point if previously set and setting auto-focus mode', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 5; + final MockCameraControl mockCameraControl = MockCameraControl(); + final MockFocusMeteringResult mockFocusMeteringResult = + MockFocusMeteringResult(); + final MockCamera2CameraControl mockCamera2CameraControl = + MockCamera2CameraControl(); + const double exposurePointX = 0.2; + const double exposurePointY = 0.7; - // Set directly for test versus calling createCamera. - camera.imageAnalysis = mockImageAnalysis; - camera.processCameraProvider = mockProcessCameraProvider; - camera.cameraSelector = MockCameraSelector(); + // Set directly for test versus calling createCamera. + camera.cameraInfo = MockCameraInfo(); + camera.cameraControl = mockCameraControl; - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; + when( + mockCamera2CameraControl.addCaptureRequestOptions(any), + ).thenAnswer((_) async => Future.value()); - // Tell plugin to create a detached analyzer for testing purposes. - camera.proxy = CameraXProxy( - createAnalyzer: (_) => MockAnalyzer(), - createCameraStateObserver: (_) => MockObserver(), - ); + final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ); + final List createdMeteringPoints = []; + camera.proxy = getProxyForSettingFocusandExposurePoints( + mockCameraControl, + mockCamera2CameraControl, + newDisplayOrientedMeteringPointFactory: ({ + required CameraInfo cameraInfo, + required double width, + required double height, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockDisplayOrientedMeteringPointFactory mockFactory = + MockDisplayOrientedMeteringPointFactory(); + when( + mockFactory.createPoint(exposurePointX, exposurePointY), + ).thenAnswer((_) async { + final MeteringPoint createdMeteringPoint = + MeteringPoint.pigeon_detached( + pigeon_instanceManager: testInstanceManager, + ); + createdMeteringPoints.add(createdMeteringPoint); + return createdMeteringPoint; + }); + when(mockFactory.createPointWithSize(0.5, 0.5, 1)).thenAnswer(( + _, + ) async { + final MeteringPoint createdMeteringPoint = + MeteringPoint.pigeon_detached( + pigeon_instanceManager: testInstanceManager, + ); + createdMeteringPoints.add(createdMeteringPoint); + return createdMeteringPoint; + }); + return mockFactory; + }, + ); - when(mockProcessCameraProvider.isBound(mockImageAnalysis)) - .thenAnswer((_) async => false); - when(mockProcessCameraProvider.bindToLifecycle( - any, [mockImageAnalysis])).thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => MockLiveCameraState()); + // Make setting focus and metering action successful for test. + when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true); + when(mockCameraControl.startFocusAndMetering(any)).thenAnswer( + (_) async => Future.value(mockFocusMeteringResult), + ); + + // Set exposure points. + await camera.setExposurePoint( + cameraId, + const Point(exposurePointX, exposurePointY), + ); - final StreamSubscription imageStreamSubscription = camera - .onStreamedFrameAvailable(cameraId) - .listen((CameraImageData data) {}); + // Lock focus default focus point. + await camera.setFocusMode(cameraId, FocusMode.locked); - await untilCalled(mockImageAnalysis.setAnalyzer(any)); - verify(mockProcessCameraProvider - .bindToLifecycle(camera.cameraSelector, [mockImageAnalysis])); + clearInteractions(mockCameraControl); - await imageStreamSubscription.cancel(); - }); + // Test removal of default focus point. + await camera.setFocusMode(cameraId, FocusMode.auto); + + final VerificationResult verificationResult = verify( + mockCameraControl.startFocusAndMetering(captureAny), + ); + final FocusMeteringAction capturedAction = + verificationResult.captured.single as FocusMeteringAction; + expect(capturedAction.isAutoCancelEnabled, isTrue); + + // We expect only the previously set exposure point to be re-set. + expect(capturedAction.meteringPointsAe.first, createdMeteringPoints[0]); + expect(capturedAction.meteringPointsAe.length, equals(1)); + expect(capturedAction.meteringPointsAf.length, equals(0)); + }, + ); test( - 'startVideoCapturing unbinds ImageAnalysis use case when camera device is not at least level 3, no image streaming callback is specified, and preview is not paused', - () async { - // Set up mocks and constants. - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockPendingRecording mockPendingRecording = MockPendingRecording(); - final MockRecording mockRecording = MockRecording(); - final MockCamera mockCamera = MockCamera(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final MockCamera2CameraInfo mockCamera2CameraInfo = MockCamera2CameraInfo(); - final TestSystemServicesHostApi mockSystemServicesApi = - MockTestSystemServicesHostApi(); - TestSystemServicesHostApi.setup(mockSystemServicesApi); + 'setFocusMode cancels focus and metering if only focus point previously set is a focus point', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 5; + final MockCameraControl mockCameraControl = MockCameraControl(); + final FocusMeteringResult mockFocusMeteringResult = + MockFocusMeteringResult(); + final MockCamera2CameraControl mockCamera2CameraControl = + MockCamera2CameraControl(); - // Set directly for test versus calling createCamera. - camera.processCameraProvider = MockProcessCameraProvider(); - camera.recorder = MockRecorder(); - camera.videoCapture = MockVideoCapture(); - camera.cameraSelector = MockCameraSelector(); - camera.cameraInfo = MockCameraInfo(); - camera.imageAnalysis = MockImageAnalysis(); + // Set directly for test versus calling createCamera. + camera.cameraInfo = MockCameraInfo(); + camera.cameraControl = mockCameraControl; - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; + when( + mockCamera2CameraControl.addCaptureRequestOptions(any), + ).thenAnswer((_) async => Future.value()); - // Tell plugin to create detached Observer when camera info updated. - camera.proxy = CameraXProxy( - createCameraStateObserver: (void Function(Object) onChanged) => - Observer.detached(onChanged: onChanged), - getCamera2CameraInfo: (CameraInfo cameraInfo) => - Future.value(mockCamera2CameraInfo)); - - const int cameraId = 7; - const String outputPath = '/temp/REC123.temp'; - - // Mock method calls. - when(mockSystemServicesApi.getTempFilePath(camera.videoPrefix, '.temp')) - .thenReturn(outputPath); - when(camera.recorder!.prepareRecording(outputPath)) - .thenAnswer((_) async => mockPendingRecording); - when(mockPendingRecording.start()).thenAnswer((_) async => mockRecording); - when(camera.processCameraProvider!.isBound(camera.videoCapture!)) - .thenAnswer((_) async => false); - when(camera.processCameraProvider!.isBound(camera.imageAnalysis!)) - .thenAnswer((_) async => true); - when(camera.processCameraProvider!.bindToLifecycle( - camera.cameraSelector!, [camera.videoCapture!])) - .thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()) - .thenAnswer((_) => Future.value(mockCameraInfo)); - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => MockLiveCameraState()); - when(mockCamera2CameraInfo.getSupportedHardwareLevel()) - .thenAnswer((_) async => CameraMetadata.infoSupportedHardwareLevelFull); - - // Simulate video recording being started so startVideoRecording completes. - PendingRecording.videoRecordingEventStreamController - .add(VideoRecordEvent.start); - - await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); - - verify( - camera.processCameraProvider!.unbind([camera.imageAnalysis!])); - }); + camera.proxy = getProxyForSettingFocusandExposurePoints( + mockCameraControl, + mockCamera2CameraControl, + ); - test( - 'startVideoCapturing unbinds ImageAnalysis use case when image streaming callback not specified, camera device is level 3, and preview is not paused', - () async { - // Set up mocks and constants. - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockPendingRecording mockPendingRecording = MockPendingRecording(); - final MockRecording mockRecording = MockRecording(); - final MockCamera mockCamera = MockCamera(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final MockCamera2CameraInfo mockCamera2CameraInfo = MockCamera2CameraInfo(); - final TestSystemServicesHostApi mockSystemServicesApi = - MockTestSystemServicesHostApi(); - TestSystemServicesHostApi.setup(mockSystemServicesApi); + // Make setting focus and metering action successful for test. + when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true); + when(mockCameraControl.startFocusAndMetering(any)).thenAnswer( + (_) async => Future.value(mockFocusMeteringResult), + ); - // Set directly for test versus calling createCamera. - camera.processCameraProvider = MockProcessCameraProvider(); - camera.recorder = MockRecorder(); - camera.videoCapture = MockVideoCapture(); - camera.cameraSelector = MockCameraSelector(); - camera.cameraInfo = MockCameraInfo(); - camera.imageAnalysis = MockImageAnalysis(); + // Lock focus default focus point. + await camera.setFocusMode(cameraId, FocusMode.locked); - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; + // Test removal of default focus point. + await camera.setFocusMode(cameraId, FocusMode.auto); - // Tell plugin to create detached Observer when camera info updated. - camera.proxy = CameraXProxy( - createCameraStateObserver: (void Function(Object) onChanged) => - Observer.detached(onChanged: onChanged), - getCamera2CameraInfo: (CameraInfo cameraInfo) => - Future.value(mockCamera2CameraInfo)); - - const int cameraId = 77; - const String outputPath = '/temp/REC123.temp'; - - // Mock method calls. - when(mockSystemServicesApi.getTempFilePath(camera.videoPrefix, '.temp')) - .thenReturn(outputPath); - when(camera.recorder!.prepareRecording(outputPath)) - .thenAnswer((_) async => mockPendingRecording); - when(mockPendingRecording.start()).thenAnswer((_) async => mockRecording); - when(camera.processCameraProvider!.isBound(camera.videoCapture!)) - .thenAnswer((_) async => false); - when(camera.processCameraProvider!.isBound(camera.imageAnalysis!)) - .thenAnswer((_) async => true); - when(camera.processCameraProvider!.bindToLifecycle( - camera.cameraSelector!, [camera.videoCapture!])) - .thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()) - .thenAnswer((_) => Future.value(mockCameraInfo)); - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => MockLiveCameraState()); - when(mockCamera2CameraInfo.getSupportedHardwareLevel()) - .thenAnswer((_) async => CameraMetadata.infoSupportedHardwareLevel3); - - // Simulate video recording being started so startVideoRecording completes. - PendingRecording.videoRecordingEventStreamController - .add(VideoRecordEvent.start); - - await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); - - verify( - camera.processCameraProvider!.unbind([camera.imageAnalysis!])); - }); + verify(mockCameraControl.cancelFocusAndMetering()); + }, + ); test( - 'startVideoCapturing unbinds ImageAnalysis use case when image streaming callback is specified, camera device is not at least level 3, and preview is not paused', - () async { - // Set up mocks and constants. - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockPendingRecording mockPendingRecording = MockPendingRecording(); - final MockRecording mockRecording = MockRecording(); - final MockCamera mockCamera = MockCamera(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final MockCamera2CameraInfo mockCamera2CameraInfo = MockCamera2CameraInfo(); - final TestSystemServicesHostApi mockSystemServicesApi = - MockTestSystemServicesHostApi(); - TestSystemServicesHostApi.setup(mockSystemServicesApi); + 'setFocusMode re-focuses on previously set auto-focus point with auto-canceled enabled if setting auto-focus mode', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 6; + final MockCameraControl mockCameraControl = MockCameraControl(); + final FocusMeteringResult mockFocusMeteringResult = + MockFocusMeteringResult(); + final MockCamera2CameraControl mockCamera2CameraControl = + MockCamera2CameraControl(); + const double focusPointX = 0.1; + const double focusPointY = 0.2; - // Set directly for test versus calling createCamera. - camera.processCameraProvider = MockProcessCameraProvider(); - camera.recorder = MockRecorder(); - camera.videoCapture = MockVideoCapture(); - camera.cameraSelector = MockCameraSelector(); - camera.cameraInfo = MockCameraInfo(); - camera.imageAnalysis = MockImageAnalysis(); + // Set directly for test versus calling createCamera. + camera.cameraInfo = MockCameraInfo(); + camera.cameraControl = mockCameraControl; - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; + when( + mockCamera2CameraControl.addCaptureRequestOptions(any), + ).thenAnswer((_) async => Future.value()); - // Tell plugin to create detached Observer when camera info updated. - camera.proxy = CameraXProxy( - createCameraStateObserver: (void Function(Object) onChanged) => - Observer.detached(onChanged: onChanged), - getCamera2CameraInfo: (CameraInfo cameraInfo) => - Future.value(mockCamera2CameraInfo)); - - const int cameraId = 87; - const String outputPath = '/temp/REC123.temp'; - - // Mock method calls. - when(mockSystemServicesApi.getTempFilePath(camera.videoPrefix, '.temp')) - .thenReturn(outputPath); - when(camera.recorder!.prepareRecording(outputPath)) - .thenAnswer((_) async => mockPendingRecording); - when(mockPendingRecording.start()).thenAnswer((_) async => mockRecording); - when(camera.processCameraProvider!.isBound(camera.videoCapture!)) - .thenAnswer((_) async => false); - when(camera.processCameraProvider!.isBound(camera.imageAnalysis!)) - .thenAnswer((_) async => true); - when(camera.processCameraProvider!.bindToLifecycle( - camera.cameraSelector!, [camera.videoCapture!])) - .thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()) - .thenAnswer((_) => Future.value(mockCameraInfo)); - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => MockLiveCameraState()); - when(mockCamera2CameraInfo.getSupportedHardwareLevel()).thenAnswer( - (_) async => CameraMetadata.infoSupportedHardwareLevelExternal); - - // Simulate video recording being started so startVideoRecording completes. - PendingRecording.videoRecordingEventStreamController - .add(VideoRecordEvent.start); - - await camera.startVideoCapturing(VideoCaptureOptions(cameraId, - streamCallback: (CameraImageData image) {})); - verify( - camera.processCameraProvider!.unbind([camera.imageAnalysis!])); - }); + camera.proxy = getProxyForSettingFocusandExposurePoints( + mockCameraControl, + mockCamera2CameraControl, + ); - test( - 'startVideoCapturing unbinds ImageCapture use case when image streaming callback is specified, camera device is at least level 3, and preview is not paused', - () async { - // Set up mocks and constants. - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockPendingRecording mockPendingRecording = MockPendingRecording(); - final MockRecording mockRecording = MockRecording(); - final MockCamera mockCamera = MockCamera(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final MockCamera2CameraInfo mockCamera2CameraInfo = MockCamera2CameraInfo(); - final TestSystemServicesHostApi mockSystemServicesApi = - MockTestSystemServicesHostApi(); - TestSystemServicesHostApi.setup(mockSystemServicesApi); + // Make setting focus and metering action successful for test. + when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true); + when(mockCameraControl.startFocusAndMetering(any)).thenAnswer( + (_) async => Future.value(mockFocusMeteringResult), + ); - // Set directly for test versus calling createCamera. - camera.processCameraProvider = MockProcessCameraProvider(); - camera.recorder = MockRecorder(); - camera.videoCapture = MockVideoCapture(); - camera.cameraSelector = MockCameraSelector(); - camera.cameraInfo = MockCameraInfo(); - camera.imageAnalysis = MockImageAnalysis(); - camera.imageCapture = MockImageCapture(); - - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; - - // Tell plugin to create detached Observer when camera info updated. - camera.proxy = CameraXProxy( - createAnalyzer: - (Future Function(ImageProxy imageProxy) analyze) => - Analyzer.detached(analyze: analyze), - createCameraStateObserver: (void Function(Object) onChanged) => - Observer.detached(onChanged: onChanged), - getCamera2CameraInfo: (CameraInfo cameraInfo) => - Future.value(mockCamera2CameraInfo)); - - const int cameraId = 107; - const String outputPath = '/temp/REC123.temp'; - - // Mock method calls. - when(mockSystemServicesApi.getTempFilePath(camera.videoPrefix, '.temp')) - .thenReturn(outputPath); - when(camera.recorder!.prepareRecording(outputPath)) - .thenAnswer((_) async => mockPendingRecording); - when(mockPendingRecording.start()).thenAnswer((_) async => mockRecording); - when(camera.processCameraProvider!.isBound(camera.videoCapture!)) - .thenAnswer((_) async => false); - when(camera.processCameraProvider!.isBound(camera.imageCapture!)) - .thenAnswer((_) async => true); - when(camera.processCameraProvider!.isBound(camera.imageAnalysis!)) - .thenAnswer((_) async => true); - when(camera.processCameraProvider!.bindToLifecycle( - camera.cameraSelector!, [camera.videoCapture!])) - .thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()) - .thenAnswer((_) => Future.value(mockCameraInfo)); - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => MockLiveCameraState()); - when(mockCamera2CameraInfo.getSupportedHardwareLevel()) - .thenAnswer((_) async => CameraMetadata.infoSupportedHardwareLevel3); - - // Simulate video recording being started so startVideoRecording completes. - PendingRecording.videoRecordingEventStreamController - .add(VideoRecordEvent.start); - - await camera.startVideoCapturing(VideoCaptureOptions(cameraId, - streamCallback: (CameraImageData image) {})); - verify( - camera.processCameraProvider!.unbind([camera.imageCapture!])); - }); + // Lock a focus point. + await camera.setFocusPoint( + cameraId, + const Point(focusPointX, focusPointY), + ); + await camera.setFocusMode(cameraId, FocusMode.locked); - test( - 'startVideoCapturing does not unbind ImageCapture or ImageAnalysis use cases when preview is paused', - () async { - // Set up mocks and constants. - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockPendingRecording mockPendingRecording = MockPendingRecording(); - final MockRecording mockRecording = MockRecording(); - final MockCamera mockCamera = MockCamera(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final MockCamera2CameraInfo mockCamera2CameraInfo = MockCamera2CameraInfo(); - final TestSystemServicesHostApi mockSystemServicesApi = - MockTestSystemServicesHostApi(); - TestSystemServicesHostApi.setup(mockSystemServicesApi); + clearInteractions(mockCameraControl); - // Set directly for test versus calling createCamera. - camera.processCameraProvider = MockProcessCameraProvider(); - camera.recorder = MockRecorder(); - camera.videoCapture = MockVideoCapture(); - camera.cameraSelector = MockCameraSelector(); - camera.cameraInfo = MockCameraInfo(); - camera.imageAnalysis = MockImageAnalysis(); - camera.imageCapture = MockImageCapture(); - camera.preview = MockPreview(); - - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; - - // Tell plugin to create detached Observer when camera info updated. - camera.proxy = CameraXProxy( - createCameraStateObserver: (void Function(Object) onChanged) => - Observer.detached(onChanged: onChanged), - getCamera2CameraInfo: (CameraInfo cameraInfo) => - Future.value(mockCamera2CameraInfo)); - - const int cameraId = 97; - const String outputPath = '/temp/REC123.temp'; - - // Mock method calls. - when(mockSystemServicesApi.getTempFilePath(camera.videoPrefix, '.temp')) - .thenReturn(outputPath); - when(camera.recorder!.prepareRecording(outputPath)) - .thenAnswer((_) async => mockPendingRecording); - when(mockPendingRecording.start()).thenAnswer((_) async => mockRecording); - when(camera.processCameraProvider!.isBound(camera.videoCapture!)) - .thenAnswer((_) async => false); - when(camera.processCameraProvider!.bindToLifecycle( - camera.cameraSelector!, [camera.videoCapture!])) - .thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()) - .thenAnswer((_) => Future.value(mockCameraInfo)); - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => MockLiveCameraState()); - - await camera.pausePreview(cameraId); - - // Simulate video recording being started so startVideoRecording completes. - PendingRecording.videoRecordingEventStreamController - .add(VideoRecordEvent.start); - - await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); - - verifyNever( - camera.processCameraProvider!.unbind([camera.imageCapture!])); - verifyNever( - camera.processCameraProvider!.unbind([camera.imageAnalysis!])); - }); + // Test re-focusing on previously set auto-focus point with auto-cancel enabled. + await camera.setFocusMode(cameraId, FocusMode.auto); + + final VerificationResult verificationResult = verify( + mockCameraControl.startFocusAndMetering(captureAny), + ); + final FocusMeteringAction capturedAction = + verificationResult.captured.single as FocusMeteringAction; + expect(capturedAction.isAutoCancelEnabled, isTrue); + expect(capturedAction.meteringPointsAe.length, equals(0)); + expect(capturedAction.meteringPointsAf.length, equals(1)); + expect(capturedAction.meteringPointsAwb.length, equals(0)); + final TestMeteringPoint focusPoint = + capturedAction.meteringPointsAf.single as TestMeteringPoint; + expect(focusPoint.x, equals(focusPointX)); + expect(focusPoint.y, equals(focusPointY)); + expect(focusPoint.size, isNull); + }, + ); test( - 'startVideoCapturing unbinds ImageCapture and ImageAnalysis use cases when running on a legacy hardware device', - () async { - // Set up mocks and constants. - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockPendingRecording mockPendingRecording = MockPendingRecording(); - final MockRecording mockRecording = MockRecording(); - final MockCamera mockCamera = MockCamera(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final MockCamera2CameraInfo mockCamera2CameraInfo = MockCamera2CameraInfo(); - final TestSystemServicesHostApi mockSystemServicesApi = - MockTestSystemServicesHostApi(); - TestSystemServicesHostApi.setup(mockSystemServicesApi); + 'setFocusMode starts expected focus and metering action with previously set auto-focus point if setting locked focus mode and current focus and metering action has auto-focus point', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 7; + final MockCameraControl mockCameraControl = MockCameraControl(); + final MockCamera2CameraControl mockCamera2CameraControl = + MockCamera2CameraControl(); + const double focusPointX = 0.88; + const double focusPointY = 0.33; - // Set directly for test versus calling createCamera. - camera.processCameraProvider = MockProcessCameraProvider(); - camera.recorder = MockRecorder(); - camera.videoCapture = MockVideoCapture(); - camera.cameraSelector = MockCameraSelector(); - camera.cameraInfo = MockCameraInfo(); - camera.imageAnalysis = MockImageAnalysis(); - camera.imageCapture = MockImageCapture(); - camera.preview = MockPreview(); - - // Ignore setting target rotation for this test; tested seprately. - camera.captureOrientationLocked = true; - - // Tell plugin to create detached Observer when camera info updated. - camera.proxy = CameraXProxy( - createCameraStateObserver: (void Function(Object) onChanged) => - Observer.detached(onChanged: onChanged), - getCamera2CameraInfo: (CameraInfo cameraInfo) => - Future.value(mockCamera2CameraInfo)); + // Set directly for test versus calling createCamera. + camera.cameraInfo = MockCameraInfo(); + camera.cameraControl = mockCameraControl; - const int cameraId = 44; - const String outputPath = '/temp/REC123.temp'; - - // Mock method calls. - when(mockSystemServicesApi.getTempFilePath(camera.videoPrefix, '.temp')) - .thenReturn(outputPath); - when(camera.recorder!.prepareRecording(outputPath)) - .thenAnswer((_) async => mockPendingRecording); - when(mockPendingRecording.start()).thenAnswer((_) async => mockRecording); - when(camera.processCameraProvider!.isBound(camera.videoCapture!)) - .thenAnswer((_) async => false); - when(camera.processCameraProvider!.isBound(camera.imageCapture!)) - .thenAnswer((_) async => true); - when(camera.processCameraProvider!.isBound(camera.imageAnalysis!)) - .thenAnswer((_) async => true); - when(camera.processCameraProvider!.bindToLifecycle( - camera.cameraSelector!, [camera.videoCapture!])) - .thenAnswer((_) async => mockCamera); - when(mockCamera.getCameraInfo()) - .thenAnswer((_) => Future.value(mockCameraInfo)); - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => MockLiveCameraState()); - when(mockCamera2CameraInfo.getSupportedHardwareLevel()).thenAnswer( - (_) async => CameraMetadata.infoSupportedHardwareLevelLegacy); - - // Simulate video recording being started so startVideoRecording completes. - PendingRecording.videoRecordingEventStreamController - .add(VideoRecordEvent.start); - - await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); - - verify( - camera.processCameraProvider!.unbind([camera.imageCapture!])); - verify( - camera.processCameraProvider!.unbind([camera.imageAnalysis!])); - }); + when( + mockCamera2CameraControl.addCaptureRequestOptions(any), + ).thenAnswer((_) async => Future.value()); - test( - 'prepareForVideoRecording does not make any calls involving starting video recording', - () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); + camera.proxy = getProxyForSettingFocusandExposurePoints( + mockCameraControl, + mockCamera2CameraControl, + ); - // Set directly for test versus calling createCamera. - camera.processCameraProvider = MockProcessCameraProvider(); - camera.recorder = MockRecorder(); - camera.videoCapture = MockVideoCapture(); - camera.camera = MockCamera(); - - await camera.prepareForVideoRecording(); - verifyNoMoreInteractions(camera.processCameraProvider); - verifyNoMoreInteractions(camera.recorder); - verifyNoMoreInteractions(camera.videoCapture); - verifyNoMoreInteractions(camera.camera); - }); + // Set a focus point. + await camera.setFocusPoint( + cameraId, + const Point(focusPointX, focusPointY), + ); + clearInteractions(mockCameraControl); + + // Lock focus point. + await camera.setFocusMode(cameraId, FocusMode.locked); + + final VerificationResult verificationResult = verify( + mockCameraControl.startFocusAndMetering(captureAny), + ); + final FocusMeteringAction capturedAction = + verificationResult.captured.single as FocusMeteringAction; + expect(capturedAction.isAutoCancelEnabled, isFalse); + + // We expect the set focus point to be locked. + expect(capturedAction.meteringPointsAe.length, equals(0)); + expect(capturedAction.meteringPointsAf.length, equals(1)); + expect(capturedAction.meteringPointsAwb.length, equals(0)); + + final TestMeteringPoint focusPoint = + capturedAction.meteringPointsAf.single as TestMeteringPoint; + expect(focusPoint.x, equals(focusPointX)); + expect(focusPoint.y, equals(focusPointY)); + expect(focusPoint.size, isNull); + }, + ); + + test( + 'setFocusMode starts expected focus and metering action with previously set auto-focus point if setting locked focus mode and current focus and metering action has auto-focus point amongst others', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 8; + final MockCameraControl mockCameraControl = MockCameraControl(); + final MockCamera2CameraControl mockCamera2CameraControl = + MockCamera2CameraControl(); + const double focusPointX = 0.38; + const double focusPointY = 0.38; + const double exposurePointX = 0.54; + const double exposurePointY = 0.45; + + // Set directly for test versus calling createCamera. + camera.cameraInfo = MockCameraInfo(); + camera.cameraControl = mockCameraControl; + + when( + mockCamera2CameraControl.addCaptureRequestOptions(any), + ).thenAnswer((_) async => Future.value()); + + camera.proxy = getProxyForSettingFocusandExposurePoints( + mockCameraControl, + mockCamera2CameraControl, + ); + + // Set focus and exposure points. + await camera.setFocusPoint( + cameraId, + const Point(focusPointX, focusPointY), + ); + await camera.setExposurePoint( + cameraId, + const Point(exposurePointX, exposurePointY), + ); + clearInteractions(mockCameraControl); + + // Lock focus point. + await camera.setFocusMode(cameraId, FocusMode.locked); + + final VerificationResult verificationResult = verify( + mockCameraControl.startFocusAndMetering(captureAny), + ); + final FocusMeteringAction capturedAction = + verificationResult.captured.single as FocusMeteringAction; + expect(capturedAction.isAutoCancelEnabled, isFalse); + + // We expect two MeteringPoints, the set focus point and the set exposure + // point. + expect(capturedAction.meteringPointsAe.length, equals(1)); + expect(capturedAction.meteringPointsAf.length, equals(1)); + expect(capturedAction.meteringPointsAwb.length, equals(0)); + + final TestMeteringPoint focusPoint = + capturedAction.meteringPointsAf.single as TestMeteringPoint; + expect(focusPoint.x, equals(focusPointX)); + expect(focusPoint.y, equals(focusPointY)); + expect(focusPoint.size, isNull); + + final TestMeteringPoint exposurePoint = + capturedAction.meteringPointsAe.single as TestMeteringPoint; + expect(exposurePoint.x, equals(exposurePointX)); + expect(exposurePoint.y, equals(exposurePointY)); + expect(exposurePoint.size, isNull); + }, + ); + + test( + 'setFocusMode starts expected focus and metering action if setting locked focus mode and current focus and metering action does not contain an auto-focus point', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 9; + final MockCameraControl mockCameraControl = MockCameraControl(); + final MockCamera2CameraControl mockCamera2CameraControl = + MockCamera2CameraControl(); + const double exposurePointX = 0.8; + const double exposurePointY = 0.3; + const double defaultFocusPointX = 0.5; + const double defaultFocusPointY = 0.5; + const double defaultFocusPointSize = 1; + + // Set directly for test versus calling createCamera. + camera.cameraInfo = MockCameraInfo(); + camera.cameraControl = mockCameraControl; + + when( + mockCamera2CameraControl.addCaptureRequestOptions(any), + ).thenAnswer((_) async => Future.value()); + + camera.proxy = getProxyForSettingFocusandExposurePoints( + mockCameraControl, + mockCamera2CameraControl, + ); + + // Set an exposure point (creates a current focus and metering action + // without a focus point). + await camera.setExposurePoint( + cameraId, + const Point(exposurePointX, exposurePointY), + ); + clearInteractions(mockCameraControl); + + // Lock focus point. + await camera.setFocusMode(cameraId, FocusMode.locked); + + final VerificationResult verificationResult = verify( + mockCameraControl.startFocusAndMetering(captureAny), + ); + final FocusMeteringAction capturedAction = + verificationResult.captured.single as FocusMeteringAction; + expect(capturedAction.isAutoCancelEnabled, isFalse); + + // We expect two MeteringPoints, the default focus point and the set + //exposure point. + expect(capturedAction.meteringPointsAe.length, equals(1)); + expect(capturedAction.meteringPointsAf.length, equals(1)); + expect(capturedAction.meteringPointsAwb.length, equals(0)); + + final TestMeteringPoint focusPoint = + capturedAction.meteringPointsAf.single as TestMeteringPoint; + expect(focusPoint.x, equals(defaultFocusPointX)); + expect(focusPoint.y, equals(defaultFocusPointY)); + expect(focusPoint.size, equals(defaultFocusPointSize)); + + final TestMeteringPoint exposurePoint = + capturedAction.meteringPointsAe.single as TestMeteringPoint; + expect(exposurePoint.x, equals(exposurePointX)); + expect(exposurePoint.y, equals(exposurePointY)); + expect(exposurePoint.size, isNull); + }, + ); + + test( + 'setFocusMode starts expected focus and metering action if there is no current focus and metering action', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 10; + final MockCameraControl mockCameraControl = MockCameraControl(); + final MockCamera2CameraControl mockCamera2CameraControl = + MockCamera2CameraControl(); + const double defaultFocusPointX = 0.5; + const double defaultFocusPointY = 0.5; + const double defaultFocusPointSize = 1; + + // Set directly for test versus calling createCamera. + camera.cameraInfo = MockCameraInfo(); + camera.cameraControl = mockCameraControl; + + when( + mockCamera2CameraControl.addCaptureRequestOptions(any), + ).thenAnswer((_) async => Future.value()); + + camera.proxy = getProxyForSettingFocusandExposurePoints( + mockCameraControl, + mockCamera2CameraControl, + ); + + // Lock focus point. + await camera.setFocusMode(cameraId, FocusMode.locked); + + final VerificationResult verificationResult = verify( + mockCameraControl.startFocusAndMetering(captureAny), + ); + final FocusMeteringAction capturedAction = + verificationResult.captured.single as FocusMeteringAction; + expect(capturedAction.isAutoCancelEnabled, isFalse); + + // We expect only the default focus point to be set. + expect(capturedAction.meteringPointsAe.length, equals(0)); + expect(capturedAction.meteringPointsAf.length, equals(1)); + expect(capturedAction.meteringPointsAwb.length, equals(0)); + + final TestMeteringPoint focusPoint = + capturedAction.meteringPointsAf.single as TestMeteringPoint; + expect(focusPoint.x, equals(defaultFocusPointX)); + expect(focusPoint.y, equals(defaultFocusPointY)); + expect(focusPoint.size, equals(defaultFocusPointSize)); + }, + ); + + test( + 'setFocusMode re-sets exposure mode if setting locked focus mode while using auto exposure mode', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 11; + final MockCameraControl mockCameraControl = MockCameraControl(); + final FocusMeteringResult mockFocusMeteringResult = + MockFocusMeteringResult(); + final MockCamera2CameraControl mockCamera2CameraControl = + MockCamera2CameraControl(); + + // Set directly for test versus calling createCamera. + camera.cameraInfo = MockCameraInfo(); + camera.cameraControl = mockCameraControl; + + when( + mockCamera2CameraControl.addCaptureRequestOptions(any), + ).thenAnswer((_) async => Future.value()); + + camera.proxy = getProxyForSettingFocusandExposurePoints( + mockCameraControl, + mockCamera2CameraControl, + ); + + // Make setting focus and metering action successful for test. + when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true); + when(mockCameraControl.startFocusAndMetering(any)).thenAnswer( + (_) async => Future.value(mockFocusMeteringResult), + ); + + // Set auto exposure mode. + await camera.setExposureMode(cameraId, ExposureMode.auto); + clearInteractions(mockCamera2CameraControl); + + // Lock focus point. + await camera.setFocusMode(cameraId, FocusMode.locked); + + final VerificationResult verificationResult = verify( + mockCamera2CameraControl.addCaptureRequestOptions(captureAny), + ); + final CaptureRequestOptions capturedCaptureRequestOptions = + verificationResult.captured.single as CaptureRequestOptions; + expect( + await capturedCaptureRequestOptions.getCaptureRequestOption( + camera.proxy.controlAELockCaptureRequest(), + ), + isFalse, + ); + }, + ); + + test( + 'setFocusPoint disables auto-cancel if auto focus mode fails to be set after locked focus mode is set', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 22; + final MockCameraControl mockCameraControl = MockCameraControl(); + final MockFocusMeteringResult mockFocusMeteringResult = + MockFocusMeteringResult(); + const Point focusPoint = Point(0.21, 0.21); + + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; + camera.cameraInfo = MockCameraInfo(); + + camera.proxy = getProxyForSettingFocusandExposurePoints( + mockCameraControl, + MockCamera2CameraControl(), + ); + + // Make setting focus and metering action successful to set locked focus + // mode. + when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true); + when(mockCameraControl.startFocusAndMetering(any)).thenAnswer( + (_) async => Future.value(mockFocusMeteringResult), + ); + + // Set exposure point to later mock failed call to set an exposure point ( + // otherwise, focus and metering will be canceled altogether, which is + //considered a successful call). + await camera.setExposurePoint(cameraId, const Point(0.3, 0.4)); + + // Set locked focus mode so we can set auto mode (cannot set auto mode + // directly since it is the default). + await camera.setFocusMode(cameraId, FocusMode.locked); + clearInteractions(mockCameraControl); + + // Make setting focus and metering action fail to test that auto-cancel is + // still disabled. + reset(mockFocusMeteringResult); + when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(false); + + // Test disabling auto cancel. + await camera.setFocusMode(cameraId, FocusMode.auto); + clearInteractions(mockCameraControl); + + await camera.setFocusPoint(cameraId, focusPoint); + final VerificationResult verificationResult = verify( + mockCameraControl.startFocusAndMetering(captureAny), + ); + final FocusMeteringAction capturedAction = + verificationResult.captured.single as FocusMeteringAction; + expect(capturedAction.isAutoCancelEnabled, isFalse); + }, + ); + + test( + 'setExposurePoint disables auto-cancel if auto focus mode fails to be set after locked focus mode is set', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 342; + final MockCameraControl mockCameraControl = MockCameraControl(); + final MockFocusMeteringResult mockFocusMeteringResult = + MockFocusMeteringResult(); + const Point exposurePoint = Point(0.23, 0.32); + + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; + camera.cameraInfo = MockCameraInfo(); + + camera.proxy = getProxyForSettingFocusandExposurePoints( + mockCameraControl, + MockCamera2CameraControl(), + ); + + // Make setting focus and metering action successful to set locked focus + // mode. + when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(true); + when(mockCameraControl.startFocusAndMetering(any)).thenAnswer( + (_) async => Future.value(mockFocusMeteringResult), + ); + + // Set exposure point to later mock failed call to set an exposure point ( + // otherwise, focus and metering will be canceled altogether, which is + //considered a successful call). + await camera.setExposurePoint(cameraId, const Point(0.4, 0.3)); + + // Set locked focus mode so we can set auto mode (cannot set auto mode + // directly since it is the default). + await camera.setFocusMode(cameraId, FocusMode.locked); + clearInteractions(mockCameraControl); + + // Make setting focus and metering action fail to test that auto-cancel is + // still disabled. + when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(false); + + // Test disabling auto cancel. + await camera.setFocusMode(cameraId, FocusMode.auto); + clearInteractions(mockCameraControl); + + await camera.setExposurePoint(cameraId, exposurePoint); + final VerificationResult verificationResult = verify( + mockCameraControl.startFocusAndMetering(captureAny), + ); + final FocusMeteringAction capturedAction = + verificationResult.captured.single as FocusMeteringAction; + expect(capturedAction.isAutoCancelEnabled, isFalse); + }, + ); + + test( + 'setFocusPoint enables auto-cancel if locked focus mode fails to be set after auto focus mode is set', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 232; + final MockCameraControl mockCameraControl = MockCameraControl(); + final MockFocusMeteringResult mockFocusMeteringResult = + MockFocusMeteringResult(); + const Point focusPoint = Point(0.221, 0.211); + + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; + camera.cameraInfo = MockCameraInfo(); + + camera.proxy = getProxyForSettingFocusandExposurePoints( + mockCameraControl, + MockCamera2CameraControl(), + ); + + // Make setting focus and metering action fail to test auto-cancel is not + // disabled. + when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(false); + when(mockCameraControl.startFocusAndMetering(any)).thenAnswer( + (_) async => Future.value(mockFocusMeteringResult), + ); + + // Set exposure point to later mock failed call to set an exposure point. + await camera.setExposurePoint(cameraId, const Point(0.43, 0.34)); + + // Test failing to set locked focus mode. + await camera.setFocusMode(cameraId, FocusMode.locked); + clearInteractions(mockCameraControl); + + await camera.setFocusPoint(cameraId, focusPoint); + final VerificationResult verificationResult = verify( + mockCameraControl.startFocusAndMetering(captureAny), + ); + final FocusMeteringAction capturedAction = + verificationResult.captured.single as FocusMeteringAction; + expect(capturedAction.isAutoCancelEnabled, isTrue); + }, + ); + + test( + 'setExposurePoint enables auto-cancel if locked focus mode fails to be set after auto focus mode is set', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 323; + final MockCameraControl mockCameraControl = MockCameraControl(); + final MockFocusMeteringResult mockFocusMeteringResult = + MockFocusMeteringResult(); + const Point exposurePoint = Point(0.223, 0.332); + + // Set directly for test versus calling createCamera. + camera.cameraControl = mockCameraControl; + camera.cameraInfo = MockCameraInfo(); + + camera.proxy = getProxyForSettingFocusandExposurePoints( + mockCameraControl, + MockCamera2CameraControl(), + ); + + // Make setting focus and metering action fail to test auto-cancel is not + // disabled. + when(mockFocusMeteringResult.isFocusSuccessful).thenReturn(false); + when(mockCameraControl.startFocusAndMetering(any)).thenAnswer( + (_) async => Future.value(mockFocusMeteringResult), + ); + + // Set exposure point to later mock failed call to set an exposure point. + await camera.setExposurePoint(cameraId, const Point(0.5, 0.2)); + + // Test failing to set locked focus mode. + await camera.setFocusMode(cameraId, FocusMode.locked); + clearInteractions(mockCameraControl); + + await camera.setExposurePoint(cameraId, exposurePoint); + final VerificationResult verificationResult = verify( + mockCameraControl.startFocusAndMetering(captureAny), + ); + final FocusMeteringAction capturedAction = + verificationResult.captured.single as FocusMeteringAction; + expect(capturedAction.isAutoCancelEnabled, isTrue); + }, + ); + + test( + 'onStreamedFrameAvailable binds ImageAnalysis use case when not already bound', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 22; + final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); + final MockProcessCameraProvider mockProcessCameraProvider = + MockProcessCameraProvider(); + final MockCamera mockCamera = MockCamera(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); + + // Set directly for test versus calling createCamera. + camera.imageAnalysis = mockImageAnalysis; + camera.processCameraProvider = mockProcessCameraProvider; + camera.cameraSelector = MockCameraSelector(); + + // Ignore setting target rotation for this test; tested seprately. + camera.captureOrientationLocked = true; + + // Tell plugin to create a detached analyzer for testing purposes. + camera.proxy = CameraXProxy( + newAnalyzer: ({ + required void Function(Analyzer, ImageProxy) analyze, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + MockAnalyzer(), + newObserver: ({ + required void Function(Observer, T) onChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Observer.detached( + onChanged: onChanged, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + ); + + when( + mockProcessCameraProvider.isBound(mockImageAnalysis), + ).thenAnswer((_) async => false); + when( + mockProcessCameraProvider.bindToLifecycle(any, [ + mockImageAnalysis, + ]), + ).thenAnswer((_) async => mockCamera); + when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => MockLiveCameraState()); + + final StreamSubscription imageStreamSubscription = camera + .onStreamedFrameAvailable(cameraId) + .listen((CameraImageData data) {}); + + await untilCalled(mockImageAnalysis.setAnalyzer(any)); + verify( + mockProcessCameraProvider.bindToLifecycle( + camera.cameraSelector, + [mockImageAnalysis], + ), + ); + + await imageStreamSubscription.cancel(); + }, + ); + + test( + 'startVideoCapturing unbinds ImageAnalysis use case when camera device is not at least level 3, no image streaming callback is specified, and preview is not paused', + () async { + // Set up mocks and constants. + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final MockPendingRecording mockPendingRecording = MockPendingRecording(); + final MockRecording mockRecording = MockRecording(); + final MockCamera mockCamera = MockCamera(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final MockCamera2CameraInfo mockCamera2CameraInfo = + MockCamera2CameraInfo(); + + // Set directly for test versus calling createCamera. + camera.processCameraProvider = MockProcessCameraProvider(); + camera.recorder = MockRecorder(); + camera.videoCapture = MockVideoCapture(); + camera.cameraSelector = MockCameraSelector(); + camera.cameraInfo = MockCameraInfo(); + camera.imageAnalysis = MockImageAnalysis(); + + // Ignore setting target rotation for this test; tested seprately. + camera.captureOrientationLocked = true; + + // Tell plugin to create detached Observer when camera info updated. + const String outputPath = '/temp/REC123.temp'; + camera.proxy = CameraXProxy( + newObserver: ({ + required void Function(Observer, T) onChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Observer.detached( + onChanged: onChanged, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + fromCamera2CameraInfo: ({ + required CameraInfo cameraInfo, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + mockCamera2CameraInfo, + newSystemServicesManager: ({ + required void Function(SystemServicesManager, String) onCameraError, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockSystemServicesManager mockSystemServicesManager = + MockSystemServicesManager(); + when( + mockSystemServicesManager.getTempFilePath( + camera.videoPrefix, + '.temp', + ), + ).thenAnswer((_) async => outputPath); + return mockSystemServicesManager; + }, + newVideoRecordEventListener: ({ + required void Function(VideoRecordEventListener, VideoRecordEvent) + onEvent, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return VideoRecordEventListener.pigeon_detached( + onEvent: onEvent, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + infoSupportedHardwareLevelCameraCharacteristics: () { + return MockCameraCharacteristicsKey(); + }, + ); + + const int cameraId = 7; + + // Mock method calls. + when( + camera.recorder!.prepareRecording(outputPath), + ).thenAnswer((_) async => mockPendingRecording); + when( + mockPendingRecording.start(any), + ).thenAnswer((_) async => mockRecording); + when( + camera.processCameraProvider!.isBound(camera.videoCapture!), + ).thenAnswer((_) async => false); + when( + camera.processCameraProvider!.isBound(camera.imageAnalysis!), + ).thenAnswer((_) async => true); + when( + camera.processCameraProvider!.bindToLifecycle( + camera.cameraSelector!, + [camera.videoCapture!], + ), + ).thenAnswer((_) async => mockCamera); + when( + mockCamera.getCameraInfo(), + ).thenAnswer((_) => Future.value(mockCameraInfo)); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => MockLiveCameraState()); + when( + mockCamera2CameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => InfoSupportedHardwareLevel.full); + + // Simulate video recording being started so startVideoRecording completes. + AndroidCameraCameraX.videoRecordingEventStreamController.add( + VideoRecordEventStart.pigeon_detached( + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ), + ); + + await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); + + verify( + camera.processCameraProvider!.unbind([camera.imageAnalysis!]), + ); + }, + ); + + test( + 'startVideoCapturing unbinds ImageAnalysis use case when image streaming callback not specified, camera device is level 3, and preview is not paused', + () async { + // Set up mocks and constants. + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final MockPendingRecording mockPendingRecording = MockPendingRecording(); + final MockRecording mockRecording = MockRecording(); + final MockCamera mockCamera = MockCamera(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final MockCamera2CameraInfo mockCamera2CameraInfo = + MockCamera2CameraInfo(); + + // Set directly for test versus calling createCamera. + camera.processCameraProvider = MockProcessCameraProvider(); + camera.recorder = MockRecorder(); + camera.videoCapture = MockVideoCapture(); + camera.cameraSelector = MockCameraSelector(); + camera.cameraInfo = MockCameraInfo(); + camera.imageAnalysis = MockImageAnalysis(); + + // Ignore setting target rotation for this test; tested seprately. + camera.captureOrientationLocked = true; + + // Tell plugin to create detached Observer when camera info updated. + const String outputPath = '/temp/REC123.temp'; + camera.proxy = CameraXProxy( + newObserver: ({ + required void Function(Observer, T) onChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Observer.detached( + onChanged: onChanged, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + fromCamera2CameraInfo: ({ + required CameraInfo cameraInfo, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + mockCamera2CameraInfo, + newSystemServicesManager: ({ + required void Function(SystemServicesManager, String) onCameraError, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockSystemServicesManager mockSystemServicesManager = + MockSystemServicesManager(); + when( + mockSystemServicesManager.getTempFilePath( + camera.videoPrefix, + '.temp', + ), + ).thenAnswer((_) async => outputPath); + return mockSystemServicesManager; + }, + newVideoRecordEventListener: ({ + required void Function(VideoRecordEventListener, VideoRecordEvent) + onEvent, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return VideoRecordEventListener.pigeon_detached( + onEvent: onEvent, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + infoSupportedHardwareLevelCameraCharacteristics: () { + return MockCameraCharacteristicsKey(); + }, + ); + + const int cameraId = 77; + + // Mock method calls. + when( + camera.recorder!.prepareRecording(outputPath), + ).thenAnswer((_) async => mockPendingRecording); + when( + mockPendingRecording.start(any), + ).thenAnswer((_) async => mockRecording); + when( + camera.processCameraProvider!.isBound(camera.videoCapture!), + ).thenAnswer((_) async => false); + when( + camera.processCameraProvider!.isBound(camera.imageAnalysis!), + ).thenAnswer((_) async => true); + when( + camera.processCameraProvider!.bindToLifecycle( + camera.cameraSelector!, + [camera.videoCapture!], + ), + ).thenAnswer((_) async => mockCamera); + when( + mockCamera.getCameraInfo(), + ).thenAnswer((_) => Future.value(mockCameraInfo)); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => MockLiveCameraState()); + when( + mockCamera2CameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => InfoSupportedHardwareLevel.level3); + + // Simulate video recording being started so startVideoRecording completes. + AndroidCameraCameraX.videoRecordingEventStreamController.add( + VideoRecordEventStart.pigeon_detached( + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ), + ); + + await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); + + verify( + camera.processCameraProvider!.unbind([camera.imageAnalysis!]), + ); + }, + ); + + test( + 'startVideoCapturing unbinds ImageAnalysis use case when image streaming callback is specified, camera device is not at least level 3, and preview is not paused', + () async { + // Set up mocks and constants. + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final MockPendingRecording mockPendingRecording = MockPendingRecording(); + final MockRecording mockRecording = MockRecording(); + final MockCamera mockCamera = MockCamera(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final MockCamera2CameraInfo mockCamera2CameraInfo = + MockCamera2CameraInfo(); + + // Set directly for test versus calling createCamera. + camera.processCameraProvider = MockProcessCameraProvider(); + camera.recorder = MockRecorder(); + camera.videoCapture = MockVideoCapture(); + camera.cameraSelector = MockCameraSelector(); + camera.cameraInfo = MockCameraInfo(); + camera.imageAnalysis = MockImageAnalysis(); + + // Ignore setting target rotation for this test; tested seprately. + camera.captureOrientationLocked = true; + + // Tell plugin to create detached Observer when camera info updated. + const String outputPath = '/temp/REC123.temp'; + camera.proxy = CameraXProxy( + newObserver: ({ + required void Function(Observer, T) onChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Observer.detached( + onChanged: onChanged, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + fromCamera2CameraInfo: ({ + required CameraInfo cameraInfo, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + mockCamera2CameraInfo, + newSystemServicesManager: ({ + required void Function(SystemServicesManager, String) onCameraError, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockSystemServicesManager mockSystemServicesManager = + MockSystemServicesManager(); + when( + mockSystemServicesManager.getTempFilePath( + camera.videoPrefix, + '.temp', + ), + ).thenAnswer((_) async => outputPath); + return mockSystemServicesManager; + }, + newVideoRecordEventListener: ({ + required void Function(VideoRecordEventListener, VideoRecordEvent) + onEvent, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return VideoRecordEventListener.pigeon_detached( + onEvent: onEvent, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + infoSupportedHardwareLevelCameraCharacteristics: () { + return MockCameraCharacteristicsKey(); + }, + ); + + const int cameraId = 87; + + // Mock method calls. + when( + camera.recorder!.prepareRecording(outputPath), + ).thenAnswer((_) async => mockPendingRecording); + when( + mockPendingRecording.start(any), + ).thenAnswer((_) async => mockRecording); + when( + camera.processCameraProvider!.isBound(camera.videoCapture!), + ).thenAnswer((_) async => false); + when( + camera.processCameraProvider!.isBound(camera.imageAnalysis!), + ).thenAnswer((_) async => true); + when( + camera.processCameraProvider!.bindToLifecycle( + camera.cameraSelector!, + [camera.videoCapture!], + ), + ).thenAnswer((_) async => mockCamera); + when( + mockCamera.getCameraInfo(), + ).thenAnswer((_) => Future.value(mockCameraInfo)); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => MockLiveCameraState()); + when( + mockCamera2CameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => InfoSupportedHardwareLevel.external); + + // Simulate video recording being started so startVideoRecording completes. + AndroidCameraCameraX.videoRecordingEventStreamController.add( + VideoRecordEventStart.pigeon_detached( + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ), + ); + + await camera.startVideoCapturing( + VideoCaptureOptions( + cameraId, + streamCallback: (CameraImageData image) {}, + ), + ); + verify( + camera.processCameraProvider!.unbind([camera.imageAnalysis!]), + ); + }, + ); + + test( + 'startVideoCapturing unbinds ImageCapture use case when image streaming callback is specified, camera device is at least level 3, and preview is not paused', + () async { + // Set up mocks and constants. + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final MockPendingRecording mockPendingRecording = MockPendingRecording(); + final MockRecording mockRecording = MockRecording(); + final MockCamera mockCamera = MockCamera(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final MockCamera2CameraInfo mockCamera2CameraInfo = + MockCamera2CameraInfo(); + + // Set directly for test versus calling createCamera. + camera.processCameraProvider = MockProcessCameraProvider(); + camera.recorder = MockRecorder(); + camera.videoCapture = MockVideoCapture(); + camera.cameraSelector = MockCameraSelector(); + camera.cameraInfo = MockCameraInfo(); + camera.imageAnalysis = MockImageAnalysis(); + camera.imageCapture = MockImageCapture(); + + // Ignore setting target rotation for this test; tested seprately. + camera.captureOrientationLocked = true; + + // Tell plugin to create detached Observer when camera info updated. + const String outputPath = '/temp/REC123.temp'; + camera.proxy = CameraXProxy( + newAnalyzer: ({ + required void Function(Analyzer, ImageProxy) analyze, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Analyzer.pigeon_detached( + analyze: analyze, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + newObserver: ({ + required void Function(Observer, T) onChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Observer.detached( + onChanged: onChanged, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + fromCamera2CameraInfo: ({ + required CameraInfo cameraInfo, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + mockCamera2CameraInfo, + newSystemServicesManager: ({ + required void Function(SystemServicesManager, String) onCameraError, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockSystemServicesManager mockSystemServicesManager = + MockSystemServicesManager(); + when( + mockSystemServicesManager.getTempFilePath( + camera.videoPrefix, + '.temp', + ), + ).thenAnswer((_) async => outputPath); + return mockSystemServicesManager; + }, + newVideoRecordEventListener: ({ + required void Function(VideoRecordEventListener, VideoRecordEvent) + onEvent, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return VideoRecordEventListener.pigeon_detached( + onEvent: onEvent, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + infoSupportedHardwareLevelCameraCharacteristics: () { + return MockCameraCharacteristicsKey(); + }, + ); + + const int cameraId = 107; + + // Mock method calls. + when( + camera.recorder!.prepareRecording(outputPath), + ).thenAnswer((_) async => mockPendingRecording); + when( + mockPendingRecording.start(any), + ).thenAnswer((_) async => mockRecording); + when( + camera.processCameraProvider!.isBound(camera.videoCapture!), + ).thenAnswer((_) async => false); + when( + camera.processCameraProvider!.isBound(camera.imageCapture!), + ).thenAnswer((_) async => true); + when( + camera.processCameraProvider!.isBound(camera.imageAnalysis!), + ).thenAnswer((_) async => true); + when( + camera.processCameraProvider!.bindToLifecycle( + camera.cameraSelector!, + [camera.videoCapture!], + ), + ).thenAnswer((_) async => mockCamera); + when( + mockCamera.getCameraInfo(), + ).thenAnswer((_) => Future.value(mockCameraInfo)); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => MockLiveCameraState()); + when( + mockCamera2CameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => InfoSupportedHardwareLevel.level3); + + // Simulate video recording being started so startVideoRecording completes. + AndroidCameraCameraX.videoRecordingEventStreamController.add( + VideoRecordEventStart.pigeon_detached( + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ), + ); + + await camera.startVideoCapturing( + VideoCaptureOptions( + cameraId, + streamCallback: (CameraImageData image) {}, + ), + ); + verify( + camera.processCameraProvider!.unbind([camera.imageCapture!]), + ); + }, + ); + + test( + 'startVideoCapturing does not unbind ImageCapture or ImageAnalysis use cases when preview is paused', + () async { + // Set up mocks and constants. + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final MockPendingRecording mockPendingRecording = MockPendingRecording(); + final MockRecording mockRecording = MockRecording(); + final MockCamera mockCamera = MockCamera(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final MockCamera2CameraInfo mockCamera2CameraInfo = + MockCamera2CameraInfo(); + + // Set directly for test versus calling createCamera. + camera.processCameraProvider = MockProcessCameraProvider(); + camera.recorder = MockRecorder(); + camera.videoCapture = MockVideoCapture(); + camera.cameraSelector = MockCameraSelector(); + camera.cameraInfo = MockCameraInfo(); + camera.imageAnalysis = MockImageAnalysis(); + camera.imageCapture = MockImageCapture(); + camera.preview = MockPreview(); + + // Ignore setting target rotation for this test; tested seprately. + camera.captureOrientationLocked = true; + + // Tell plugin to create detached Observer when camera info updated. + const String outputPath = '/temp/REC123.temp'; + camera.proxy = CameraXProxy( + newAnalyzer: ({ + required void Function(Analyzer, ImageProxy) analyze, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Analyzer.pigeon_detached( + analyze: analyze, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + newObserver: ({ + required void Function(Observer, T) onChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Observer.detached( + onChanged: onChanged, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + fromCamera2CameraInfo: ({ + required CameraInfo cameraInfo, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + mockCamera2CameraInfo, + newSystemServicesManager: ({ + required void Function(SystemServicesManager, String) onCameraError, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockSystemServicesManager mockSystemServicesManager = + MockSystemServicesManager(); + when( + mockSystemServicesManager.getTempFilePath( + camera.videoPrefix, + '.temp', + ), + ).thenAnswer((_) async => outputPath); + return mockSystemServicesManager; + }, + newVideoRecordEventListener: ({ + required void Function(VideoRecordEventListener, VideoRecordEvent) + onEvent, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return VideoRecordEventListener.pigeon_detached( + onEvent: onEvent, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + infoSupportedHardwareLevelCameraCharacteristics: () { + return MockCameraCharacteristicsKey(); + }, + ); + + const int cameraId = 97; + + // Mock method calls. + when( + camera.recorder!.prepareRecording(outputPath), + ).thenAnswer((_) async => mockPendingRecording); + when( + mockPendingRecording.start(any), + ).thenAnswer((_) async => mockRecording); + when( + camera.processCameraProvider!.isBound(camera.videoCapture!), + ).thenAnswer((_) async => false); + when( + camera.processCameraProvider!.bindToLifecycle( + camera.cameraSelector!, + [camera.videoCapture!], + ), + ).thenAnswer((_) async => mockCamera); + when( + mockCamera.getCameraInfo(), + ).thenAnswer((_) => Future.value(mockCameraInfo)); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => MockLiveCameraState()); + + await camera.pausePreview(cameraId); + + // Simulate video recording being started so startVideoRecording completes. + AndroidCameraCameraX.videoRecordingEventStreamController.add( + VideoRecordEventStart.pigeon_detached( + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ), + ); + + await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); + + verifyNever( + camera.processCameraProvider!.unbind([camera.imageCapture!]), + ); + verifyNever( + camera.processCameraProvider!.unbind([camera.imageAnalysis!]), + ); + }, + ); + + test( + 'startVideoCapturing unbinds ImageCapture and ImageAnalysis use cases when running on a legacy hardware device', + () async { + // Set up mocks and constants. + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final MockPendingRecording mockPendingRecording = MockPendingRecording(); + final MockRecording mockRecording = MockRecording(); + final MockCamera mockCamera = MockCamera(); + final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final MockCamera2CameraInfo mockCamera2CameraInfo = + MockCamera2CameraInfo(); + + // Set directly for test versus calling createCamera. + camera.processCameraProvider = MockProcessCameraProvider(); + camera.recorder = MockRecorder(); + camera.videoCapture = MockVideoCapture(); + camera.cameraSelector = MockCameraSelector(); + camera.cameraInfo = MockCameraInfo(); + camera.imageAnalysis = MockImageAnalysis(); + camera.imageCapture = MockImageCapture(); + camera.preview = MockPreview(); + + // Ignore setting target rotation for this test; tested seprately. + camera.captureOrientationLocked = true; + + // Tell plugin to create detached Observer when camera info updated. + const String outputPath = '/temp/REC123.temp'; + camera.proxy = CameraXProxy( + newAnalyzer: ({ + required void Function(Analyzer, ImageProxy) analyze, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Analyzer.pigeon_detached( + analyze: analyze, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + newObserver: ({ + required void Function(Observer, T) onChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Observer.detached( + onChanged: onChanged, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + fromCamera2CameraInfo: ({ + required CameraInfo cameraInfo, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + mockCamera2CameraInfo, + newSystemServicesManager: ({ + required void Function(SystemServicesManager, String) onCameraError, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockSystemServicesManager mockSystemServicesManager = + MockSystemServicesManager(); + when( + mockSystemServicesManager.getTempFilePath( + camera.videoPrefix, + '.temp', + ), + ).thenAnswer((_) async => outputPath); + return mockSystemServicesManager; + }, + newVideoRecordEventListener: ({ + required void Function(VideoRecordEventListener, VideoRecordEvent) + onEvent, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return VideoRecordEventListener.pigeon_detached( + onEvent: onEvent, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + infoSupportedHardwareLevelCameraCharacteristics: () { + return MockCameraCharacteristicsKey(); + }, + ); + + const int cameraId = 44; + + // Mock method calls. + when( + camera.recorder!.prepareRecording(outputPath), + ).thenAnswer((_) async => mockPendingRecording); + when( + mockPendingRecording.start(any), + ).thenAnswer((_) async => mockRecording); + when( + camera.processCameraProvider!.isBound(camera.videoCapture!), + ).thenAnswer((_) async => false); + when( + camera.processCameraProvider!.isBound(camera.imageCapture!), + ).thenAnswer((_) async => true); + when( + camera.processCameraProvider!.isBound(camera.imageAnalysis!), + ).thenAnswer((_) async => true); + when( + camera.processCameraProvider!.bindToLifecycle( + camera.cameraSelector!, + [camera.videoCapture!], + ), + ).thenAnswer((_) async => mockCamera); + when( + mockCamera.getCameraInfo(), + ).thenAnswer((_) => Future.value(mockCameraInfo)); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => MockLiveCameraState()); + when( + mockCamera2CameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => InfoSupportedHardwareLevel.legacy); + + // Simulate video recording being started so startVideoRecording completes. + AndroidCameraCameraX.videoRecordingEventStreamController.add( + VideoRecordEventStart.pigeon_detached( + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ), + ); + + await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); + + verify( + camera.processCameraProvider!.unbind([camera.imageCapture!]), + ); + verify( + camera.processCameraProvider!.unbind([camera.imageAnalysis!]), + ); + }, + ); + + test( + 'prepareForVideoRecording does not make any calls involving starting video recording', + () async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + + // Set directly for test versus calling createCamera. + camera.processCameraProvider = MockProcessCameraProvider(); + camera.recorder = MockRecorder(); + camera.videoCapture = MockVideoCapture(); + camera.camera = MockCamera(); + + await camera.prepareForVideoRecording(); + verifyNoMoreInteractions(camera.processCameraProvider); + verifyNoMoreInteractions(camera.recorder); + verifyNoMoreInteractions(camera.videoCapture); + verifyNoMoreInteractions(camera.camera); + }, + ); +} + +class TestMeteringPoint extends MeteringPoint { + TestMeteringPoint.detached({required this.x, required this.y, this.size}) + : super.pigeon_detached( + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + + final double x; + final double y; + final double? size; } diff --git a/packages/camera/camera_android_camerax/test/android_camera_camerax_test.mocks.dart b/packages/camera/camera_android_camerax/test/android_camera_camerax_test.mocks.dart index fc838a461bb4..e1ece4971f7b 100644 --- a/packages/camera/camera_android_camerax/test/android_camera_camerax_test.mocks.dart +++ b/packages/camera/camera_android_camerax/test/android_camera_camerax_test.mocks.dart @@ -1,56 +1,19 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.5 from annotations // in camera_android_camerax/test/android_camera_camerax_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i17; -import 'dart:typed_data' as _i34; -import 'dart:ui' as _i14; - -import 'package:camera_android_camerax/src/analyzer.dart' as _i16; -import 'package:camera_android_camerax/src/aspect_ratio_strategy.dart' as _i19; -import 'package:camera_android_camerax/src/camera.dart' as _i12; -import 'package:camera_android_camerax/src/camera2_camera_control.dart' as _i24; -import 'package:camera_android_camerax/src/camera2_camera_info.dart' as _i26; -import 'package:camera_android_camerax/src/camera_control.dart' as _i6; -import 'package:camera_android_camerax/src/camera_info.dart' as _i5; -import 'package:camera_android_camerax/src/camera_selector.dart' as _i28; -import 'package:camera_android_camerax/src/camera_state.dart' as _i20; -import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i10; -import 'package:camera_android_camerax/src/capture_request_options.dart' - as _i25; -import 'package:camera_android_camerax/src/exposure_state.dart' as _i8; -import 'package:camera_android_camerax/src/fallback_strategy.dart' as _i29; -import 'package:camera_android_camerax/src/focus_metering_action.dart' as _i23; -import 'package:camera_android_camerax/src/focus_metering_result.dart' as _i22; -import 'package:camera_android_camerax/src/image_analysis.dart' as _i30; -import 'package:camera_android_camerax/src/image_capture.dart' as _i31; -import 'package:camera_android_camerax/src/image_proxy.dart' as _i18; -import 'package:camera_android_camerax/src/live_data.dart' as _i7; -import 'package:camera_android_camerax/src/observer.dart' as _i33; -import 'package:camera_android_camerax/src/pending_recording.dart' as _i13; -import 'package:camera_android_camerax/src/plane_proxy.dart' as _i32; -import 'package:camera_android_camerax/src/preview.dart' as _i35; -import 'package:camera_android_camerax/src/process_camera_provider.dart' - as _i36; -import 'package:camera_android_camerax/src/quality_selector.dart' as _i38; -import 'package:camera_android_camerax/src/recorder.dart' as _i15; -import 'package:camera_android_camerax/src/recording.dart' as _i11; -import 'package:camera_android_camerax/src/resolution_filter.dart' as _i39; -import 'package:camera_android_camerax/src/resolution_selector.dart' as _i40; -import 'package:camera_android_camerax/src/resolution_strategy.dart' as _i41; -import 'package:camera_android_camerax/src/use_case.dart' as _i37; -import 'package:camera_android_camerax/src/video_capture.dart' as _i43; -import 'package:camera_android_camerax/src/zoom_state.dart' as _i21; +import 'dart:async' as _i5; +import 'dart:typed_data' as _i9; + +import 'package:camera_android_camerax/src/camerax_library.dart' as _i3; +import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i2; +import 'package:camera_android_camerax/src/camerax_proxy.dart' as _i7; import 'package:camera_platform_interface/camera_platform_interface.dart' - as _i9; -import 'package:flutter/foundation.dart' as _i4; -import 'package:flutter/services.dart' as _i3; -import 'package:flutter/widgets.dart' as _i2; + as _i4; +import 'package:flutter/services.dart' as _i8; import 'package:mockito/mockito.dart' as _i1; -import 'package:mockito/src/dummies.dart' as _i27; - -import 'test_camerax_library.g.dart' as _i42; +import 'package:mockito/src/dummies.dart' as _i6; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values @@ -60,901 +23,2573 @@ import 'test_camerax_library.g.dart' as _i42; // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class -class _FakeWidget_0 extends _i1.SmartFake implements _i2.Widget { - _FakeWidget_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); +class _FakePigeonInstanceManager_0 extends _i1.SmartFake + implements _i2.PigeonInstanceManager { + _FakePigeonInstanceManager_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} - @override - String toString({_i3.DiagnosticLevel? minLevel = _i3.DiagnosticLevel.info}) => - super.toString(); +class _FakeAnalyzer_1 extends _i1.SmartFake implements _i2.Analyzer { + _FakeAnalyzer_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } -class _FakeInheritedWidget_1 extends _i1.SmartFake - implements _i2.InheritedWidget { - _FakeInheritedWidget_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); +class _FakeAspectRatioStrategy_2 extends _i1.SmartFake + implements _i2.AspectRatioStrategy { + _FakeAspectRatioStrategy_2(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} - @override - String toString({_i3.DiagnosticLevel? minLevel = _i3.DiagnosticLevel.info}) => - super.toString(); +class _FakeCameraControl_3 extends _i1.SmartFake implements _i2.CameraControl { + _FakeCameraControl_3(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } -class _FakeDiagnosticsNode_2 extends _i1.SmartFake - implements _i4.DiagnosticsNode { - _FakeDiagnosticsNode_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); +class _FakeCameraInfo_4 extends _i1.SmartFake implements _i2.CameraInfo { + _FakeCameraInfo_4(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} - @override - String toString({ - _i4.TextTreeConfiguration? parentConfiguration, - _i3.DiagnosticLevel? minLevel = _i3.DiagnosticLevel.info, - }) => - super.toString(); +class _FakeCamera_5 extends _i1.SmartFake implements _i2.Camera { + _FakeCamera_5(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } -class _FakeCameraInfo_3 extends _i1.SmartFake implements _i5.CameraInfo { - _FakeCameraInfo_3( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); +class _FakeExposureState_6 extends _i1.SmartFake implements _i2.ExposureState { + _FakeExposureState_6(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } -class _FakeCameraControl_4 extends _i1.SmartFake implements _i6.CameraControl { - _FakeCameraControl_4( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); +class _FakeLiveData_7 extends _i1.SmartFake implements _i3.LiveData { + _FakeLiveData_7(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } -class _FakeLiveData_5 extends _i1.SmartFake - implements _i7.LiveData { - _FakeLiveData_5( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); +class _FakeCameraInfo_8 extends _i1.SmartFake implements _i3.CameraInfo { + _FakeCameraInfo_8(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } -class _FakeExposureState_6 extends _i1.SmartFake implements _i8.ExposureState { - _FakeExposureState_6( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); +class _FakeCameraCharacteristicsKey_9 extends _i1.SmartFake + implements _i2.CameraCharacteristicsKey { + _FakeCameraCharacteristicsKey_9(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } -class _FakeCameraImageFormat_7 extends _i1.SmartFake - implements _i9.CameraImageFormat { - _FakeCameraImageFormat_7( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); +class _FakeCameraSize_10 extends _i1.SmartFake implements _i2.CameraSize { + _FakeCameraSize_10(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } -class _FakeExposureCompensationRange_8 extends _i1.SmartFake - implements _i10.ExposureCompensationRange { - _FakeExposureCompensationRange_8( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); +class _FakeCamera2CameraControl_11 extends _i1.SmartFake + implements _i2.Camera2CameraControl { + _FakeCamera2CameraControl_11(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } -class _FakeRecording_9 extends _i1.SmartFake implements _i11.Recording { - _FakeRecording_9( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); +class _FakeCamera2CameraInfo_12 extends _i1.SmartFake + implements _i2.Camera2CameraInfo { + _FakeCamera2CameraInfo_12(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } -class _FakeResolutionInfo_10 extends _i1.SmartFake - implements _i10.ResolutionInfo { - _FakeResolutionInfo_10( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); +class _FakeCameraImageFormat_13 extends _i1.SmartFake + implements _i4.CameraImageFormat { + _FakeCameraImageFormat_13(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } -class _FakeCamera_11 extends _i1.SmartFake implements _i12.Camera { - _FakeCamera_11( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); +class _FakeCameraSelector_14 extends _i1.SmartFake + implements _i2.CameraSelector { + _FakeCameraSelector_14(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } -class _FakePendingRecording_12 extends _i1.SmartFake - implements _i13.PendingRecording { - _FakePendingRecording_12( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); +class _FakeCameraIntegerRange_15 extends _i1.SmartFake + implements _i2.CameraIntegerRange { + _FakeCameraIntegerRange_15(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } -class _FakeSize_13 extends _i1.SmartFake implements _i14.Size { - _FakeSize_13( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); +class _FakeObserver_16 extends _i1.SmartFake implements _i3.Observer { + _FakeObserver_16(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeSystemServicesManager_17 extends _i1.SmartFake + implements _i2.SystemServicesManager { + _FakeSystemServicesManager_17(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeDeviceOrientationManager_18 extends _i1.SmartFake + implements _i2.DeviceOrientationManager { + _FakeDeviceOrientationManager_18(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakePreview_19 extends _i1.SmartFake implements _i2.Preview { + _FakePreview_19(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeVideoCapture_20 extends _i1.SmartFake implements _i2.VideoCapture { + _FakeVideoCapture_20(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeRecorder_21 extends _i1.SmartFake implements _i2.Recorder { + _FakeRecorder_21(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeVideoRecordEventListener_22 extends _i1.SmartFake + implements _i2.VideoRecordEventListener { + _FakeVideoRecordEventListener_22(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeImageCapture_23 extends _i1.SmartFake implements _i2.ImageCapture { + _FakeImageCapture_23(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeResolutionStrategy_24 extends _i1.SmartFake + implements _i2.ResolutionStrategy { + _FakeResolutionStrategy_24(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeResolutionSelector_25 extends _i1.SmartFake + implements _i2.ResolutionSelector { + _FakeResolutionSelector_25(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeImageAnalysis_26 extends _i1.SmartFake implements _i2.ImageAnalysis { + _FakeImageAnalysis_26(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } -class _FakeRecorder_14 extends _i1.SmartFake implements _i15.Recorder { - _FakeRecorder_14( +class _FakeQualitySelector_27 extends _i1.SmartFake + implements _i2.QualitySelector { + _FakeQualitySelector_27(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeFallbackStrategy_28 extends _i1.SmartFake + implements _i2.FallbackStrategy { + _FakeFallbackStrategy_28(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeFocusMeteringActionBuilder_29 extends _i1.SmartFake + implements _i2.FocusMeteringActionBuilder { + _FakeFocusMeteringActionBuilder_29(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeCaptureRequestOptions_30 extends _i1.SmartFake + implements _i2.CaptureRequestOptions { + _FakeCaptureRequestOptions_30(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeResolutionFilter_31 extends _i1.SmartFake + implements _i2.ResolutionFilter { + _FakeResolutionFilter_31(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeDisplayOrientedMeteringPointFactory_32 extends _i1.SmartFake + implements _i2.DisplayOrientedMeteringPointFactory { + _FakeDisplayOrientedMeteringPointFactory_32( Object parent, Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); + ) : super(parent, parentInvocation); +} + +class _FakeProcessCameraProvider_33 extends _i1.SmartFake + implements _i2.ProcessCameraProvider { + _FakeProcessCameraProvider_33(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeCaptureRequestKey_34 extends _i1.SmartFake + implements _i2.CaptureRequestKey { + _FakeCaptureRequestKey_34(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeMeteringPoint_35 extends _i1.SmartFake implements _i2.MeteringPoint { + _FakeMeteringPoint_35(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeFocusMeteringAction_36 extends _i1.SmartFake + implements _i2.FocusMeteringAction { + _FakeFocusMeteringAction_36(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeFocusMeteringResult_37 extends _i1.SmartFake + implements _i2.FocusMeteringResult { + _FakeFocusMeteringResult_37(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeImageProxy_38 extends _i1.SmartFake implements _i2.ImageProxy { + _FakeImageProxy_38(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeRecording_39 extends _i1.SmartFake implements _i2.Recording { + _FakeRecording_39(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakePendingRecording_40 extends _i1.SmartFake + implements _i2.PendingRecording { + _FakePendingRecording_40(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakePlaneProxy_41 extends _i1.SmartFake implements _i2.PlaneProxy { + _FakePlaneProxy_41(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeVideoOutput_42 extends _i1.SmartFake implements _i2.VideoOutput { + _FakeVideoOutput_42(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +class _FakeZoomState_43 extends _i1.SmartFake implements _i2.ZoomState { + _FakeZoomState_43(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); } /// A class which mocks [Analyzer]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockAnalyzer extends _i1.Mock implements _i16.Analyzer { +class MockAnalyzer extends _i1.Mock implements _i2.Analyzer { @override - _i17.Future Function(_i18.ImageProxy) get analyze => + void Function(_i2.Analyzer, _i2.ImageProxy) get analyze => (super.noSuchMethod( Invocation.getter(#analyze), - returnValue: (_i18.ImageProxy imageProxy) => _i17.Future.value(), - returnValueForMissingStub: (_i18.ImageProxy imageProxy) => - _i17.Future.value(), - ) as _i17.Future Function(_i18.ImageProxy)); + returnValue: (_i2.Analyzer pigeon_instance, _i2.ImageProxy image) {}, + returnValueForMissingStub: + (_i2.Analyzer pigeon_instance, _i2.ImageProxy image) {}, + ) as void Function(_i2.Analyzer, _i2.ImageProxy)); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.Analyzer pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAnalyzer_1( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeAnalyzer_1( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.Analyzer); } /// A class which mocks [AspectRatioStrategy]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable class MockAspectRatioStrategy extends _i1.Mock - implements _i19.AspectRatioStrategy { + implements _i2.AspectRatioStrategy { + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future<_i2.AspectRatioStrategyFallbackRule> getFallbackRule() => + (super.noSuchMethod( + Invocation.method(#getFallbackRule, []), + returnValue: _i5.Future<_i2.AspectRatioStrategyFallbackRule>.value( + _i2.AspectRatioStrategyFallbackRule.auto, + ), + returnValueForMissingStub: + _i5.Future<_i2.AspectRatioStrategyFallbackRule>.value( + _i2.AspectRatioStrategyFallbackRule.auto, + ), + ) as _i5.Future<_i2.AspectRatioStrategyFallbackRule>); + + @override + _i5.Future<_i2.AspectRatio> getPreferredAspectRatio() => (super.noSuchMethod( + Invocation.method(#getPreferredAspectRatio, []), + returnValue: _i5.Future<_i2.AspectRatio>.value( + _i2.AspectRatio.ratio16To9, + ), + returnValueForMissingStub: _i5.Future<_i2.AspectRatio>.value( + _i2.AspectRatio.ratio16To9, + ), + ) as _i5.Future<_i2.AspectRatio>); + + @override + _i2.AspectRatioStrategy pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeAspectRatioStrategy_2( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeAspectRatioStrategy_2( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.AspectRatioStrategy); +} + +/// A class which mocks [Camera]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockCamera extends _i1.Mock implements _i2.Camera { + @override + _i2.CameraControl get cameraControl => (super.noSuchMethod( + Invocation.getter(#cameraControl), + returnValue: _FakeCameraControl_3( + this, + Invocation.getter(#cameraControl), + ), + returnValueForMissingStub: _FakeCameraControl_3( + this, + Invocation.getter(#cameraControl), + ), + ) as _i2.CameraControl); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future<_i2.CameraInfo> getCameraInfo() => (super.noSuchMethod( + Invocation.method(#getCameraInfo, []), + returnValue: _i5.Future<_i2.CameraInfo>.value( + _FakeCameraInfo_4(this, Invocation.method(#getCameraInfo, [])), + ), + returnValueForMissingStub: _i5.Future<_i2.CameraInfo>.value( + _FakeCameraInfo_4(this, Invocation.method(#getCameraInfo, [])), + ), + ) as _i5.Future<_i2.CameraInfo>); + + @override + _i2.Camera pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCamera_5( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeCamera_5( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.Camera); +} + +/// A class which mocks [CameraInfo]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockCameraInfo extends _i1.Mock implements _i3.CameraInfo { + @override + int get sensorRotationDegrees => (super.noSuchMethod( + Invocation.getter(#sensorRotationDegrees), + returnValue: 0, + returnValueForMissingStub: 0, + ) as int); + + @override + _i2.ExposureState get exposureState => (super.noSuchMethod( + Invocation.getter(#exposureState), + returnValue: _FakeExposureState_6( + this, + Invocation.getter(#exposureState), + ), + returnValueForMissingStub: _FakeExposureState_6( + this, + Invocation.getter(#exposureState), + ), + ) as _i2.ExposureState); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future<_i3.LiveData<_i2.CameraState>> getCameraState() => + (super.noSuchMethod( + Invocation.method(#getCameraState, []), + returnValue: _i5.Future<_i3.LiveData<_i2.CameraState>>.value( + _FakeLiveData_7<_i2.CameraState>( + this, + Invocation.method(#getCameraState, []), + ), + ), + returnValueForMissingStub: + _i5.Future<_i3.LiveData<_i2.CameraState>>.value( + _FakeLiveData_7<_i2.CameraState>( + this, + Invocation.method(#getCameraState, []), + ), + ), + ) as _i5.Future<_i3.LiveData<_i2.CameraState>>); + + @override + _i5.Future<_i3.LiveData<_i2.ZoomState>> getZoomState() => (super.noSuchMethod( + Invocation.method(#getZoomState, []), + returnValue: _i5.Future<_i3.LiveData<_i2.ZoomState>>.value( + _FakeLiveData_7<_i2.ZoomState>( + this, + Invocation.method(#getZoomState, []), + ), + ), + returnValueForMissingStub: + _i5.Future<_i3.LiveData<_i2.ZoomState>>.value( + _FakeLiveData_7<_i2.ZoomState>( + this, + Invocation.method(#getZoomState, []), + ), + ), + ) as _i5.Future<_i3.LiveData<_i2.ZoomState>>); + + @override + _i3.CameraInfo pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCameraInfo_8( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeCameraInfo_8( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i3.CameraInfo); +} + +/// A class which mocks [CameraCharacteristicsKey]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockCameraCharacteristicsKey extends _i1.Mock + implements _i2.CameraCharacteristicsKey { + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.CameraCharacteristicsKey pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCameraCharacteristicsKey_9( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeCameraCharacteristicsKey_9( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.CameraCharacteristicsKey); +} + +/// A class which mocks [CameraControl]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockCameraControl extends _i1.Mock implements _i2.CameraControl { + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future enableTorch(bool? torch) => (super.noSuchMethod( + Invocation.method(#enableTorch, [torch]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + @override - int get preferredAspectRatio => (super.noSuchMethod( - Invocation.getter(#preferredAspectRatio), + _i5.Future setZoomRatio(double? ratio) => (super.noSuchMethod( + Invocation.method(#setZoomRatio, [ratio]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future<_i2.FocusMeteringResult?> startFocusAndMetering( + _i2.FocusMeteringAction? action, + ) => + (super.noSuchMethod( + Invocation.method(#startFocusAndMetering, [action]), + returnValue: _i5.Future<_i2.FocusMeteringResult?>.value(), + returnValueForMissingStub: _i5.Future<_i2.FocusMeteringResult?>.value(), + ) as _i5.Future<_i2.FocusMeteringResult?>); + + @override + _i5.Future cancelFocusAndMetering() => (super.noSuchMethod( + Invocation.method(#cancelFocusAndMetering, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future setExposureCompensationIndex(int? index) => + (super.noSuchMethod( + Invocation.method(#setExposureCompensationIndex, [index]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.CameraControl pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCameraControl_3( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeCameraControl_3( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.CameraControl); +} + +/// A class which mocks [CameraSize]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockCameraSize extends _i1.Mock implements _i2.CameraSize { + @override + int get width => (super.noSuchMethod( + Invocation.getter(#width), returnValue: 0, returnValueForMissingStub: 0, ) as int); @override - int get fallbackRule => (super.noSuchMethod( - Invocation.getter(#fallbackRule), + int get height => (super.noSuchMethod( + Invocation.getter(#height), returnValue: 0, returnValueForMissingStub: 0, ) as int); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.CameraSize pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCameraSize_10( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeCameraSize_10( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.CameraSize); +} + +/// A class which mocks [Camera2CameraControl]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockCamera2CameraControl extends _i1.Mock + implements _i2.Camera2CameraControl { + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future addCaptureRequestOptions( + _i2.CaptureRequestOptions? bundle, + ) => + (super.noSuchMethod( + Invocation.method(#addCaptureRequestOptions, [bundle]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.Camera2CameraControl pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCamera2CameraControl_11( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeCamera2CameraControl_11( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.Camera2CameraControl); +} + +/// A class which mocks [Camera2CameraInfo]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockCamera2CameraInfo extends _i1.Mock implements _i2.Camera2CameraInfo { + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future getCameraId() => (super.noSuchMethod( + Invocation.method(#getCameraId, []), + returnValue: _i5.Future.value( + _i6.dummyValue(this, Invocation.method(#getCameraId, [])), + ), + returnValueForMissingStub: _i5.Future.value( + _i6.dummyValue(this, Invocation.method(#getCameraId, [])), + ), + ) as _i5.Future); + + @override + _i5.Future getCameraCharacteristic( + _i2.CameraCharacteristicsKey? key, + ) => + (super.noSuchMethod( + Invocation.method(#getCameraCharacteristic, [key]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.Camera2CameraInfo pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCamera2CameraInfo_12( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeCamera2CameraInfo_12( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.Camera2CameraInfo); } -/// A class which mocks [BuildContext]. +/// A class which mocks [CameraImageData]. /// /// See the documentation for Mockito's code generation for more information. -class MockBuildContext extends _i1.Mock implements _i2.BuildContext { +// ignore: must_be_immutable +class MockCameraImageData extends _i1.Mock implements _i4.CameraImageData { + @override + _i4.CameraImageFormat get format => (super.noSuchMethod( + Invocation.getter(#format), + returnValue: _FakeCameraImageFormat_13( + this, + Invocation.getter(#format), + ), + returnValueForMissingStub: _FakeCameraImageFormat_13( + this, + Invocation.getter(#format), + ), + ) as _i4.CameraImageFormat); + + @override + int get height => (super.noSuchMethod( + Invocation.getter(#height), + returnValue: 0, + returnValueForMissingStub: 0, + ) as int); + + @override + int get width => (super.noSuchMethod( + Invocation.getter(#width), + returnValue: 0, + returnValueForMissingStub: 0, + ) as int); + @override - _i2.Widget get widget => (super.noSuchMethod( - Invocation.getter(#widget), - returnValue: _FakeWidget_0( + List<_i4.CameraImagePlane> get planes => (super.noSuchMethod( + Invocation.getter(#planes), + returnValue: <_i4.CameraImagePlane>[], + returnValueForMissingStub: <_i4.CameraImagePlane>[], + ) as List<_i4.CameraImagePlane>); +} + +/// A class which mocks [CameraSelector]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockCameraSelector extends _i1.Mock implements _i2.CameraSelector { + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future> filter(List<_i2.CameraInfo>? cameraInfos) => + (super.noSuchMethod( + Invocation.method(#filter, [cameraInfos]), + returnValue: _i5.Future>.value( + <_i2.CameraInfo>[], + ), + returnValueForMissingStub: _i5.Future>.value( + <_i2.CameraInfo>[], + ), + ) as _i5.Future>); + + @override + _i2.CameraSelector pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCameraSelector_14( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeCameraSelector_14( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.CameraSelector); +} + +/// A class which mocks [CameraXProxy]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockCameraXProxy extends _i1.Mock implements _i7.CameraXProxy { + @override + void Function({ + _i8.BinaryMessenger? pigeonBinaryMessenger, + _i2.PigeonInstanceManager? pigeonInstanceManager, + }) get setUpGenericsProxy => (super.noSuchMethod( + Invocation.getter(#setUpGenericsProxy), + returnValue: ({ + _i8.BinaryMessenger? pigeonBinaryMessenger, + _i2.PigeonInstanceManager? pigeonInstanceManager, + }) {}, + returnValueForMissingStub: ({ + _i8.BinaryMessenger? pigeonBinaryMessenger, + _i2.PigeonInstanceManager? pigeonInstanceManager, + }) {}, + ) as void Function({ + _i8.BinaryMessenger? pigeonBinaryMessenger, + _i2.PigeonInstanceManager? pigeonInstanceManager, + })); + + @override + _i2.CameraSize Function({ + required int height, + required int width, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get newCameraSize => (super.noSuchMethod( + Invocation.getter(#newCameraSize), + returnValue: ({ + required int height, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required int width, + }) => + _FakeCameraSize_10(this, Invocation.getter(#newCameraSize)), + returnValueForMissingStub: ({ + required int height, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required int width, + }) => + _FakeCameraSize_10(this, Invocation.getter(#newCameraSize)), + ) as _i2.CameraSize Function({ + required int height, + required int width, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + _i2.CameraIntegerRange Function({ + required int lower, + required int upper, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get newCameraIntegerRange => (super.noSuchMethod( + Invocation.getter(#newCameraIntegerRange), + returnValue: ({ + required int lower, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required int upper, + }) => + _FakeCameraIntegerRange_15( + this, + Invocation.getter(#newCameraIntegerRange), + ), + returnValueForMissingStub: ({ + required int lower, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required int upper, + }) => + _FakeCameraIntegerRange_15( + this, + Invocation.getter(#newCameraIntegerRange), + ), + ) as _i2.CameraIntegerRange Function({ + required int lower, + required int upper, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + _i3.Observer Function({ + required void Function(_i3.Observer, T) onChanged, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get newObserver => (super.noSuchMethod( + Invocation.getter(#newObserver), + returnValue: ({ + required void Function(_i3.Observer, T) onChanged, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) => + _FakeObserver_16(this, Invocation.getter(#newObserver)), + returnValueForMissingStub: ({ + required void Function(_i3.Observer, T) onChanged, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) => + _FakeObserver_16(this, Invocation.getter(#newObserver)), + ) as _i3.Observer Function({ + required void Function(_i3.Observer, T) onChanged, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + _i2.CameraSelector Function({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.LensFacing? requireLensFacing, + }) get newCameraSelector => (super.noSuchMethod( + Invocation.getter(#newCameraSelector), + returnValue: ({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.LensFacing? requireLensFacing, + }) => + _FakeCameraSelector_14( + this, + Invocation.getter(#newCameraSelector), + ), + returnValueForMissingStub: ({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.LensFacing? requireLensFacing, + }) => + _FakeCameraSelector_14( + this, + Invocation.getter(#newCameraSelector), + ), + ) as _i2.CameraSelector Function({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.LensFacing? requireLensFacing, + })); + + @override + _i2.SystemServicesManager Function({ + required void Function(_i2.SystemServicesManager, String) onCameraError, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get newSystemServicesManager => (super.noSuchMethod( + Invocation.getter(#newSystemServicesManager), + returnValue: ({ + required void Function(_i2.SystemServicesManager, String) + onCameraError, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) => + _FakeSystemServicesManager_17( + this, + Invocation.getter(#newSystemServicesManager), + ), + returnValueForMissingStub: ({ + required void Function(_i2.SystemServicesManager, String) + onCameraError, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) => + _FakeSystemServicesManager_17( + this, + Invocation.getter(#newSystemServicesManager), + ), + ) as _i2.SystemServicesManager Function({ + required void Function(_i2.SystemServicesManager, String) onCameraError, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + _i2.DeviceOrientationManager Function({ + required void Function(_i2.DeviceOrientationManager, String) + onDeviceOrientationChanged, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get newDeviceOrientationManager => (super.noSuchMethod( + Invocation.getter(#newDeviceOrientationManager), + returnValue: ({ + required void Function(_i2.DeviceOrientationManager, String) + onDeviceOrientationChanged, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) => + _FakeDeviceOrientationManager_18( + this, + Invocation.getter(#newDeviceOrientationManager), + ), + returnValueForMissingStub: ({ + required void Function(_i2.DeviceOrientationManager, String) + onDeviceOrientationChanged, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) => + _FakeDeviceOrientationManager_18( + this, + Invocation.getter(#newDeviceOrientationManager), + ), + ) as _i2.DeviceOrientationManager Function({ + required void Function(_i2.DeviceOrientationManager, String) + onDeviceOrientationChanged, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + _i2.Preview Function({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.ResolutionSelector? resolutionSelector, + int? targetRotation, + }) get newPreview => (super.noSuchMethod( + Invocation.getter(#newPreview), + returnValue: ({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.ResolutionSelector? resolutionSelector, + int? targetRotation, + }) => + _FakePreview_19(this, Invocation.getter(#newPreview)), + returnValueForMissingStub: ({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.ResolutionSelector? resolutionSelector, + int? targetRotation, + }) => + _FakePreview_19(this, Invocation.getter(#newPreview)), + ) as _i2.Preview Function({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.ResolutionSelector? resolutionSelector, + int? targetRotation, + })); + + @override + _i2.VideoCapture Function({ + required _i2.VideoOutput videoOutput, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get withOutputVideoCapture => (super.noSuchMethod( + Invocation.getter(#withOutputVideoCapture), + returnValue: ({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required _i2.VideoOutput videoOutput, + }) => + _FakeVideoCapture_20( + this, + Invocation.getter(#withOutputVideoCapture), + ), + returnValueForMissingStub: ({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required _i2.VideoOutput videoOutput, + }) => + _FakeVideoCapture_20( + this, + Invocation.getter(#withOutputVideoCapture), + ), + ) as _i2.VideoCapture Function({ + required _i2.VideoOutput videoOutput, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + _i2.Recorder Function({ + int? aspectRatio, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.QualitySelector? qualitySelector, + int? targetVideoEncodingBitRate, + }) get newRecorder => (super.noSuchMethod( + Invocation.getter(#newRecorder), + returnValue: ({ + int? aspectRatio, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.QualitySelector? qualitySelector, + int? targetVideoEncodingBitRate, + }) => + _FakeRecorder_21(this, Invocation.getter(#newRecorder)), + returnValueForMissingStub: ({ + int? aspectRatio, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.QualitySelector? qualitySelector, + int? targetVideoEncodingBitRate, + }) => + _FakeRecorder_21(this, Invocation.getter(#newRecorder)), + ) as _i2.Recorder Function({ + int? aspectRatio, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.QualitySelector? qualitySelector, + int? targetVideoEncodingBitRate, + })); + + @override + _i2.VideoRecordEventListener Function({ + required void Function(_i2.VideoRecordEventListener, _i2.VideoRecordEvent) + onEvent, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get newVideoRecordEventListener => (super.noSuchMethod( + Invocation.getter(#newVideoRecordEventListener), + returnValue: ({ + required void Function( + _i2.VideoRecordEventListener, + _i2.VideoRecordEvent, + ) onEvent, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) => + _FakeVideoRecordEventListener_22( + this, + Invocation.getter(#newVideoRecordEventListener), + ), + returnValueForMissingStub: ({ + required void Function( + _i2.VideoRecordEventListener, + _i2.VideoRecordEvent, + ) onEvent, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) => + _FakeVideoRecordEventListener_22( + this, + Invocation.getter(#newVideoRecordEventListener), + ), + ) as _i2.VideoRecordEventListener Function({ + required void Function( + _i2.VideoRecordEventListener, + _i2.VideoRecordEvent, + ) onEvent, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + _i2.ImageCapture Function({ + _i2.CameraXFlashMode? flashMode, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.ResolutionSelector? resolutionSelector, + int? targetRotation, + }) get newImageCapture => (super.noSuchMethod( + Invocation.getter(#newImageCapture), + returnValue: ({ + _i2.CameraXFlashMode? flashMode, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.ResolutionSelector? resolutionSelector, + int? targetRotation, + }) => + _FakeImageCapture_23( + this, + Invocation.getter(#newImageCapture), + ), + returnValueForMissingStub: ({ + _i2.CameraXFlashMode? flashMode, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.ResolutionSelector? resolutionSelector, + int? targetRotation, + }) => + _FakeImageCapture_23( + this, + Invocation.getter(#newImageCapture), + ), + ) as _i2.ImageCapture Function({ + _i2.CameraXFlashMode? flashMode, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.ResolutionSelector? resolutionSelector, + int? targetRotation, + })); + + @override + _i2.ResolutionStrategy Function({ + required _i2.CameraSize boundSize, + required _i2.ResolutionStrategyFallbackRule fallbackRule, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get newResolutionStrategy => (super.noSuchMethod( + Invocation.getter(#newResolutionStrategy), + returnValue: ({ + required _i2.CameraSize boundSize, + required _i2.ResolutionStrategyFallbackRule fallbackRule, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) => + _FakeResolutionStrategy_24( + this, + Invocation.getter(#newResolutionStrategy), + ), + returnValueForMissingStub: ({ + required _i2.CameraSize boundSize, + required _i2.ResolutionStrategyFallbackRule fallbackRule, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) => + _FakeResolutionStrategy_24( + this, + Invocation.getter(#newResolutionStrategy), + ), + ) as _i2.ResolutionStrategy Function({ + required _i2.CameraSize boundSize, + required _i2.ResolutionStrategyFallbackRule fallbackRule, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + _i2.ResolutionSelector Function({ + _i2.AspectRatioStrategy? aspectRatioStrategy, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.ResolutionFilter? resolutionFilter, + _i2.ResolutionStrategy? resolutionStrategy, + }) get newResolutionSelector => (super.noSuchMethod( + Invocation.getter(#newResolutionSelector), + returnValue: ({ + _i2.AspectRatioStrategy? aspectRatioStrategy, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.ResolutionFilter? resolutionFilter, + _i2.ResolutionStrategy? resolutionStrategy, + }) => + _FakeResolutionSelector_25( + this, + Invocation.getter(#newResolutionSelector), + ), + returnValueForMissingStub: ({ + _i2.AspectRatioStrategy? aspectRatioStrategy, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.ResolutionFilter? resolutionFilter, + _i2.ResolutionStrategy? resolutionStrategy, + }) => + _FakeResolutionSelector_25( + this, + Invocation.getter(#newResolutionSelector), + ), + ) as _i2.ResolutionSelector Function({ + _i2.AspectRatioStrategy? aspectRatioStrategy, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.ResolutionFilter? resolutionFilter, + _i2.ResolutionStrategy? resolutionStrategy, + })); + + @override + _i2.AspectRatioStrategy Function({ + required _i2.AspectRatioStrategyFallbackRule fallbackRule, + required _i2.AspectRatio preferredAspectRatio, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get newAspectRatioStrategy => (super.noSuchMethod( + Invocation.getter(#newAspectRatioStrategy), + returnValue: ({ + required _i2.AspectRatioStrategyFallbackRule fallbackRule, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required _i2.AspectRatio preferredAspectRatio, + }) => + _FakeAspectRatioStrategy_2( + this, + Invocation.getter(#newAspectRatioStrategy), + ), + returnValueForMissingStub: ({ + required _i2.AspectRatioStrategyFallbackRule fallbackRule, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required _i2.AspectRatio preferredAspectRatio, + }) => + _FakeAspectRatioStrategy_2( + this, + Invocation.getter(#newAspectRatioStrategy), + ), + ) as _i2.AspectRatioStrategy Function({ + required _i2.AspectRatioStrategyFallbackRule fallbackRule, + required _i2.AspectRatio preferredAspectRatio, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + _i2.ImageAnalysis Function({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.ResolutionSelector? resolutionSelector, + int? targetRotation, + }) get newImageAnalysis => (super.noSuchMethod( + Invocation.getter(#newImageAnalysis), + returnValue: ({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.ResolutionSelector? resolutionSelector, + int? targetRotation, + }) => + _FakeImageAnalysis_26( + this, + Invocation.getter(#newImageAnalysis), + ), + returnValueForMissingStub: ({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.ResolutionSelector? resolutionSelector, + int? targetRotation, + }) => + _FakeImageAnalysis_26( + this, + Invocation.getter(#newImageAnalysis), + ), + ) as _i2.ImageAnalysis Function({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + _i2.ResolutionSelector? resolutionSelector, + int? targetRotation, + })); + + @override + _i2.Analyzer Function({ + required void Function(_i2.Analyzer, _i2.ImageProxy) analyze, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get newAnalyzer => (super.noSuchMethod( + Invocation.getter(#newAnalyzer), + returnValue: ({ + required void Function(_i2.Analyzer, _i2.ImageProxy) analyze, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) => + _FakeAnalyzer_1(this, Invocation.getter(#newAnalyzer)), + returnValueForMissingStub: ({ + required void Function(_i2.Analyzer, _i2.ImageProxy) analyze, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) => + _FakeAnalyzer_1(this, Invocation.getter(#newAnalyzer)), + ) as _i2.Analyzer Function({ + required void Function(_i2.Analyzer, _i2.ImageProxy) analyze, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + _i2.QualitySelector Function({ + required _i2.VideoQuality quality, + _i2.FallbackStrategy? fallbackStrategy, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get fromQualitySelector => (super.noSuchMethod( + Invocation.getter(#fromQualitySelector), + returnValue: ({ + _i2.FallbackStrategy? fallbackStrategy, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required _i2.VideoQuality quality, + }) => + _FakeQualitySelector_27( + this, + Invocation.getter(#fromQualitySelector), + ), + returnValueForMissingStub: ({ + _i2.FallbackStrategy? fallbackStrategy, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required _i2.VideoQuality quality, + }) => + _FakeQualitySelector_27( + this, + Invocation.getter(#fromQualitySelector), + ), + ) as _i2.QualitySelector Function({ + required _i2.VideoQuality quality, + _i2.FallbackStrategy? fallbackStrategy, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + _i2.QualitySelector Function({ + required List<_i2.VideoQuality> qualities, + _i2.FallbackStrategy? fallbackStrategy, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get fromOrderedListQualitySelector => (super.noSuchMethod( + Invocation.getter(#fromOrderedListQualitySelector), + returnValue: ({ + _i2.FallbackStrategy? fallbackStrategy, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required List<_i2.VideoQuality> qualities, + }) => + _FakeQualitySelector_27( + this, + Invocation.getter(#fromOrderedListQualitySelector), + ), + returnValueForMissingStub: ({ + _i2.FallbackStrategy? fallbackStrategy, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required List<_i2.VideoQuality> qualities, + }) => + _FakeQualitySelector_27( + this, + Invocation.getter(#fromOrderedListQualitySelector), + ), + ) as _i2.QualitySelector Function({ + required List<_i2.VideoQuality> qualities, + _i2.FallbackStrategy? fallbackStrategy, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + _i2.FallbackStrategy Function({ + required _i2.VideoQuality quality, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get higherQualityOrLowerThanFallbackStrategy => (super.noSuchMethod( + Invocation.getter(#higherQualityOrLowerThanFallbackStrategy), + returnValue: ({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required _i2.VideoQuality quality, + }) => + _FakeFallbackStrategy_28( + this, + Invocation.getter(#higherQualityOrLowerThanFallbackStrategy), + ), + returnValueForMissingStub: ({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required _i2.VideoQuality quality, + }) => + _FakeFallbackStrategy_28( + this, + Invocation.getter(#higherQualityOrLowerThanFallbackStrategy), + ), + ) as _i2.FallbackStrategy Function({ + required _i2.VideoQuality quality, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + _i2.FallbackStrategy Function({ + required _i2.VideoQuality quality, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get higherQualityThanFallbackStrategy => (super.noSuchMethod( + Invocation.getter(#higherQualityThanFallbackStrategy), + returnValue: ({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required _i2.VideoQuality quality, + }) => + _FakeFallbackStrategy_28( + this, + Invocation.getter(#higherQualityThanFallbackStrategy), + ), + returnValueForMissingStub: ({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required _i2.VideoQuality quality, + }) => + _FakeFallbackStrategy_28( + this, + Invocation.getter(#higherQualityThanFallbackStrategy), + ), + ) as _i2.FallbackStrategy Function({ + required _i2.VideoQuality quality, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + _i2.FallbackStrategy Function({ + required _i2.VideoQuality quality, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get lowerQualityOrHigherThanFallbackStrategy => (super.noSuchMethod( + Invocation.getter(#lowerQualityOrHigherThanFallbackStrategy), + returnValue: ({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required _i2.VideoQuality quality, + }) => + _FakeFallbackStrategy_28( + this, + Invocation.getter(#lowerQualityOrHigherThanFallbackStrategy), + ), + returnValueForMissingStub: ({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required _i2.VideoQuality quality, + }) => + _FakeFallbackStrategy_28( + this, + Invocation.getter(#lowerQualityOrHigherThanFallbackStrategy), + ), + ) as _i2.FallbackStrategy Function({ + required _i2.VideoQuality quality, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + _i2.FallbackStrategy Function({ + required _i2.VideoQuality quality, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get lowerQualityThanFallbackStrategy => (super.noSuchMethod( + Invocation.getter(#lowerQualityThanFallbackStrategy), + returnValue: ({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required _i2.VideoQuality quality, + }) => + _FakeFallbackStrategy_28( + this, + Invocation.getter(#lowerQualityThanFallbackStrategy), + ), + returnValueForMissingStub: ({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required _i2.VideoQuality quality, + }) => + _FakeFallbackStrategy_28( + this, + Invocation.getter(#lowerQualityThanFallbackStrategy), + ), + ) as _i2.FallbackStrategy Function({ + required _i2.VideoQuality quality, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + _i2.FocusMeteringActionBuilder Function({ + required _i2.MeteringPoint point, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get newFocusMeteringActionBuilder => (super.noSuchMethod( + Invocation.getter(#newFocusMeteringActionBuilder), + returnValue: ({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required _i2.MeteringPoint point, + }) => + _FakeFocusMeteringActionBuilder_29( + this, + Invocation.getter(#newFocusMeteringActionBuilder), + ), + returnValueForMissingStub: ({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required _i2.MeteringPoint point, + }) => + _FakeFocusMeteringActionBuilder_29( + this, + Invocation.getter(#newFocusMeteringActionBuilder), + ), + ) as _i2.FocusMeteringActionBuilder Function({ + required _i2.MeteringPoint point, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + _i2.FocusMeteringActionBuilder Function({ + required _i2.MeteringMode mode, + required _i2.MeteringPoint point, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get withModeFocusMeteringActionBuilder => (super.noSuchMethod( + Invocation.getter(#withModeFocusMeteringActionBuilder), + returnValue: ({ + required _i2.MeteringMode mode, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required _i2.MeteringPoint point, + }) => + _FakeFocusMeteringActionBuilder_29( + this, + Invocation.getter(#withModeFocusMeteringActionBuilder), + ), + returnValueForMissingStub: ({ + required _i2.MeteringMode mode, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required _i2.MeteringPoint point, + }) => + _FakeFocusMeteringActionBuilder_29( + this, + Invocation.getter(#withModeFocusMeteringActionBuilder), + ), + ) as _i2.FocusMeteringActionBuilder Function({ + required _i2.MeteringMode mode, + required _i2.MeteringPoint point, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + set withModeFocusMeteringActionBuilder( + _i2.FocusMeteringActionBuilder Function({ + required _i2.MeteringMode mode, + required _i2.MeteringPoint point, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })? _withModeFocusMeteringActionBuilder, + ) => + super.noSuchMethod( + Invocation.setter( + #withModeFocusMeteringActionBuilder, + _withModeFocusMeteringActionBuilder, + ), + returnValueForMissingStub: null, + ); + + @override + _i2.CaptureRequestOptions Function({ + required Map<_i2.CaptureRequestKey, Object?> options, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get newCaptureRequestOptions => (super.noSuchMethod( + Invocation.getter(#newCaptureRequestOptions), + returnValue: ({ + required Map<_i2.CaptureRequestKey, Object?> options, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) => + _FakeCaptureRequestOptions_30( + this, + Invocation.getter(#newCaptureRequestOptions), + ), + returnValueForMissingStub: ({ + required Map<_i2.CaptureRequestKey, Object?> options, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) => + _FakeCaptureRequestOptions_30( + this, + Invocation.getter(#newCaptureRequestOptions), + ), + ) as _i2.CaptureRequestOptions Function({ + required Map<_i2.CaptureRequestKey, Object?> options, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + set newCaptureRequestOptions( + _i2.CaptureRequestOptions Function({ + required Map<_i2.CaptureRequestKey, Object?> options, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })? _newCaptureRequestOptions, + ) => + super.noSuchMethod( + Invocation.setter(#newCaptureRequestOptions, _newCaptureRequestOptions), + returnValueForMissingStub: null, + ); + + @override + _i2.Camera2CameraControl Function({ + required _i2.CameraControl cameraControl, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get fromCamera2CameraControl => (super.noSuchMethod( + Invocation.getter(#fromCamera2CameraControl), + returnValue: ({ + required _i2.CameraControl cameraControl, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) => + _FakeCamera2CameraControl_11( + this, + Invocation.getter(#fromCamera2CameraControl), + ), + returnValueForMissingStub: ({ + required _i2.CameraControl cameraControl, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) => + _FakeCamera2CameraControl_11( + this, + Invocation.getter(#fromCamera2CameraControl), + ), + ) as _i2.Camera2CameraControl Function({ + required _i2.CameraControl cameraControl, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + set fromCamera2CameraControl( + _i2.Camera2CameraControl Function({ + required _i2.CameraControl cameraControl, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })? _fromCamera2CameraControl, + ) => + super.noSuchMethod( + Invocation.setter(#fromCamera2CameraControl, _fromCamera2CameraControl), + returnValueForMissingStub: null, + ); + + @override + _i2.ResolutionFilter Function({ + required _i2.CameraSize preferredSize, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get createWithOnePreferredSizeResolutionFilter => (super.noSuchMethod( + Invocation.getter(#createWithOnePreferredSizeResolutionFilter), + returnValue: ({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required _i2.CameraSize preferredSize, + }) => + _FakeResolutionFilter_31( + this, + Invocation.getter( + #createWithOnePreferredSizeResolutionFilter, + ), + ), + returnValueForMissingStub: ({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required _i2.CameraSize preferredSize, + }) => + _FakeResolutionFilter_31( + this, + Invocation.getter( + #createWithOnePreferredSizeResolutionFilter, + ), + ), + ) as _i2.ResolutionFilter Function({ + required _i2.CameraSize preferredSize, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + _i2.Camera2CameraInfo Function({ + required _i3.CameraInfo cameraInfo, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get fromCamera2CameraInfo => (super.noSuchMethod( + Invocation.getter(#fromCamera2CameraInfo), + returnValue: ({ + required _i3.CameraInfo cameraInfo, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) => + _FakeCamera2CameraInfo_12( + this, + Invocation.getter(#fromCamera2CameraInfo), + ), + returnValueForMissingStub: ({ + required _i3.CameraInfo cameraInfo, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) => + _FakeCamera2CameraInfo_12( + this, + Invocation.getter(#fromCamera2CameraInfo), + ), + ) as _i2.Camera2CameraInfo Function({ + required _i3.CameraInfo cameraInfo, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + _i2.DisplayOrientedMeteringPointFactory Function({ + required _i3.CameraInfo cameraInfo, + required double height, + required double width, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get newDisplayOrientedMeteringPointFactory => (super.noSuchMethod( + Invocation.getter(#newDisplayOrientedMeteringPointFactory), + returnValue: ({ + required _i3.CameraInfo cameraInfo, + required double height, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required double width, + }) => + _FakeDisplayOrientedMeteringPointFactory_32( + this, + Invocation.getter(#newDisplayOrientedMeteringPointFactory), + ), + returnValueForMissingStub: ({ + required _i3.CameraInfo cameraInfo, + required double height, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + required double width, + }) => + _FakeDisplayOrientedMeteringPointFactory_32( + this, + Invocation.getter(#newDisplayOrientedMeteringPointFactory), + ), + ) as _i2.DisplayOrientedMeteringPointFactory Function({ + required _i3.CameraInfo cameraInfo, + required double height, + required double width, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + set newDisplayOrientedMeteringPointFactory( + _i2.DisplayOrientedMeteringPointFactory Function({ + required _i3.CameraInfo cameraInfo, + required double height, + required double width, + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })? _newDisplayOrientedMeteringPointFactory, + ) => + super.noSuchMethod( + Invocation.setter( + #newDisplayOrientedMeteringPointFactory, + _newDisplayOrientedMeteringPointFactory, + ), + returnValueForMissingStub: null, + ); + + @override + _i5.Future<_i2.ProcessCameraProvider> Function({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get getInstanceProcessCameraProvider => (super.noSuchMethod( + Invocation.getter(#getInstanceProcessCameraProvider), + returnValue: ({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) => + _i5.Future<_i2.ProcessCameraProvider>.value( + _FakeProcessCameraProvider_33( + this, + Invocation.getter(#getInstanceProcessCameraProvider), + ), + ), + returnValueForMissingStub: ({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) => + _i5.Future<_i2.ProcessCameraProvider>.value( + _FakeProcessCameraProvider_33( + this, + Invocation.getter(#getInstanceProcessCameraProvider), + ), + ), + ) as _i5.Future<_i2.ProcessCameraProvider> Function({ + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + _i5.Future<_i2.CameraSize?> Function( + _i3.CameraInfo, + _i2.VideoQuality, { + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) get getResolutionQualitySelector => (super.noSuchMethod( + Invocation.getter(#getResolutionQualitySelector), + returnValue: ( + _i3.CameraInfo __p0, + _i2.VideoQuality __p1, { + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) => + _i5.Future<_i2.CameraSize?>.value(), + returnValueForMissingStub: ( + _i3.CameraInfo __p0, + _i2.VideoQuality __p1, { + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + }) => + _i5.Future<_i2.CameraSize?>.value(), + ) as _i5.Future<_i2.CameraSize?> Function( + _i3.CameraInfo, + _i2.VideoQuality, { + _i8.BinaryMessenger? pigeon_binaryMessenger, + _i2.PigeonInstanceManager? pigeon_instanceManager, + })); + + @override + _i2.CameraSelector Function() get defaultBackCameraCameraSelector => + (super.noSuchMethod( + Invocation.getter(#defaultBackCameraCameraSelector), + returnValue: () => _FakeCameraSelector_14( this, - Invocation.getter(#widget), + Invocation.getter(#defaultBackCameraCameraSelector), ), - returnValueForMissingStub: _FakeWidget_0( + returnValueForMissingStub: () => _FakeCameraSelector_14( this, - Invocation.getter(#widget), + Invocation.getter(#defaultBackCameraCameraSelector), ), - ) as _i2.Widget); + ) as _i2.CameraSelector Function()); @override - bool get mounted => (super.noSuchMethod( - Invocation.getter(#mounted), - returnValue: false, - returnValueForMissingStub: false, - ) as bool); - - @override - bool get debugDoingBuild => (super.noSuchMethod( - Invocation.getter(#debugDoingBuild), - returnValue: false, - returnValueForMissingStub: false, - ) as bool); - - @override - _i2.InheritedWidget dependOnInheritedElement( - _i2.InheritedElement? ancestor, { - Object? aspect, - }) => + _i2.CameraSelector Function() get defaultFrontCameraCameraSelector => (super.noSuchMethod( - Invocation.method( - #dependOnInheritedElement, - [ancestor], - {#aspect: aspect}, + Invocation.getter(#defaultFrontCameraCameraSelector), + returnValue: () => _FakeCameraSelector_14( + this, + Invocation.getter(#defaultFrontCameraCameraSelector), ), - returnValue: _FakeInheritedWidget_1( + returnValueForMissingStub: () => _FakeCameraSelector_14( this, - Invocation.method( - #dependOnInheritedElement, - [ancestor], - {#aspect: aspect}, - ), + Invocation.getter(#defaultFrontCameraCameraSelector), + ), + ) as _i2.CameraSelector Function()); + + @override + _i2.ResolutionStrategy Function() + get highestAvailableStrategyResolutionStrategy => (super.noSuchMethod( + Invocation.getter(#highestAvailableStrategyResolutionStrategy), + returnValue: () => _FakeResolutionStrategy_24( + this, + Invocation.getter( + #highestAvailableStrategyResolutionStrategy, + ), + ), + returnValueForMissingStub: () => _FakeResolutionStrategy_24( + this, + Invocation.getter( + #highestAvailableStrategyResolutionStrategy, + ), + ), + ) as _i2.ResolutionStrategy Function()); + + @override + _i2.AspectRatioStrategy Function() + get ratio_16_9FallbackAutoStrategyAspectRatioStrategy => + (super.noSuchMethod( + Invocation.getter( + #ratio_16_9FallbackAutoStrategyAspectRatioStrategy, + ), + returnValue: () => _FakeAspectRatioStrategy_2( + this, + Invocation.getter( + #ratio_16_9FallbackAutoStrategyAspectRatioStrategy, + ), + ), + returnValueForMissingStub: () => _FakeAspectRatioStrategy_2( + this, + Invocation.getter( + #ratio_16_9FallbackAutoStrategyAspectRatioStrategy, + ), + ), + ) as _i2.AspectRatioStrategy Function()); + + @override + _i2.AspectRatioStrategy Function() + get ratio_4_3FallbackAutoStrategyAspectRatioStrategy => + (super.noSuchMethod( + Invocation.getter( + #ratio_4_3FallbackAutoStrategyAspectRatioStrategy, + ), + returnValue: () => _FakeAspectRatioStrategy_2( + this, + Invocation.getter( + #ratio_4_3FallbackAutoStrategyAspectRatioStrategy, + ), + ), + returnValueForMissingStub: () => _FakeAspectRatioStrategy_2( + this, + Invocation.getter( + #ratio_4_3FallbackAutoStrategyAspectRatioStrategy, + ), + ), + ) as _i2.AspectRatioStrategy Function()); + + @override + _i2.CaptureRequestKey Function() get controlAELockCaptureRequest => + (super.noSuchMethod( + Invocation.getter(#controlAELockCaptureRequest), + returnValue: () => _FakeCaptureRequestKey_34( + this, + Invocation.getter(#controlAELockCaptureRequest), ), - returnValueForMissingStub: _FakeInheritedWidget_1( + returnValueForMissingStub: () => _FakeCaptureRequestKey_34( this, - Invocation.method( - #dependOnInheritedElement, - [ancestor], - {#aspect: aspect}, - ), + Invocation.getter(#controlAELockCaptureRequest), ), - ) as _i2.InheritedWidget); + ) as _i2.CaptureRequestKey Function()); @override - void visitAncestorElements(_i2.ConditionalElementVisitor? visitor) => + set controlAELockCaptureRequest( + _i2.CaptureRequestKey Function()? _controlAELockCaptureRequest, + ) => super.noSuchMethod( - Invocation.method( - #visitAncestorElements, - [visitor], + Invocation.setter( + #controlAELockCaptureRequest, + _controlAELockCaptureRequest, ), returnValueForMissingStub: null, ); @override - void visitChildElements(_i2.ElementVisitor? visitor) => super.noSuchMethod( - Invocation.method( - #visitChildElements, - [visitor], - ), - returnValueForMissingStub: null, - ); + _i2.CameraCharacteristicsKey Function() + get infoSupportedHardwareLevelCameraCharacteristics => + (super.noSuchMethod( + Invocation.getter(#infoSupportedHardwareLevelCameraCharacteristics), + returnValue: () => _FakeCameraCharacteristicsKey_9( + this, + Invocation.getter( + #infoSupportedHardwareLevelCameraCharacteristics, + ), + ), + returnValueForMissingStub: () => _FakeCameraCharacteristicsKey_9( + this, + Invocation.getter( + #infoSupportedHardwareLevelCameraCharacteristics, + ), + ), + ) as _i2.CameraCharacteristicsKey Function()); + + @override + _i2.CameraCharacteristicsKey Function() + get sensorOrientationCameraCharacteristics => (super.noSuchMethod( + Invocation.getter(#sensorOrientationCameraCharacteristics), + returnValue: () => _FakeCameraCharacteristicsKey_9( + this, + Invocation.getter(#sensorOrientationCameraCharacteristics), + ), + returnValueForMissingStub: () => _FakeCameraCharacteristicsKey_9( + this, + Invocation.getter(#sensorOrientationCameraCharacteristics), + ), + ) as _i2.CameraCharacteristicsKey Function()); +} +/// A class which mocks [CaptureRequestOptions]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockCaptureRequestOptions extends _i1.Mock + implements _i2.CaptureRequestOptions { @override - void dispatchNotification(_i2.Notification? notification) => - super.noSuchMethod( - Invocation.method( - #dispatchNotification, - [notification], + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), ), - returnValueForMissingStub: null, - ); + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i4.DiagnosticsNode describeElement( - String? name, { - _i4.DiagnosticsTreeStyle? style = _i4.DiagnosticsTreeStyle.errorProperty, - }) => + _i5.Future getCaptureRequestOption(_i2.CaptureRequestKey? key) => (super.noSuchMethod( - Invocation.method( - #describeElement, - [name], - {#style: style}, - ), - returnValue: _FakeDiagnosticsNode_2( + Invocation.method(#getCaptureRequestOption, [key]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.CaptureRequestOptions pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeCaptureRequestOptions_30( this, - Invocation.method( - #describeElement, - [name], - {#style: style}, - ), + Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakeDiagnosticsNode_2( + returnValueForMissingStub: _FakeCaptureRequestOptions_30( this, - Invocation.method( - #describeElement, - [name], - {#style: style}, - ), + Invocation.method(#pigeon_copy, []), ), - ) as _i4.DiagnosticsNode); + ) as _i2.CaptureRequestOptions); +} - @override - _i4.DiagnosticsNode describeWidget( - String? name, { - _i4.DiagnosticsTreeStyle? style = _i4.DiagnosticsTreeStyle.errorProperty, - }) => - (super.noSuchMethod( - Invocation.method( - #describeWidget, - [name], - {#style: style}, - ), - returnValue: _FakeDiagnosticsNode_2( +/// A class which mocks [DeviceOrientationManager]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockDeviceOrientationManager extends _i1.Mock + implements _i2.DeviceOrientationManager { + @override + void Function(_i2.DeviceOrientationManager, String) + get onDeviceOrientationChanged => (super.noSuchMethod( + Invocation.getter(#onDeviceOrientationChanged), + returnValue: ( + _i2.DeviceOrientationManager pigeon_instance, + String orientation, + ) {}, + returnValueForMissingStub: ( + _i2.DeviceOrientationManager pigeon_instance, + String orientation, + ) {}, + ) as void Function(_i2.DeviceOrientationManager, String)); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( this, - Invocation.method( - #describeWidget, - [name], - {#style: style}, - ), + Invocation.getter(#pigeon_instanceManager), ), - returnValueForMissingStub: _FakeDiagnosticsNode_2( + returnValueForMissingStub: _FakePigeonInstanceManager_0( this, - Invocation.method( - #describeWidget, - [name], - {#style: style}, - ), + Invocation.getter(#pigeon_instanceManager), ), - ) as _i4.DiagnosticsNode); + ) as _i2.PigeonInstanceManager); @override - List<_i4.DiagnosticsNode> describeMissingAncestor( - {required Type? expectedAncestorType}) => + _i5.Future startListeningForDeviceOrientationChange() => (super.noSuchMethod( - Invocation.method( - #describeMissingAncestor, - [], - {#expectedAncestorType: expectedAncestorType}, - ), - returnValue: <_i4.DiagnosticsNode>[], - returnValueForMissingStub: <_i4.DiagnosticsNode>[], - ) as List<_i4.DiagnosticsNode>); + Invocation.method(#startListeningForDeviceOrientationChange, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i4.DiagnosticsNode describeOwnershipChain(String? name) => + _i5.Future stopListeningForDeviceOrientationChange() => (super.noSuchMethod( - Invocation.method( - #describeOwnershipChain, - [name], - ), - returnValue: _FakeDiagnosticsNode_2( - this, - Invocation.method( - #describeOwnershipChain, - [name], + Invocation.method(#stopListeningForDeviceOrientationChange, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future getDefaultDisplayRotation() => (super.noSuchMethod( + Invocation.method(#getDefaultDisplayRotation, []), + returnValue: _i5.Future.value(0), + returnValueForMissingStub: _i5.Future.value(0), + ) as _i5.Future); + + @override + _i5.Future getUiOrientation() => (super.noSuchMethod( + Invocation.method(#getUiOrientation, []), + returnValue: _i5.Future.value( + _i6.dummyValue( + this, + Invocation.method(#getUiOrientation, []), ), ), - returnValueForMissingStub: _FakeDiagnosticsNode_2( - this, - Invocation.method( - #describeOwnershipChain, - [name], + returnValueForMissingStub: _i5.Future.value( + _i6.dummyValue( + this, + Invocation.method(#getUiOrientation, []), ), ), - ) as _i4.DiagnosticsNode); -} + ) as _i5.Future); -/// A class which mocks [Camera]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockCamera extends _i1.Mock implements _i12.Camera { @override - _i17.Future<_i5.CameraInfo> getCameraInfo() => (super.noSuchMethod( - Invocation.method( - #getCameraInfo, - [], - ), - returnValue: _i17.Future<_i5.CameraInfo>.value(_FakeCameraInfo_3( + _i2.DeviceOrientationManager pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeDeviceOrientationManager_18( this, - Invocation.method( - #getCameraInfo, - [], - ), - )), - returnValueForMissingStub: - _i17.Future<_i5.CameraInfo>.value(_FakeCameraInfo_3( - this, - Invocation.method( - #getCameraInfo, - [], - ), - )), - ) as _i17.Future<_i5.CameraInfo>); - - @override - _i17.Future<_i6.CameraControl> getCameraControl() => (super.noSuchMethod( - Invocation.method( - #getCameraControl, - [], + Invocation.method(#pigeon_copy, []), ), - returnValue: _i17.Future<_i6.CameraControl>.value(_FakeCameraControl_4( - this, - Invocation.method( - #getCameraControl, - [], - ), - )), - returnValueForMissingStub: - _i17.Future<_i6.CameraControl>.value(_FakeCameraControl_4( + returnValueForMissingStub: _FakeDeviceOrientationManager_18( this, - Invocation.method( - #getCameraControl, - [], - ), - )), - ) as _i17.Future<_i6.CameraControl>); + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.DeviceOrientationManager); } -/// A class which mocks [CameraInfo]. +/// A class which mocks [DisplayOrientedMeteringPointFactory]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockCameraInfo extends _i1.Mock implements _i5.CameraInfo { +class MockDisplayOrientedMeteringPointFactory extends _i1.Mock + implements _i2.DisplayOrientedMeteringPointFactory { @override - _i17.Future getSensorRotationDegrees() => (super.noSuchMethod( - Invocation.method( - #getSensorRotationDegrees, - [], + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), ), - returnValue: _i17.Future.value(0), - returnValueForMissingStub: _i17.Future.value(0), - ) as _i17.Future); + ) as _i2.PigeonInstanceManager); @override - _i17.Future<_i7.LiveData<_i20.CameraState>> getCameraState() => - (super.noSuchMethod( - Invocation.method( - #getCameraState, - [], - ), - returnValue: _i17.Future<_i7.LiveData<_i20.CameraState>>.value( - _FakeLiveData_5<_i20.CameraState>( + _i2.DisplayOrientedMeteringPointFactory pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeDisplayOrientedMeteringPointFactory_32( this, - Invocation.method( - #getCameraState, - [], - ), - )), - returnValueForMissingStub: - _i17.Future<_i7.LiveData<_i20.CameraState>>.value( - _FakeLiveData_5<_i20.CameraState>( + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeDisplayOrientedMeteringPointFactory_32( this, - Invocation.method( - #getCameraState, - [], - ), - )), - ) as _i17.Future<_i7.LiveData<_i20.CameraState>>); + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.DisplayOrientedMeteringPointFactory); @override - _i17.Future<_i8.ExposureState> getExposureState() => (super.noSuchMethod( - Invocation.method( - #getExposureState, - [], - ), - returnValue: _i17.Future<_i8.ExposureState>.value(_FakeExposureState_6( - this, - Invocation.method( - #getExposureState, - [], + _i5.Future<_i2.MeteringPoint> createPoint(double? x, double? y) => + (super.noSuchMethod( + Invocation.method(#createPoint, [x, y]), + returnValue: _i5.Future<_i2.MeteringPoint>.value( + _FakeMeteringPoint_35( + this, + Invocation.method(#createPoint, [x, y]), ), - )), - returnValueForMissingStub: - _i17.Future<_i8.ExposureState>.value(_FakeExposureState_6( - this, - Invocation.method( - #getExposureState, - [], + ), + returnValueForMissingStub: _i5.Future<_i2.MeteringPoint>.value( + _FakeMeteringPoint_35( + this, + Invocation.method(#createPoint, [x, y]), ), - )), - ) as _i17.Future<_i8.ExposureState>); + ), + ) as _i5.Future<_i2.MeteringPoint>); @override - _i17.Future<_i7.LiveData<_i21.ZoomState>> getZoomState() => + _i5.Future<_i2.MeteringPoint> createPointWithSize( + double? x, + double? y, + double? size, + ) => (super.noSuchMethod( - Invocation.method( - #getZoomState, - [], - ), - returnValue: _i17.Future<_i7.LiveData<_i21.ZoomState>>.value( - _FakeLiveData_5<_i21.ZoomState>( - this, - Invocation.method( - #getZoomState, - [], + Invocation.method(#createPointWithSize, [x, y, size]), + returnValue: _i5.Future<_i2.MeteringPoint>.value( + _FakeMeteringPoint_35( + this, + Invocation.method(#createPointWithSize, [x, y, size]), ), - )), - returnValueForMissingStub: - _i17.Future<_i7.LiveData<_i21.ZoomState>>.value( - _FakeLiveData_5<_i21.ZoomState>( - this, - Invocation.method( - #getZoomState, - [], + ), + returnValueForMissingStub: _i5.Future<_i2.MeteringPoint>.value( + _FakeMeteringPoint_35( + this, + Invocation.method(#createPointWithSize, [x, y, size]), ), - )), - ) as _i17.Future<_i7.LiveData<_i21.ZoomState>>); + ), + ) as _i5.Future<_i2.MeteringPoint>); } -/// A class which mocks [CameraControl]. +/// A class which mocks [ExposureState]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockCameraControl extends _i1.Mock implements _i6.CameraControl { +class MockExposureState extends _i1.Mock implements _i2.ExposureState { @override - _i17.Future enableTorch(bool? torch) => (super.noSuchMethod( - Invocation.method( - #enableTorch, - [torch], + _i2.CameraIntegerRange get exposureCompensationRange => (super.noSuchMethod( + Invocation.getter(#exposureCompensationRange), + returnValue: _FakeCameraIntegerRange_15( + this, + Invocation.getter(#exposureCompensationRange), ), - returnValue: _i17.Future.value(), - returnValueForMissingStub: _i17.Future.value(), - ) as _i17.Future); - - @override - _i17.Future setZoomRatio(double? ratio) => (super.noSuchMethod( - Invocation.method( - #setZoomRatio, - [ratio], + returnValueForMissingStub: _FakeCameraIntegerRange_15( + this, + Invocation.getter(#exposureCompensationRange), ), - returnValue: _i17.Future.value(), - returnValueForMissingStub: _i17.Future.value(), - ) as _i17.Future); + ) as _i2.CameraIntegerRange); @override - _i17.Future<_i22.FocusMeteringResult?> startFocusAndMetering( - _i23.FocusMeteringAction? action) => - (super.noSuchMethod( - Invocation.method( - #startFocusAndMetering, - [action], - ), - returnValue: _i17.Future<_i22.FocusMeteringResult?>.value(), - returnValueForMissingStub: - _i17.Future<_i22.FocusMeteringResult?>.value(), - ) as _i17.Future<_i22.FocusMeteringResult?>); + double get exposureCompensationStep => (super.noSuchMethod( + Invocation.getter(#exposureCompensationStep), + returnValue: 0.0, + returnValueForMissingStub: 0.0, + ) as double); @override - _i17.Future cancelFocusAndMetering() => (super.noSuchMethod( - Invocation.method( - #cancelFocusAndMetering, - [], + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), ), - returnValue: _i17.Future.value(), - returnValueForMissingStub: _i17.Future.value(), - ) as _i17.Future); - - @override - _i17.Future setExposureCompensationIndex(int? index) => - (super.noSuchMethod( - Invocation.method( - #setExposureCompensationIndex, - [index], + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), ), - returnValue: _i17.Future.value(), - returnValueForMissingStub: _i17.Future.value(), - ) as _i17.Future); -} + ) as _i2.PigeonInstanceManager); -/// A class which mocks [Camera2CameraControl]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockCamera2CameraControl extends _i1.Mock - implements _i24.Camera2CameraControl { @override - _i6.CameraControl get cameraControl => (super.noSuchMethod( - Invocation.getter(#cameraControl), - returnValue: _FakeCameraControl_4( + _i2.ExposureState pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeExposureState_6( this, - Invocation.getter(#cameraControl), + Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakeCameraControl_4( + returnValueForMissingStub: _FakeExposureState_6( this, - Invocation.getter(#cameraControl), - ), - ) as _i6.CameraControl); - - @override - _i17.Future addCaptureRequestOptions( - _i25.CaptureRequestOptions? captureRequestOptions) => - (super.noSuchMethod( - Invocation.method( - #addCaptureRequestOptions, - [captureRequestOptions], + Invocation.method(#pigeon_copy, []), ), - returnValue: _i17.Future.value(), - returnValueForMissingStub: _i17.Future.value(), - ) as _i17.Future); + ) as _i2.ExposureState); } -/// A class which mocks [Camera2CameraInfo]. +/// A class which mocks [FallbackStrategy]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockCamera2CameraInfo extends _i1.Mock implements _i26.Camera2CameraInfo { +class MockFallbackStrategy extends _i1.Mock implements _i2.FallbackStrategy { @override - _i17.Future getSupportedHardwareLevel() => (super.noSuchMethod( - Invocation.method( - #getSupportedHardwareLevel, - [], + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), ), - returnValue: _i17.Future.value(0), - returnValueForMissingStub: _i17.Future.value(0), - ) as _i17.Future); + ) as _i2.PigeonInstanceManager); @override - _i17.Future getCameraId() => (super.noSuchMethod( - Invocation.method( - #getCameraId, - [], - ), - returnValue: _i17.Future.value(_i27.dummyValue( + _i2.FallbackStrategy pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeFallbackStrategy_28( this, - Invocation.method( - #getCameraId, - [], - ), - )), - returnValueForMissingStub: - _i17.Future.value(_i27.dummyValue( + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeFallbackStrategy_28( this, - Invocation.method( - #getCameraId, - [], - ), - )), - ) as _i17.Future); - - @override - _i17.Future getSensorOrientation() => (super.noSuchMethod( - Invocation.method( - #getSensorOrientation, - [], + Invocation.method(#pigeon_copy, []), ), - returnValue: _i17.Future.value(0), - returnValueForMissingStub: _i17.Future.value(0), - ) as _i17.Future); + ) as _i2.FallbackStrategy); } -/// A class which mocks [CameraImageData]. +/// A class which mocks [FocusMeteringActionBuilder]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockCameraImageData extends _i1.Mock implements _i9.CameraImageData { +class MockFocusMeteringActionBuilder extends _i1.Mock + implements _i2.FocusMeteringActionBuilder { @override - _i9.CameraImageFormat get format => (super.noSuchMethod( - Invocation.getter(#format), - returnValue: _FakeCameraImageFormat_7( + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( this, - Invocation.getter(#format), + Invocation.getter(#pigeon_instanceManager), ), - returnValueForMissingStub: _FakeCameraImageFormat_7( + returnValueForMissingStub: _FakePigeonInstanceManager_0( this, - Invocation.getter(#format), + Invocation.getter(#pigeon_instanceManager), ), - ) as _i9.CameraImageFormat); + ) as _i2.PigeonInstanceManager); @override - int get height => (super.noSuchMethod( - Invocation.getter(#height), - returnValue: 0, - returnValueForMissingStub: 0, - ) as int); + _i5.Future addPoint(_i2.MeteringPoint? point) => (super.noSuchMethod( + Invocation.method(#addPoint, [point]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - int get width => (super.noSuchMethod( - Invocation.getter(#width), - returnValue: 0, - returnValueForMissingStub: 0, - ) as int); + _i5.Future addPointWithMode( + _i2.MeteringPoint? point, + _i2.MeteringMode? mode, + ) => + (super.noSuchMethod( + Invocation.method(#addPointWithMode, [point, mode]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - List<_i9.CameraImagePlane> get planes => (super.noSuchMethod( - Invocation.getter(#planes), - returnValue: <_i9.CameraImagePlane>[], - returnValueForMissingStub: <_i9.CameraImagePlane>[], - ) as List<_i9.CameraImagePlane>); -} + _i5.Future disableAutoCancel() => (super.noSuchMethod( + Invocation.method(#disableAutoCancel, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); -/// A class which mocks [CameraSelector]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockCameraSelector extends _i1.Mock implements _i28.CameraSelector { @override - _i17.Future> filter(List<_i5.CameraInfo>? cameraInfos) => - (super.noSuchMethod( - Invocation.method( - #filter, - [cameraInfos], + _i5.Future<_i2.FocusMeteringAction> build() => (super.noSuchMethod( + Invocation.method(#build, []), + returnValue: _i5.Future<_i2.FocusMeteringAction>.value( + _FakeFocusMeteringAction_36(this, Invocation.method(#build, [])), ), - returnValue: - _i17.Future>.value(<_i5.CameraInfo>[]), - returnValueForMissingStub: - _i17.Future>.value(<_i5.CameraInfo>[]), - ) as _i17.Future>); -} + returnValueForMissingStub: _i5.Future<_i2.FocusMeteringAction>.value( + _FakeFocusMeteringAction_36( + this, + Invocation.method(#build, []), + ), + ), + ) as _i5.Future<_i2.FocusMeteringAction>); -/// A class which mocks [ExposureState]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockExposureState extends _i1.Mock implements _i8.ExposureState { @override - _i10.ExposureCompensationRange get exposureCompensationRange => - (super.noSuchMethod( - Invocation.getter(#exposureCompensationRange), - returnValue: _FakeExposureCompensationRange_8( + _i2.FocusMeteringActionBuilder pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeFocusMeteringActionBuilder_29( this, - Invocation.getter(#exposureCompensationRange), + Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakeExposureCompensationRange_8( + returnValueForMissingStub: _FakeFocusMeteringActionBuilder_29( this, - Invocation.getter(#exposureCompensationRange), + Invocation.method(#pigeon_copy, []), ), - ) as _i10.ExposureCompensationRange); - - @override - double get exposureCompensationStep => (super.noSuchMethod( - Invocation.getter(#exposureCompensationStep), - returnValue: 0.0, - returnValueForMissingStub: 0.0, - ) as double); + ) as _i2.FocusMeteringActionBuilder); } -/// A class which mocks [FallbackStrategy]. +/// A class which mocks [FocusMeteringResult]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockFallbackStrategy extends _i1.Mock implements _i29.FallbackStrategy { +class MockFocusMeteringResult extends _i1.Mock + implements _i2.FocusMeteringResult { @override - _i10.VideoQuality get quality => (super.noSuchMethod( - Invocation.getter(#quality), - returnValue: _i10.VideoQuality.SD, - returnValueForMissingStub: _i10.VideoQuality.SD, - ) as _i10.VideoQuality); + bool get isFocusSuccessful => (super.noSuchMethod( + Invocation.getter(#isFocusSuccessful), + returnValue: false, + returnValueForMissingStub: false, + ) as bool); @override - _i10.VideoResolutionFallbackRule get fallbackRule => (super.noSuchMethod( - Invocation.getter(#fallbackRule), - returnValue: _i10.VideoResolutionFallbackRule.higherQualityOrLowerThan, - returnValueForMissingStub: - _i10.VideoResolutionFallbackRule.higherQualityOrLowerThan, - ) as _i10.VideoResolutionFallbackRule); -} + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); -/// A class which mocks [FocusMeteringResult]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockFocusMeteringResult extends _i1.Mock - implements _i22.FocusMeteringResult { @override - _i17.Future isFocusSuccessful() => (super.noSuchMethod( - Invocation.method( - #isFocusSuccessful, - [], + _i2.FocusMeteringResult pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeFocusMeteringResult_37( + this, + Invocation.method(#pigeon_copy, []), ), - returnValue: _i17.Future.value(false), - returnValueForMissingStub: _i17.Future.value(false), - ) as _i17.Future); + returnValueForMissingStub: _FakeFocusMeteringResult_37( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.FocusMeteringResult); } /// A class which mocks [ImageAnalysis]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockImageAnalysis extends _i1.Mock implements _i30.ImageAnalysis { +class MockImageAnalysis extends _i1.Mock implements _i2.ImageAnalysis { @override - _i17.Future setTargetRotation(int? rotation) => (super.noSuchMethod( - Invocation.method( - #setTargetRotation, - [rotation], + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), ), - returnValue: _i17.Future.value(), - returnValueForMissingStub: _i17.Future.value(), - ) as _i17.Future); + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i17.Future setAnalyzer(_i16.Analyzer? analyzer) => (super.noSuchMethod( - Invocation.method( - #setAnalyzer, - [analyzer], - ), - returnValue: _i17.Future.value(), - returnValueForMissingStub: _i17.Future.value(), - ) as _i17.Future); + _i5.Future setAnalyzer(_i2.Analyzer? analyzer) => (super.noSuchMethod( + Invocation.method(#setAnalyzer, [analyzer]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future clearAnalyzer() => (super.noSuchMethod( + Invocation.method(#clearAnalyzer, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future setTargetRotation(int? rotation) => (super.noSuchMethod( + Invocation.method(#setTargetRotation, [rotation]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i17.Future clearAnalyzer() => (super.noSuchMethod( - Invocation.method( - #clearAnalyzer, - [], + _i2.ImageAnalysis pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeImageAnalysis_26( + this, + Invocation.method(#pigeon_copy, []), ), - returnValue: _i17.Future.value(), - returnValueForMissingStub: _i17.Future.value(), - ) as _i17.Future); + returnValueForMissingStub: _FakeImageAnalysis_26( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.ImageAnalysis); } /// A class which mocks [ImageCapture]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockImageCapture extends _i1.Mock implements _i31.ImageCapture { +class MockImageCapture extends _i1.Mock implements _i2.ImageCapture { @override - _i17.Future setTargetRotation(int? rotation) => (super.noSuchMethod( - Invocation.method( - #setTargetRotation, - [rotation], + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), ), - returnValue: _i17.Future.value(), - returnValueForMissingStub: _i17.Future.value(), - ) as _i17.Future); + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - _i17.Future setFlashMode(int? newFlashMode) => (super.noSuchMethod( - Invocation.method( - #setFlashMode, - [newFlashMode], - ), - returnValue: _i17.Future.value(), - returnValueForMissingStub: _i17.Future.value(), - ) as _i17.Future); + _i5.Future setFlashMode(_i2.CameraXFlashMode? flashMode) => + (super.noSuchMethod( + Invocation.method(#setFlashMode, [flashMode]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i17.Future takePicture() => (super.noSuchMethod( - Invocation.method( - #takePicture, - [], + _i5.Future takePicture() => (super.noSuchMethod( + Invocation.method(#takePicture, []), + returnValue: _i5.Future.value( + _i6.dummyValue(this, Invocation.method(#takePicture, [])), ), - returnValue: _i17.Future.value(_i27.dummyValue( + returnValueForMissingStub: _i5.Future.value( + _i6.dummyValue(this, Invocation.method(#takePicture, [])), + ), + ) as _i5.Future); + + @override + _i5.Future setTargetRotation(int? rotation) => (super.noSuchMethod( + Invocation.method(#setTargetRotation, [rotation]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.ImageCapture pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeImageCapture_23( this, - Invocation.method( - #takePicture, - [], - ), - )), - returnValueForMissingStub: - _i17.Future.value(_i27.dummyValue( + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeImageCapture_23( this, - Invocation.method( - #takePicture, - [], - ), - )), - ) as _i17.Future); + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.ImageCapture); } /// A class which mocks [ImageProxy]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockImageProxy extends _i1.Mock implements _i18.ImageProxy { +class MockImageProxy extends _i1.Mock implements _i2.ImageProxy { @override int get format => (super.noSuchMethod( Invocation.getter(#format), @@ -963,104 +2598,156 @@ class MockImageProxy extends _i1.Mock implements _i18.ImageProxy { ) as int); @override - int get height => (super.noSuchMethod( - Invocation.getter(#height), + int get width => (super.noSuchMethod( + Invocation.getter(#width), returnValue: 0, returnValueForMissingStub: 0, ) as int); @override - int get width => (super.noSuchMethod( - Invocation.getter(#width), + int get height => (super.noSuchMethod( + Invocation.getter(#height), returnValue: 0, returnValueForMissingStub: 0, ) as int); @override - _i17.Future> getPlanes() => (super.noSuchMethod( - Invocation.method( - #getPlanes, - [], + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), ), - returnValue: - _i17.Future>.value(<_i32.PlaneProxy>[]), - returnValueForMissingStub: - _i17.Future>.value(<_i32.PlaneProxy>[]), - ) as _i17.Future>); + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future> getPlanes() => (super.noSuchMethod( + Invocation.method(#getPlanes, []), + returnValue: _i5.Future>.value( + <_i2.PlaneProxy>[], + ), + returnValueForMissingStub: _i5.Future>.value( + <_i2.PlaneProxy>[], + ), + ) as _i5.Future>); + + @override + _i5.Future close() => (super.noSuchMethod( + Invocation.method(#close, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i17.Future close() => (super.noSuchMethod( - Invocation.method( - #close, - [], + _i2.ImageProxy pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeImageProxy_38( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeImageProxy_38( + this, + Invocation.method(#pigeon_copy, []), ), - returnValue: _i17.Future.value(), - returnValueForMissingStub: _i17.Future.value(), - ) as _i17.Future); + ) as _i2.ImageProxy); } /// A class which mocks [Observer]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockObserver extends _i1.Mock implements _i33.Observer<_i20.CameraState> { +class MockObserver extends _i1.Mock implements _i3.Observer<_i2.CameraState> { @override - void Function(Object) get onChanged => (super.noSuchMethod( + void Function(_i2.Observer, Object) get onChanged => (super.noSuchMethod( Invocation.getter(#onChanged), - returnValue: (Object value) {}, - returnValueForMissingStub: (Object value) {}, - ) as void Function(Object)); + returnValue: (_i2.Observer pigeon_instance, Object value) {}, + returnValueForMissingStub: + (_i2.Observer pigeon_instance, Object value) {}, + ) as void Function(_i2.Observer, Object)); @override - set onChanged(void Function(Object)? _onChanged) => super.noSuchMethod( - Invocation.setter( - #onChanged, - _onChanged, + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), ), - returnValueForMissingStub: null, - ); + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i3.Observer<_i2.CameraState> pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeObserver_16<_i2.CameraState>( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeObserver_16<_i2.CameraState>( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i3.Observer<_i2.CameraState>); } /// A class which mocks [PendingRecording]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockPendingRecording extends _i1.Mock implements _i13.PendingRecording { +class MockPendingRecording extends _i1.Mock implements _i2.PendingRecording { + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + @override - _i17.Future<_i11.Recording> start() => (super.noSuchMethod( - Invocation.method( - #start, - [], + _i5.Future<_i2.Recording> start(_i2.VideoRecordEventListener? listener) => + (super.noSuchMethod( + Invocation.method(#start, [listener]), + returnValue: _i5.Future<_i2.Recording>.value( + _FakeRecording_39(this, Invocation.method(#start, [listener])), ), - returnValue: _i17.Future<_i11.Recording>.value(_FakeRecording_9( + returnValueForMissingStub: _i5.Future<_i2.Recording>.value( + _FakeRecording_39(this, Invocation.method(#start, [listener])), + ), + ) as _i5.Future<_i2.Recording>); + + @override + _i2.PendingRecording pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakePendingRecording_40( this, - Invocation.method( - #start, - [], - ), - )), - returnValueForMissingStub: - _i17.Future<_i11.Recording>.value(_FakeRecording_9( + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakePendingRecording_40( this, - Invocation.method( - #start, - [], - ), - )), - ) as _i17.Future<_i11.Recording>); + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.PendingRecording); } /// A class which mocks [PlaneProxy]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockPlaneProxy extends _i1.Mock implements _i32.PlaneProxy { +class MockPlaneProxy extends _i1.Mock implements _i2.PlaneProxy { @override - _i34.Uint8List get buffer => (super.noSuchMethod( + _i9.Uint8List get buffer => (super.noSuchMethod( Invocation.getter(#buffer), - returnValue: _i34.Uint8List(0), - returnValueForMissingStub: _i34.Uint8List(0), - ) as _i34.Uint8List); + returnValue: _i9.Uint8List(0), + returnValueForMissingStub: _i9.Uint8List(0), + ) as _i9.Uint8List); @override int get pixelStride => (super.noSuchMethod( @@ -1075,398 +2762,621 @@ class MockPlaneProxy extends _i1.Mock implements _i32.PlaneProxy { returnValue: 0, returnValueForMissingStub: 0, ) as int); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.PlaneProxy pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakePlaneProxy_41( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakePlaneProxy_41( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.PlaneProxy); } /// A class which mocks [Preview]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockPreview extends _i1.Mock implements _i35.Preview { +class MockPreview extends _i1.Mock implements _i2.Preview { @override - _i17.Future setTargetRotation(int? rotation) => (super.noSuchMethod( - Invocation.method( - #setTargetRotation, - [rotation], + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), ), - returnValue: _i17.Future.value(), - returnValueForMissingStub: _i17.Future.value(), - ) as _i17.Future); + ) as _i2.PigeonInstanceManager); @override - _i17.Future setSurfaceProvider() => (super.noSuchMethod( - Invocation.method( - #setSurfaceProvider, - [], - ), - returnValue: _i17.Future.value(0), - returnValueForMissingStub: _i17.Future.value(0), - ) as _i17.Future); + _i5.Future setSurfaceProvider( + _i2.SystemServicesManager? systemServicesManager, + ) => + (super.noSuchMethod( + Invocation.method(#setSurfaceProvider, [systemServicesManager]), + returnValue: _i5.Future.value(0), + returnValueForMissingStub: _i5.Future.value(0), + ) as _i5.Future); @override - void releaseFlutterSurfaceTexture() => super.noSuchMethod( - Invocation.method( - #releaseFlutterSurfaceTexture, - [], - ), - returnValueForMissingStub: null, - ); + _i5.Future releaseSurfaceProvider() => (super.noSuchMethod( + Invocation.method(#releaseSurfaceProvider, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i17.Future<_i10.ResolutionInfo> getResolutionInfo() => (super.noSuchMethod( - Invocation.method( - #getResolutionInfo, - [], - ), - returnValue: - _i17.Future<_i10.ResolutionInfo>.value(_FakeResolutionInfo_10( - this, - Invocation.method( - #getResolutionInfo, - [], - ), - )), - returnValueForMissingStub: - _i17.Future<_i10.ResolutionInfo>.value(_FakeResolutionInfo_10( - this, - Invocation.method( - #getResolutionInfo, - [], - ), - )), - ) as _i17.Future<_i10.ResolutionInfo>); + _i5.Future<_i2.ResolutionInfo?> getResolutionInfo() => (super.noSuchMethod( + Invocation.method(#getResolutionInfo, []), + returnValue: _i5.Future<_i2.ResolutionInfo?>.value(), + returnValueForMissingStub: _i5.Future<_i2.ResolutionInfo?>.value(), + ) as _i5.Future<_i2.ResolutionInfo?>); + + @override + _i5.Future setTargetRotation(int? rotation) => (super.noSuchMethod( + Invocation.method(#setTargetRotation, [rotation]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - _i17.Future surfaceProducerHandlesCropAndRotation() => + _i5.Future surfaceProducerHandlesCropAndRotation() => (super.noSuchMethod( - Invocation.method( - #surfaceProducerHandlesCropAndRotation, - [], + Invocation.method(#surfaceProducerHandlesCropAndRotation, []), + returnValue: _i5.Future.value(false), + returnValueForMissingStub: _i5.Future.value(false), + ) as _i5.Future); + + @override + _i2.Preview pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakePreview_19( + this, + Invocation.method(#pigeon_copy, []), ), - returnValue: _i17.Future.value(false), - returnValueForMissingStub: _i17.Future.value(false), - ) as _i17.Future); + returnValueForMissingStub: _FakePreview_19( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.Preview); } /// A class which mocks [ProcessCameraProvider]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable class MockProcessCameraProvider extends _i1.Mock - implements _i36.ProcessCameraProvider { + implements _i2.ProcessCameraProvider { + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + @override - _i17.Future> getAvailableCameraInfos() => + _i5.Future> getAvailableCameraInfos() => (super.noSuchMethod( - Invocation.method( - #getAvailableCameraInfos, - [], + Invocation.method(#getAvailableCameraInfos, []), + returnValue: _i5.Future>.value( + <_i2.CameraInfo>[], ), - returnValue: - _i17.Future>.value(<_i5.CameraInfo>[]), - returnValueForMissingStub: - _i17.Future>.value(<_i5.CameraInfo>[]), - ) as _i17.Future>); + returnValueForMissingStub: _i5.Future>.value( + <_i2.CameraInfo>[], + ), + ) as _i5.Future>); @override - _i17.Future<_i12.Camera> bindToLifecycle( - _i28.CameraSelector? cameraSelector, - List<_i37.UseCase>? useCases, + _i5.Future<_i2.Camera> bindToLifecycle( + _i2.CameraSelector? cameraSelector, + List<_i2.UseCase>? useCases, ) => (super.noSuchMethod( - Invocation.method( - #bindToLifecycle, - [ - cameraSelector, - useCases, - ], - ), - returnValue: _i17.Future<_i12.Camera>.value(_FakeCamera_11( - this, - Invocation.method( - #bindToLifecycle, - [ - cameraSelector, - useCases, - ], + Invocation.method(#bindToLifecycle, [cameraSelector, useCases]), + returnValue: _i5.Future<_i2.Camera>.value( + _FakeCamera_5( + this, + Invocation.method(#bindToLifecycle, [cameraSelector, useCases]), ), - )), - returnValueForMissingStub: - _i17.Future<_i12.Camera>.value(_FakeCamera_11( - this, - Invocation.method( - #bindToLifecycle, - [ - cameraSelector, - useCases, - ], + ), + returnValueForMissingStub: _i5.Future<_i2.Camera>.value( + _FakeCamera_5( + this, + Invocation.method(#bindToLifecycle, [cameraSelector, useCases]), ), - )), - ) as _i17.Future<_i12.Camera>); + ), + ) as _i5.Future<_i2.Camera>); @override - _i17.Future isBound(_i37.UseCase? useCase) => (super.noSuchMethod( - Invocation.method( - #isBound, - [useCase], - ), - returnValue: _i17.Future.value(false), - returnValueForMissingStub: _i17.Future.value(false), - ) as _i17.Future); + _i5.Future isBound(_i2.UseCase? useCase) => (super.noSuchMethod( + Invocation.method(#isBound, [useCase]), + returnValue: _i5.Future.value(false), + returnValueForMissingStub: _i5.Future.value(false), + ) as _i5.Future); @override - void unbind(List<_i37.UseCase>? useCases) => super.noSuchMethod( - Invocation.method( - #unbind, - [useCases], - ), - returnValueForMissingStub: null, - ); + _i5.Future unbind(List<_i2.UseCase>? useCases) => (super.noSuchMethod( + Invocation.method(#unbind, [useCases]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future unbindAll() => (super.noSuchMethod( + Invocation.method(#unbindAll, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); @override - void unbindAll() => super.noSuchMethod( - Invocation.method( - #unbindAll, - [], + _i2.ProcessCameraProvider pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeProcessCameraProvider_33( + this, + Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: null, - ); + returnValueForMissingStub: _FakeProcessCameraProvider_33( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.ProcessCameraProvider); } /// A class which mocks [QualitySelector]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockQualitySelector extends _i1.Mock implements _i38.QualitySelector { +class MockQualitySelector extends _i1.Mock implements _i2.QualitySelector { + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + @override - List<_i10.VideoQualityData> get qualityList => (super.noSuchMethod( - Invocation.getter(#qualityList), - returnValue: <_i10.VideoQualityData>[], - returnValueForMissingStub: <_i10.VideoQualityData>[], - ) as List<_i10.VideoQualityData>); + _i2.QualitySelector pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeQualitySelector_27( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeQualitySelector_27( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.QualitySelector); } /// A class which mocks [Recorder]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockRecorder extends _i1.Mock implements _i15.Recorder { +class MockRecorder extends _i1.Mock implements _i2.Recorder { @override - _i17.Future<_i13.PendingRecording> prepareRecording(String? path) => - (super.noSuchMethod( - Invocation.method( - #prepareRecording, - [path], + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), ), - returnValue: - _i17.Future<_i13.PendingRecording>.value(_FakePendingRecording_12( + returnValueForMissingStub: _FakePigeonInstanceManager_0( this, - Invocation.method( - #prepareRecording, - [path], + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future getAspectRatio() => (super.noSuchMethod( + Invocation.method(#getAspectRatio, []), + returnValue: _i5.Future.value(0), + returnValueForMissingStub: _i5.Future.value(0), + ) as _i5.Future); + + @override + _i5.Future getTargetVideoEncodingBitRate() => (super.noSuchMethod( + Invocation.method(#getTargetVideoEncodingBitRate, []), + returnValue: _i5.Future.value(0), + returnValueForMissingStub: _i5.Future.value(0), + ) as _i5.Future); + + @override + _i5.Future<_i2.QualitySelector> getQualitySelector() => (super.noSuchMethod( + Invocation.method(#getQualitySelector, []), + returnValue: _i5.Future<_i2.QualitySelector>.value( + _FakeQualitySelector_27( + this, + Invocation.method(#getQualitySelector, []), ), - )), - returnValueForMissingStub: - _i17.Future<_i13.PendingRecording>.value(_FakePendingRecording_12( - this, - Invocation.method( - #prepareRecording, - [path], + ), + returnValueForMissingStub: _i5.Future<_i2.QualitySelector>.value( + _FakeQualitySelector_27( + this, + Invocation.method(#getQualitySelector, []), + ), + ), + ) as _i5.Future<_i2.QualitySelector>); + + @override + _i5.Future<_i2.PendingRecording> prepareRecording(String? path) => + (super.noSuchMethod( + Invocation.method(#prepareRecording, [path]), + returnValue: _i5.Future<_i2.PendingRecording>.value( + _FakePendingRecording_40( + this, + Invocation.method(#prepareRecording, [path]), + ), + ), + returnValueForMissingStub: _i5.Future<_i2.PendingRecording>.value( + _FakePendingRecording_40( + this, + Invocation.method(#prepareRecording, [path]), ), - )), - ) as _i17.Future<_i13.PendingRecording>); + ), + ) as _i5.Future<_i2.PendingRecording>); + + @override + _i2.Recorder pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeRecorder_21( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeRecorder_21( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.Recorder); } /// A class which mocks [ResolutionFilter]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockResolutionFilter extends _i1.Mock implements _i39.ResolutionFilter { +class MockResolutionFilter extends _i1.Mock implements _i2.ResolutionFilter { @override - _i14.Size get preferredResolution => (super.noSuchMethod( - Invocation.getter(#preferredResolution), - returnValue: _FakeSize_13( + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( this, - Invocation.getter(#preferredResolution), + Invocation.getter(#pigeon_instanceManager), ), - returnValueForMissingStub: _FakeSize_13( + returnValueForMissingStub: _FakePigeonInstanceManager_0( this, - Invocation.getter(#preferredResolution), + Invocation.getter(#pigeon_instanceManager), ), - ) as _i14.Size); + ) as _i2.PigeonInstanceManager); + + @override + _i2.ResolutionFilter pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeResolutionFilter_31( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeResolutionFilter_31( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.ResolutionFilter); } /// A class which mocks [ResolutionSelector]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable class MockResolutionSelector extends _i1.Mock - implements _i40.ResolutionSelector {} + implements _i2.ResolutionSelector { + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future<_i2.AspectRatioStrategy> getAspectRatioStrategy() => + (super.noSuchMethod( + Invocation.method(#getAspectRatioStrategy, []), + returnValue: _i5.Future<_i2.AspectRatioStrategy>.value( + _FakeAspectRatioStrategy_2( + this, + Invocation.method(#getAspectRatioStrategy, []), + ), + ), + returnValueForMissingStub: _i5.Future<_i2.AspectRatioStrategy>.value( + _FakeAspectRatioStrategy_2( + this, + Invocation.method(#getAspectRatioStrategy, []), + ), + ), + ) as _i5.Future<_i2.AspectRatioStrategy>); + + @override + _i2.ResolutionSelector pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeResolutionSelector_25( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeResolutionSelector_25( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.ResolutionSelector); +} /// A class which mocks [ResolutionStrategy]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable class MockResolutionStrategy extends _i1.Mock - implements _i41.ResolutionStrategy {} - -/// A class which mocks [Recording]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockRecording extends _i1.Mock implements _i11.Recording { + implements _i2.ResolutionStrategy { @override - _i17.Future close() => (super.noSuchMethod( - Invocation.method( - #close, - [], + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), ), - returnValue: _i17.Future.value(), - returnValueForMissingStub: _i17.Future.value(), - ) as _i17.Future); + ) as _i2.PigeonInstanceManager); @override - _i17.Future pause() => (super.noSuchMethod( - Invocation.method( - #pause, - [], - ), - returnValue: _i17.Future.value(), - returnValueForMissingStub: _i17.Future.value(), - ) as _i17.Future); + _i5.Future<_i2.CameraSize?> getBoundSize() => (super.noSuchMethod( + Invocation.method(#getBoundSize, []), + returnValue: _i5.Future<_i2.CameraSize?>.value(), + returnValueForMissingStub: _i5.Future<_i2.CameraSize?>.value(), + ) as _i5.Future<_i2.CameraSize?>); @override - _i17.Future resume() => (super.noSuchMethod( - Invocation.method( - #resume, - [], + _i5.Future<_i2.ResolutionStrategyFallbackRule> getFallbackRule() => + (super.noSuchMethod( + Invocation.method(#getFallbackRule, []), + returnValue: _i5.Future<_i2.ResolutionStrategyFallbackRule>.value( + _i2.ResolutionStrategyFallbackRule.closestHigher, + ), + returnValueForMissingStub: + _i5.Future<_i2.ResolutionStrategyFallbackRule>.value( + _i2.ResolutionStrategyFallbackRule.closestHigher, ), - returnValue: _i17.Future.value(), - returnValueForMissingStub: _i17.Future.value(), - ) as _i17.Future); + ) as _i5.Future<_i2.ResolutionStrategyFallbackRule>); @override - _i17.Future stop() => (super.noSuchMethod( - Invocation.method( - #stop, - [], + _i2.ResolutionStrategy pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeResolutionStrategy_24( + this, + Invocation.method(#pigeon_copy, []), ), - returnValue: _i17.Future.value(), - returnValueForMissingStub: _i17.Future.value(), - ) as _i17.Future); + returnValueForMissingStub: _FakeResolutionStrategy_24( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.ResolutionStrategy); } -/// A class which mocks [TestInstanceManagerHostApi]. +/// A class which mocks [Recording]. /// /// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i42.TestInstanceManagerHostApi { +class MockRecording extends _i1.Mock implements _i2.Recording { @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), ), - returnValueForMissingStub: null, - ); + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future close() => (super.noSuchMethod( + Invocation.method(#close, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future pause() => (super.noSuchMethod( + Invocation.method(#pause, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future resume() => (super.noSuchMethod( + Invocation.method(#resume, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future stop() => (super.noSuchMethod( + Invocation.method(#stop, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.Recording pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeRecording_39( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeRecording_39( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.Recording); } -/// A class which mocks [TestSystemServicesHostApi]. +/// A class which mocks [SystemServicesManager]. /// /// See the documentation for Mockito's code generation for more information. -class MockTestSystemServicesHostApi extends _i1.Mock - implements _i42.TestSystemServicesHostApi { +class MockSystemServicesManager extends _i1.Mock + implements _i2.SystemServicesManager { @override - _i17.Future<_i10.CameraPermissionsErrorData?> requestCameraPermissions( - bool? enableAudio) => + void Function(_i2.SystemServicesManager, String) get onCameraError => (super.noSuchMethod( - Invocation.method( - #requestCameraPermissions, - [enableAudio], + Invocation.getter(#onCameraError), + returnValue: ( + _i2.SystemServicesManager pigeon_instance, + String errorDescription, + ) {}, + returnValueForMissingStub: ( + _i2.SystemServicesManager pigeon_instance, + String errorDescription, + ) {}, + ) as void Function(_i2.SystemServicesManager, String)); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), ), - returnValue: _i17.Future<_i10.CameraPermissionsErrorData?>.value(), - returnValueForMissingStub: - _i17.Future<_i10.CameraPermissionsErrorData?>.value(), - ) as _i17.Future<_i10.CameraPermissionsErrorData?>); + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); @override - String getTempFilePath( - String? prefix, - String? suffix, + _i5.Future<_i2.CameraPermissionsError?> requestCameraPermissions( + bool? enableAudio, ) => (super.noSuchMethod( - Invocation.method( - #getTempFilePath, - [ - prefix, - suffix, - ], - ), - returnValue: _i27.dummyValue( - this, - Invocation.method( - #getTempFilePath, - [ - prefix, - suffix, - ], + Invocation.method(#requestCameraPermissions, [enableAudio]), + returnValue: _i5.Future<_i2.CameraPermissionsError?>.value(), + returnValueForMissingStub: + _i5.Future<_i2.CameraPermissionsError?>.value(), + ) as _i5.Future<_i2.CameraPermissionsError?>); + + @override + _i5.Future getTempFilePath(String? prefix, String? suffix) => + (super.noSuchMethod( + Invocation.method(#getTempFilePath, [prefix, suffix]), + returnValue: _i5.Future.value( + _i6.dummyValue( + this, + Invocation.method(#getTempFilePath, [prefix, suffix]), ), ), - returnValueForMissingStub: _i27.dummyValue( - this, - Invocation.method( - #getTempFilePath, - [ - prefix, - suffix, - ], + returnValueForMissingStub: _i5.Future.value( + _i6.dummyValue( + this, + Invocation.method(#getTempFilePath, [prefix, suffix]), ), ), - ) as String); + ) as _i5.Future); + + @override + _i2.SystemServicesManager pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeSystemServicesManager_17( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeSystemServicesManager_17( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.SystemServicesManager); } /// A class which mocks [VideoCapture]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockVideoCapture extends _i1.Mock implements _i43.VideoCapture { +class MockVideoCapture extends _i1.Mock implements _i2.VideoCapture { @override - _i17.Future setTargetRotation(int? rotation) => (super.noSuchMethod( - Invocation.method( - #setTargetRotation, - [rotation], + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), ), - returnValue: _i17.Future.value(), - returnValueForMissingStub: _i17.Future.value(), - ) as _i17.Future); + ) as _i2.PigeonInstanceManager); @override - _i17.Future<_i15.Recorder> getOutput() => (super.noSuchMethod( - Invocation.method( - #getOutput, - [], + _i5.Future<_i2.VideoOutput> getOutput() => (super.noSuchMethod( + Invocation.method(#getOutput, []), + returnValue: _i5.Future<_i2.VideoOutput>.value( + _FakeVideoOutput_42(this, Invocation.method(#getOutput, [])), + ), + returnValueForMissingStub: _i5.Future<_i2.VideoOutput>.value( + _FakeVideoOutput_42(this, Invocation.method(#getOutput, [])), ), - returnValue: _i17.Future<_i15.Recorder>.value(_FakeRecorder_14( + ) as _i5.Future<_i2.VideoOutput>); + + @override + _i5.Future setTargetRotation(int? rotation) => (super.noSuchMethod( + Invocation.method(#setTargetRotation, [rotation]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i2.VideoCapture pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeVideoCapture_20( this, - Invocation.method( - #getOutput, - [], - ), - )), - returnValueForMissingStub: - _i17.Future<_i15.Recorder>.value(_FakeRecorder_14( + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeVideoCapture_20( this, - Invocation.method( - #getOutput, - [], - ), - )), - ) as _i17.Future<_i15.Recorder>); + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.VideoCapture); } /// A class which mocks [ZoomState]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockZoomState extends _i1.Mock implements _i21.ZoomState { +class MockZoomState extends _i1.Mock implements _i2.ZoomState { @override double get minZoomRatio => (super.noSuchMethod( Invocation.getter(#minZoomRatio), @@ -1480,68 +3390,138 @@ class MockZoomState extends _i1.Mock implements _i21.ZoomState { returnValue: 0.0, returnValueForMissingStub: 0.0, ) as double); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + returnValueForMissingStub: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), + ), + ) as _i2.PigeonInstanceManager); + + @override + _i2.ZoomState pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeZoomState_43( + this, + Invocation.method(#pigeon_copy, []), + ), + returnValueForMissingStub: _FakeZoomState_43( + this, + Invocation.method(#pigeon_copy, []), + ), + ) as _i2.ZoomState); } /// A class which mocks [LiveData]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable class MockLiveCameraState extends _i1.Mock - implements _i7.LiveData<_i20.CameraState> { + implements _i3.LiveData<_i2.CameraState> { MockLiveCameraState() { _i1.throwOnMissingStub(this); } @override - _i17.Future observe(_i33.Observer<_i20.CameraState>? observer) => - (super.noSuchMethod( - Invocation.method( - #observe, - [observer], + _i2.LiveDataSupportedType get type => (super.noSuchMethod( + Invocation.getter(#type), + returnValue: _i2.LiveDataSupportedType.cameraState, + ) as _i2.LiveDataSupportedType); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), ), - returnValue: _i17.Future.value(), - returnValueForMissingStub: _i17.Future.value(), - ) as _i17.Future); + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future observe(_i2.Observer? observer) => (super.noSuchMethod( + Invocation.method(#observe, [observer]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future<_i2.CameraState?> getValue() => (super.noSuchMethod( + Invocation.method(#getValue, []), + returnValue: _i5.Future<_i2.CameraState?>.value(), + ) as _i5.Future<_i2.CameraState?>); @override - _i17.Future removeObservers() => (super.noSuchMethod( - Invocation.method( - #removeObservers, - [], + _i3.LiveData<_i2.CameraState> pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeLiveData_7<_i2.CameraState>( + this, + Invocation.method(#pigeon_copy, []), ), - returnValue: _i17.Future.value(), - returnValueForMissingStub: _i17.Future.value(), - ) as _i17.Future); + ) as _i3.LiveData<_i2.CameraState>); + + @override + _i5.Future removeObservers() => (super.noSuchMethod( + Invocation.method(#removeObservers, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); } /// A class which mocks [LiveData]. /// /// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable class MockLiveZoomState extends _i1.Mock - implements _i7.LiveData<_i21.ZoomState> { + implements _i3.LiveData<_i2.ZoomState> { MockLiveZoomState() { _i1.throwOnMissingStub(this); } @override - _i17.Future observe(_i33.Observer<_i21.ZoomState>? observer) => - (super.noSuchMethod( - Invocation.method( - #observe, - [observer], + _i2.LiveDataSupportedType get type => (super.noSuchMethod( + Invocation.getter(#type), + returnValue: _i2.LiveDataSupportedType.cameraState, + ) as _i2.LiveDataSupportedType); + + @override + _i2.PigeonInstanceManager get pigeon_instanceManager => (super.noSuchMethod( + Invocation.getter(#pigeon_instanceManager), + returnValue: _FakePigeonInstanceManager_0( + this, + Invocation.getter(#pigeon_instanceManager), ), - returnValue: _i17.Future.value(), - returnValueForMissingStub: _i17.Future.value(), - ) as _i17.Future); + ) as _i2.PigeonInstanceManager); + + @override + _i5.Future observe(_i2.Observer? observer) => (super.noSuchMethod( + Invocation.method(#observe, [observer]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); + + @override + _i5.Future<_i2.ZoomState?> getValue() => (super.noSuchMethod( + Invocation.method(#getValue, []), + returnValue: _i5.Future<_i2.ZoomState?>.value(), + ) as _i5.Future<_i2.ZoomState?>); @override - _i17.Future removeObservers() => (super.noSuchMethod( - Invocation.method( - #removeObservers, - [], + _i3.LiveData<_i2.ZoomState> pigeon_copy() => (super.noSuchMethod( + Invocation.method(#pigeon_copy, []), + returnValue: _FakeLiveData_7<_i2.ZoomState>( + this, + Invocation.method(#pigeon_copy, []), ), - returnValue: _i17.Future.value(), - returnValueForMissingStub: _i17.Future.value(), - ) as _i17.Future); + ) as _i3.LiveData<_i2.ZoomState>); + + @override + _i5.Future removeObservers() => (super.noSuchMethod( + Invocation.method(#removeObservers, []), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) as _i5.Future); } diff --git a/packages/camera/camera_android_camerax/test/aspect_ratio_strategy_test.dart b/packages/camera/camera_android_camerax/test/aspect_ratio_strategy_test.dart deleted file mode 100644 index 28ec032a2a9e..000000000000 --- a/packages/camera/camera_android_camerax/test/aspect_ratio_strategy_test.dart +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/aspect_ratio_strategy.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'aspect_ratio_strategy_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([ - TestAspectRatioStrategyHostApi, - TestInstanceManagerHostApi, -]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - group('AspectRatioStrategy', () { - tearDown(() { - TestAspectRatioStrategyHostApi.setup(null); - TestInstanceManagerHostApi.setup(null); - }); - - test( - 'detached create does not make call to create expected AspectRatioStrategy instance', - () async { - final MockTestAspectRatioStrategyHostApi mockApi = - MockTestAspectRatioStrategyHostApi(); - TestAspectRatioStrategyHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - const int preferredAspectRatio = 1; - - const int fallbackRule = 1; - - AspectRatioStrategy.detached( - preferredAspectRatio: preferredAspectRatio, - fallbackRule: fallbackRule, - instanceManager: instanceManager, - ); - - verifyNever(mockApi.create( - argThat(isA()), - preferredAspectRatio, - fallbackRule, - )); - }); - - test( - 'HostApi create makes call to create expected AspectRatioStrategy instance', - () { - final MockTestAspectRatioStrategyHostApi mockApi = - MockTestAspectRatioStrategyHostApi(); - TestAspectRatioStrategyHostApi.setup(mockApi); - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - const int preferredAspectRatio = 0; - - const int fallbackRule = 0; - - final AspectRatioStrategy instance = AspectRatioStrategy( - preferredAspectRatio: preferredAspectRatio, - fallbackRule: fallbackRule, - instanceManager: instanceManager, - ); - - verify(mockApi.create( - instanceManager.getIdentifier(instance), - preferredAspectRatio, - fallbackRule, - )); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/aspect_ratio_strategy_test.mocks.dart b/packages/camera/camera_android_camerax/test/aspect_ratio_strategy_test.mocks.dart deleted file mode 100644 index dc93715debae..000000000000 --- a/packages/camera/camera_android_camerax/test/aspect_ratio_strategy_test.mocks.dart +++ /dev/null @@ -1,68 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/aspect_ratio_strategy_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestAspectRatioStrategyHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestAspectRatioStrategyHostApi extends _i1.Mock - implements _i2.TestAspectRatioStrategyHostApi { - MockTestAspectRatioStrategyHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void create( - int? identifier, - int? preferredAspectRatio, - int? fallbackRule, - ) => - super.noSuchMethod( - Invocation.method( - #create, - [ - identifier, - preferredAspectRatio, - fallbackRule, - ], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} diff --git a/packages/camera/camera_android_camerax/test/camera2_camera_control_test.dart b/packages/camera/camera_android_camerax/test/camera2_camera_control_test.dart deleted file mode 100644 index 6ec783a727c2..000000000000 --- a/packages/camera/camera_android_camerax/test/camera2_camera_control_test.dart +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camera2_camera_control.dart'; -import 'package:camera_android_camerax/src/camera_control.dart'; -import 'package:camera_android_camerax/src/capture_request_options.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'camera2_camera_control_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([ - CameraControl, - CaptureRequestOptions, - TestCamera2CameraControlHostApi, - TestInstanceManagerHostApi -]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('Camera2CameraControl', () { - tearDown(() { - TestCamera2CameraControlHostApi.setup(null); - TestInstanceManagerHostApi.setup(null); - }); - - test('detached create does not call create on the Java side', () { - final MockTestCamera2CameraControlHostApi mockApi = - MockTestCamera2CameraControlHostApi(); - TestCamera2CameraControlHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - Camera2CameraControl.detached( - cameraControl: MockCameraControl(), - instanceManager: instanceManager, - ); - - verifyNever(mockApi.create(argThat(isA()), argThat(isA()))); - }); - - test('create calls create on the Java side', () { - final MockTestCamera2CameraControlHostApi mockApi = - MockTestCamera2CameraControlHostApi(); - TestCamera2CameraControlHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final CameraControl mockCameraControl = MockCameraControl(); - const int cameraControlIdentifier = 9; - instanceManager.addHostCreatedInstance( - mockCameraControl, - cameraControlIdentifier, - onCopy: (_) => CameraControl.detached( - instanceManager: instanceManager, - ), - ); - - final Camera2CameraControl instance = Camera2CameraControl( - cameraControl: mockCameraControl, - instanceManager: instanceManager, - ); - - verify(mockApi.create( - instanceManager.getIdentifier(instance), - cameraControlIdentifier, - )); - }); - - test( - 'addCaptureRequestOptions makes call on Java side to add capture request options', - () async { - final MockTestCamera2CameraControlHostApi mockApi = - MockTestCamera2CameraControlHostApi(); - TestCamera2CameraControlHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final Camera2CameraControl instance = Camera2CameraControl.detached( - cameraControl: MockCameraControl(), - instanceManager: instanceManager, - ); - const int instanceIdentifier = 30; - instanceManager.addHostCreatedInstance( - instance, - instanceIdentifier, - onCopy: (Camera2CameraControl original) => - Camera2CameraControl.detached( - cameraControl: original.cameraControl, - instanceManager: instanceManager, - ), - ); - - final CaptureRequestOptions mockCaptureRequestOptions = - MockCaptureRequestOptions(); - const int mockCaptureRequestOptionsIdentifier = 8; - instanceManager.addHostCreatedInstance( - mockCaptureRequestOptions, - mockCaptureRequestOptionsIdentifier, - onCopy: (_) => MockCaptureRequestOptions(), - ); - - await instance.addCaptureRequestOptions( - mockCaptureRequestOptions, - ); - - verify(mockApi.addCaptureRequestOptions( - instanceIdentifier, - mockCaptureRequestOptionsIdentifier, - )); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/camera2_camera_control_test.mocks.dart b/packages/camera/camera_android_camerax/test/camera2_camera_control_test.mocks.dart deleted file mode 100644 index 58d89c49b20a..000000000000 --- a/packages/camera/camera_android_camerax/test/camera2_camera_control_test.mocks.dart +++ /dev/null @@ -1,169 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/camera2_camera_control_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i3; - -import 'package:camera_android_camerax/src/camera_control.dart' as _i2; -import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i7; -import 'package:camera_android_camerax/src/capture_request_options.dart' as _i6; -import 'package:camera_android_camerax/src/focus_metering_action.dart' as _i5; -import 'package:camera_android_camerax/src/focus_metering_result.dart' as _i4; -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i8; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [CameraControl]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockCameraControl extends _i1.Mock implements _i2.CameraControl { - MockCameraControl() { - _i1.throwOnMissingStub(this); - } - - @override - _i3.Future enableTorch(bool? torch) => (super.noSuchMethod( - Invocation.method( - #enableTorch, - [torch], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future setZoomRatio(double? ratio) => (super.noSuchMethod( - Invocation.method( - #setZoomRatio, - [ratio], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future<_i4.FocusMeteringResult?> startFocusAndMetering( - _i5.FocusMeteringAction? action) => - (super.noSuchMethod( - Invocation.method( - #startFocusAndMetering, - [action], - ), - returnValue: _i3.Future<_i4.FocusMeteringResult?>.value(), - ) as _i3.Future<_i4.FocusMeteringResult?>); - - @override - _i3.Future cancelFocusAndMetering() => (super.noSuchMethod( - Invocation.method( - #cancelFocusAndMetering, - [], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future setExposureCompensationIndex(int? index) => - (super.noSuchMethod( - Invocation.method( - #setExposureCompensationIndex, - [index], - ), - returnValue: _i3.Future.value(), - ) as _i3.Future); -} - -/// A class which mocks [CaptureRequestOptions]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockCaptureRequestOptions extends _i1.Mock - implements _i6.CaptureRequestOptions { - MockCaptureRequestOptions() { - _i1.throwOnMissingStub(this); - } - - @override - List<(_i7.CaptureRequestKeySupportedType, Object?)> get requestedOptions => - (super.noSuchMethod( - Invocation.getter(#requestedOptions), - returnValue: <(_i7.CaptureRequestKeySupportedType, Object?)>[], - ) as List<(_i7.CaptureRequestKeySupportedType, Object?)>); -} - -/// A class which mocks [TestCamera2CameraControlHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestCamera2CameraControlHostApi extends _i1.Mock - implements _i8.TestCamera2CameraControlHostApi { - MockTestCamera2CameraControlHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void create( - int? identifier, - int? cameraControlIdentifier, - ) => - super.noSuchMethod( - Invocation.method( - #create, - [ - identifier, - cameraControlIdentifier, - ], - ), - returnValueForMissingStub: null, - ); - - @override - _i3.Future addCaptureRequestOptions( - int? identifier, - int? captureRequestOptionsIdentifier, - ) => - (super.noSuchMethod( - Invocation.method( - #addCaptureRequestOptions, - [ - identifier, - captureRequestOptionsIdentifier, - ], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i8.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} diff --git a/packages/camera/camera_android_camerax/test/camera2_camera_info_test.dart b/packages/camera/camera_android_camerax/test/camera2_camera_info_test.dart deleted file mode 100644 index 0766eee37e83..000000000000 --- a/packages/camera/camera_android_camerax/test/camera2_camera_info_test.dart +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camera2_camera_info.dart'; -import 'package:camera_android_camerax/src/camera_info.dart'; -import 'package:camera_android_camerax/src/camera_metadata.dart'; -import 'package:camera_android_camerax/src/camerax_library.g.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'camera2_camera_info_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([ - TestCamera2CameraInfoHostApi, - TestInstanceManagerHostApi, - CameraInfo -]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('Camera2CameraInfo', () { - tearDown(() => TestCamera2CameraInfoHostApi.setup(null)); - - test('from returns expected Camera2CameraInfo instance', () async { - final MockTestCamera2CameraInfoHostApi mockApi = - MockTestCamera2CameraInfoHostApi(); - TestCamera2CameraInfoHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final Camera2CameraInfo camera2CameraInfo = Camera2CameraInfo.detached( - instanceManager: instanceManager, - ); - final CameraInfo mockCameraInfo = MockCameraInfo(); - const int camera2CameraInfoId = 33; - const int mockCameraInfoId = 44; - - instanceManager.addHostCreatedInstance( - camera2CameraInfo, - camera2CameraInfoId, - onCopy: (_) => Camera2CameraInfo.detached(), - ); - instanceManager.addHostCreatedInstance( - mockCameraInfo, - mockCameraInfoId, - onCopy: (_) => CameraInfo.detached(), - ); - - when(mockApi.createFrom(mockCameraInfoId)) - .thenAnswer((_) => camera2CameraInfoId); - expect( - await Camera2CameraInfo.from(mockCameraInfo, - instanceManager: instanceManager), - equals(camera2CameraInfo)); - verify(mockApi.createFrom(mockCameraInfoId)); - }); - - test('detached constructor does not create Camera2CameraInfo on Java side', - () async { - final MockTestCamera2CameraInfoHostApi mockApi = - MockTestCamera2CameraInfoHostApi(); - TestCamera2CameraInfoHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - Camera2CameraInfo.detached( - instanceManager: instanceManager, - ); - - verifyNever(mockApi.createFrom(argThat(isA()))); - }); - - test( - 'getSupportedHardwareLevel makes call to retrieve supported hardware level', - () async { - final MockTestCamera2CameraInfoHostApi mockApi = - MockTestCamera2CameraInfoHostApi(); - TestCamera2CameraInfoHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final Camera2CameraInfo camera2CameraInfo = Camera2CameraInfo.detached( - instanceManager: instanceManager, - ); - const int camera2CameraInfoId = 9; - - instanceManager.addHostCreatedInstance( - camera2CameraInfo, - camera2CameraInfoId, - onCopy: (_) => Camera2CameraInfo.detached(), - ); - - const int expectedSupportedHardwareLevel = - CameraMetadata.infoSupportedHardwareLevelExternal; - when(mockApi.getSupportedHardwareLevel(camera2CameraInfoId)) - .thenReturn(expectedSupportedHardwareLevel); - expect(await camera2CameraInfo.getSupportedHardwareLevel(), - equals(expectedSupportedHardwareLevel)); - - verify(mockApi.getSupportedHardwareLevel(camera2CameraInfoId)); - }); - - test('getCameraId makes call to retrieve camera ID', () async { - final MockTestCamera2CameraInfoHostApi mockApi = - MockTestCamera2CameraInfoHostApi(); - TestCamera2CameraInfoHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final Camera2CameraInfo camera2CameraInfo = Camera2CameraInfo.detached( - instanceManager: instanceManager, - ); - const int camera2CameraInfoId = 19; - - instanceManager.addHostCreatedInstance( - camera2CameraInfo, - camera2CameraInfoId, - onCopy: (_) => Camera2CameraInfo.detached(), - ); - - const String expectedCameraId = 'testCameraId'; - when(mockApi.getCameraId(camera2CameraInfoId)) - .thenReturn(expectedCameraId); - expect(await camera2CameraInfo.getCameraId(), equals(expectedCameraId)); - - verify(mockApi.getCameraId(camera2CameraInfoId)); - }); - - test('flutterApi create makes call to create expected instance type', () { - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final Camera2CameraInfoFlutterApi flutterApi = - Camera2CameraInfoFlutterApiImpl( - instanceManager: instanceManager, - ); - - flutterApi.create(0); - - expect(instanceManager.getInstanceWithWeakReference(0), - isA()); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/camera2_camera_info_test.mocks.dart b/packages/camera/camera_android_camerax/test/camera2_camera_info_test.mocks.dart deleted file mode 100644 index 88b219f28cf1..000000000000 --- a/packages/camera/camera_android_camerax/test/camera2_camera_info_test.mocks.dart +++ /dev/null @@ -1,188 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/camera2_camera_info_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i7; - -import 'package:camera_android_camerax/src/camera_info.dart' as _i6; -import 'package:camera_android_camerax/src/camera_state.dart' as _i8; -import 'package:camera_android_camerax/src/exposure_state.dart' as _i3; -import 'package:camera_android_camerax/src/live_data.dart' as _i2; -import 'package:camera_android_camerax/src/zoom_state.dart' as _i9; -import 'package:mockito/mockito.dart' as _i1; -import 'package:mockito/src/dummies.dart' as _i5; - -import 'test_camerax_library.g.dart' as _i4; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -class _FakeLiveData_0 extends _i1.SmartFake - implements _i2.LiveData { - _FakeLiveData_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); -} - -class _FakeExposureState_1 extends _i1.SmartFake implements _i3.ExposureState { - _FakeExposureState_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); -} - -/// A class which mocks [TestCamera2CameraInfoHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestCamera2CameraInfoHostApi extends _i1.Mock - implements _i4.TestCamera2CameraInfoHostApi { - MockTestCamera2CameraInfoHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - int createFrom(int? cameraInfoIdentifier) => (super.noSuchMethod( - Invocation.method( - #createFrom, - [cameraInfoIdentifier], - ), - returnValue: 0, - ) as int); - - @override - int getSupportedHardwareLevel(int? identifier) => (super.noSuchMethod( - Invocation.method( - #getSupportedHardwareLevel, - [identifier], - ), - returnValue: 0, - ) as int); - - @override - String getCameraId(int? identifier) => (super.noSuchMethod( - Invocation.method( - #getCameraId, - [identifier], - ), - returnValue: _i5.dummyValue( - this, - Invocation.method( - #getCameraId, - [identifier], - ), - ), - ) as String); - - @override - int getSensorOrientation(int? identifier) => (super.noSuchMethod( - Invocation.method( - #getSensorOrientation, - [identifier], - ), - returnValue: 0, - ) as int); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i4.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [CameraInfo]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockCameraInfo extends _i1.Mock implements _i6.CameraInfo { - MockCameraInfo() { - _i1.throwOnMissingStub(this); - } - - @override - _i7.Future getSensorRotationDegrees() => (super.noSuchMethod( - Invocation.method( - #getSensorRotationDegrees, - [], - ), - returnValue: _i7.Future.value(0), - ) as _i7.Future); - - @override - _i7.Future<_i2.LiveData<_i8.CameraState>> getCameraState() => - (super.noSuchMethod( - Invocation.method( - #getCameraState, - [], - ), - returnValue: _i7.Future<_i2.LiveData<_i8.CameraState>>.value( - _FakeLiveData_0<_i8.CameraState>( - this, - Invocation.method( - #getCameraState, - [], - ), - )), - ) as _i7.Future<_i2.LiveData<_i8.CameraState>>); - - @override - _i7.Future<_i3.ExposureState> getExposureState() => (super.noSuchMethod( - Invocation.method( - #getExposureState, - [], - ), - returnValue: _i7.Future<_i3.ExposureState>.value(_FakeExposureState_1( - this, - Invocation.method( - #getExposureState, - [], - ), - )), - ) as _i7.Future<_i3.ExposureState>); - - @override - _i7.Future<_i2.LiveData<_i9.ZoomState>> getZoomState() => (super.noSuchMethod( - Invocation.method( - #getZoomState, - [], - ), - returnValue: _i7.Future<_i2.LiveData<_i9.ZoomState>>.value( - _FakeLiveData_0<_i9.ZoomState>( - this, - Invocation.method( - #getZoomState, - [], - ), - )), - ) as _i7.Future<_i2.LiveData<_i9.ZoomState>>); -} diff --git a/packages/camera/camera_android_camerax/test/camera_control_test.dart b/packages/camera/camera_android_camerax/test/camera_control_test.dart deleted file mode 100644 index 22ba8aaf2479..000000000000 --- a/packages/camera/camera_android_camerax/test/camera_control_test.dart +++ /dev/null @@ -1,306 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camera_control.dart'; -import 'package:camera_android_camerax/src/focus_metering_action.dart'; -import 'package:camera_android_camerax/src/focus_metering_result.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:flutter/services.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'camera_control_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([ - TestCameraControlHostApi, - TestInstanceManagerHostApi, - FocusMeteringAction -]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('CameraControl', () { - tearDown(() => TestCameraHostApi.setup(null)); - - test('enableTorch makes call on Java side to enable torch', () async { - final MockTestCameraControlHostApi mockApi = - MockTestCameraControlHostApi(); - TestCameraControlHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final CameraControl cameraControl = CameraControl.detached( - instanceManager: instanceManager, - ); - const int cameraControlIdentifier = 22; - - instanceManager.addHostCreatedInstance( - cameraControl, - cameraControlIdentifier, - onCopy: (_) => CameraControl.detached(instanceManager: instanceManager), - ); - - const bool enableTorch = true; - await cameraControl.enableTorch(enableTorch); - - verify(mockApi.enableTorch(cameraControlIdentifier, enableTorch)); - }); - - test('setZoomRatio makes call on Java side to set zoom ratio', () async { - final MockTestCameraControlHostApi mockApi = - MockTestCameraControlHostApi(); - TestCameraControlHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final CameraControl cameraControl = CameraControl.detached( - instanceManager: instanceManager, - ); - const int cameraControlIdentifier = 45; - - instanceManager.addHostCreatedInstance( - cameraControl, - cameraControlIdentifier, - onCopy: (_) => CameraControl.detached(instanceManager: instanceManager), - ); - - const double zoom = 0.2; - await cameraControl.setZoomRatio(zoom); - - verify(mockApi.setZoomRatio(cameraControlIdentifier, zoom)); - }); - - test( - 'startFocusAndMetering makes call on Java side to start focus and metering and returns expected result', - () async { - final MockTestCameraControlHostApi mockApi = - MockTestCameraControlHostApi(); - TestCameraControlHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final CameraControl cameraControl = CameraControl.detached( - instanceManager: instanceManager, - ); - const int cameraControlIdentifier = 75; - final FocusMeteringAction action = MockFocusMeteringAction(); - const int actionId = 5; - final FocusMeteringResult result = - FocusMeteringResult.detached(instanceManager: instanceManager); - const int resultId = 2; - - instanceManager.addHostCreatedInstance( - cameraControl, - cameraControlIdentifier, - onCopy: (_) => CameraControl.detached(instanceManager: instanceManager), - ); - instanceManager.addHostCreatedInstance( - action, - actionId, - onCopy: (_) => MockFocusMeteringAction(), - ); - instanceManager.addHostCreatedInstance( - result, - resultId, - onCopy: (_) => - FocusMeteringResult.detached(instanceManager: instanceManager), - ); - - when(mockApi.startFocusAndMetering(cameraControlIdentifier, actionId)) - .thenAnswer((_) => Future.value(resultId)); - - expect(await cameraControl.startFocusAndMetering(action), equals(result)); - verify(mockApi.startFocusAndMetering(cameraControlIdentifier, actionId)); - }); - - test('startFocusAndMetering returns null result if operation was canceled', - () async { - final MockTestCameraControlHostApi mockApi = - MockTestCameraControlHostApi(); - TestCameraControlHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final CameraControl cameraControl = CameraControl.detached( - instanceManager: instanceManager, - ); - const int cameraControlIdentifier = 75; - final FocusMeteringAction action = MockFocusMeteringAction(); - const int actionId = 5; - - instanceManager.addHostCreatedInstance( - cameraControl, - cameraControlIdentifier, - onCopy: (_) => CameraControl.detached(instanceManager: instanceManager), - ); - instanceManager.addHostCreatedInstance( - action, - actionId, - onCopy: (_) => MockFocusMeteringAction(), - ); - - when(mockApi.startFocusAndMetering(cameraControlIdentifier, actionId)) - .thenAnswer((_) => Future.value()); - - expect(await cameraControl.startFocusAndMetering(action), isNull); - verify(mockApi.startFocusAndMetering(cameraControlIdentifier, actionId)); - }); - - test( - 'cancelFocusAndMetering makes call on Java side to cancel focus and metering', - () async { - final MockTestCameraControlHostApi mockApi = - MockTestCameraControlHostApi(); - TestCameraControlHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final CameraControl cameraControl = CameraControl.detached( - instanceManager: instanceManager, - ); - const int cameraControlIdentifier = 45; - - instanceManager.addHostCreatedInstance( - cameraControl, - cameraControlIdentifier, - onCopy: (_) => CameraControl.detached(instanceManager: instanceManager), - ); - - await cameraControl.cancelFocusAndMetering(); - - verify(mockApi.cancelFocusAndMetering(cameraControlIdentifier)); - }); - - test( - 'setExposureCompensationIndex makes call on Java side to set index and returns expected target exposure value', - () async { - final MockTestCameraControlHostApi mockApi = - MockTestCameraControlHostApi(); - TestCameraControlHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final CameraControl cameraControl = CameraControl.detached( - instanceManager: instanceManager, - ); - const int cameraControlIdentifier = 40; - - instanceManager.addHostCreatedInstance( - cameraControl, - cameraControlIdentifier, - onCopy: (_) => CameraControl.detached(instanceManager: instanceManager), - ); - - const int index = 3; - const int fakeTargetExposureValue = 2; - when(mockApi.setExposureCompensationIndex(cameraControlIdentifier, index)) - .thenAnswer((_) => Future.value(fakeTargetExposureValue)); - - expect(await cameraControl.setExposureCompensationIndex(index), - equals(fakeTargetExposureValue)); - verify( - mockApi.setExposureCompensationIndex(cameraControlIdentifier, index)); - }); - - test( - 'setExposureCompensationIndex returns null when operation was canceled', - () async { - final MockTestCameraControlHostApi mockApi = - MockTestCameraControlHostApi(); - TestCameraControlHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final CameraControl cameraControl = CameraControl.detached( - instanceManager: instanceManager, - ); - const int cameraControlIdentifier = 40; - - instanceManager.addHostCreatedInstance( - cameraControl, - cameraControlIdentifier, - onCopy: (_) => CameraControl.detached(instanceManager: instanceManager), - ); - - const int index = 2; - when(mockApi.setExposureCompensationIndex(cameraControlIdentifier, index)) - .thenAnswer((_) => Future.value()); - - expect(await cameraControl.setExposureCompensationIndex(index), isNull); - verify( - mockApi.setExposureCompensationIndex(cameraControlIdentifier, index)); - }); - - test( - 'setExposureCompensationIndex throws PlatformException when one is thrown from native side', - () async { - final MockTestCameraControlHostApi mockApi = - MockTestCameraControlHostApi(); - TestCameraControlHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final CameraControl cameraControl = CameraControl.detached( - instanceManager: instanceManager, - ); - const int cameraControlIdentifier = 40; - - instanceManager.addHostCreatedInstance( - cameraControl, - cameraControlIdentifier, - onCopy: (_) => CameraControl.detached(instanceManager: instanceManager), - ); - - const int index = 1; - when(mockApi.setExposureCompensationIndex(cameraControlIdentifier, index)) - .thenThrow(PlatformException( - code: 'TEST_ERROR', - details: 'Platform exception thrown from Java side.')); - - expect(() => cameraControl.setExposureCompensationIndex(index), - throwsA(isA())); - - verify( - mockApi.setExposureCompensationIndex(cameraControlIdentifier, index)); - }); - - test('flutterApiCreate makes call to add instance to instance manager', () { - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final CameraControlFlutterApiImpl flutterApi = - CameraControlFlutterApiImpl( - instanceManager: instanceManager, - ); - const int cameraControlIdentifier = 67; - - flutterApi.create(cameraControlIdentifier); - - expect( - instanceManager.getInstanceWithWeakReference(cameraControlIdentifier), - isA()); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/camera_control_test.mocks.dart b/packages/camera/camera_android_camerax/test/camera_control_test.mocks.dart deleted file mode 100644 index 57040bcac62b..000000000000 --- a/packages/camera/camera_android_camerax/test/camera_control_test.mocks.dart +++ /dev/null @@ -1,148 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/camera_control_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i3; - -import 'package:camera_android_camerax/src/focus_metering_action.dart' as _i4; -import 'package:camera_android_camerax/src/metering_point.dart' as _i5; -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestCameraControlHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestCameraControlHostApi extends _i1.Mock - implements _i2.TestCameraControlHostApi { - MockTestCameraControlHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - _i3.Future enableTorch( - int? identifier, - bool? torch, - ) => - (super.noSuchMethod( - Invocation.method( - #enableTorch, - [ - identifier, - torch, - ], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future setZoomRatio( - int? identifier, - double? ratio, - ) => - (super.noSuchMethod( - Invocation.method( - #setZoomRatio, - [ - identifier, - ratio, - ], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future startFocusAndMetering( - int? identifier, - int? focusMeteringActionId, - ) => - (super.noSuchMethod( - Invocation.method( - #startFocusAndMetering, - [ - identifier, - focusMeteringActionId, - ], - ), - returnValue: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future cancelFocusAndMetering(int? identifier) => - (super.noSuchMethod( - Invocation.method( - #cancelFocusAndMetering, - [identifier], - ), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), - ) as _i3.Future); - - @override - _i3.Future setExposureCompensationIndex( - int? identifier, - int? index, - ) => - (super.noSuchMethod( - Invocation.method( - #setExposureCompensationIndex, - [ - identifier, - index, - ], - ), - returnValue: _i3.Future.value(), - ) as _i3.Future); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [FocusMeteringAction]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockFocusMeteringAction extends _i1.Mock - implements _i4.FocusMeteringAction { - MockFocusMeteringAction() { - _i1.throwOnMissingStub(this); - } - - @override - List<(_i5.MeteringPoint, int?)> get meteringPointInfos => (super.noSuchMethod( - Invocation.getter(#meteringPointInfos), - returnValue: <(_i5.MeteringPoint, int?)>[], - ) as List<(_i5.MeteringPoint, int?)>); -} diff --git a/packages/camera/camera_android_camerax/test/camera_info_test.dart b/packages/camera/camera_android_camerax/test/camera_info_test.dart deleted file mode 100644 index 487983b33656..000000000000 --- a/packages/camera/camera_android_camerax/test/camera_info_test.dart +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camera_info.dart'; -import 'package:camera_android_camerax/src/camera_state.dart'; -import 'package:camera_android_camerax/src/camerax_library.g.dart'; -import 'package:camera_android_camerax/src/exposure_state.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:camera_android_camerax/src/live_data.dart'; -import 'package:camera_android_camerax/src/zoom_state.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'camera_info_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([ - TestCameraInfoHostApi, - TestInstanceManagerHostApi -], customMocks: >[ - MockSpec>(as: #MockLiveCameraState), - MockSpec>(as: #MockLiveZoomState), -]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('CameraInfo', () { - tearDown(() => TestCameraInfoHostApi.setup(null)); - - test( - 'getSensorRotationDegrees makes call to retrieve expected sensor rotation', - () async { - final MockTestCameraInfoHostApi mockApi = MockTestCameraInfoHostApi(); - TestCameraInfoHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final CameraInfo cameraInfo = CameraInfo.detached( - instanceManager: instanceManager, - ); - instanceManager.addHostCreatedInstance( - cameraInfo, - 0, - onCopy: (_) => CameraInfo.detached(), - ); - - when(mockApi.getSensorRotationDegrees( - instanceManager.getIdentifier(cameraInfo))) - .thenReturn(90); - expect(await cameraInfo.getSensorRotationDegrees(), equals(90)); - - verify(mockApi.getSensorRotationDegrees(0)); - }); - - test('getCameraState makes call to retrieve live camera state', () async { - final MockTestCameraInfoHostApi mockApi = MockTestCameraInfoHostApi(); - TestCameraInfoHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final CameraInfo cameraInfo = CameraInfo.detached( - instanceManager: instanceManager, - ); - const int cameraIdentifier = 55; - final MockLiveCameraState mockLiveCameraState = MockLiveCameraState(); - const int liveCameraStateIdentifier = 73; - instanceManager.addHostCreatedInstance( - cameraInfo, - cameraIdentifier, - onCopy: (_) => CameraInfo.detached(), - ); - instanceManager.addHostCreatedInstance( - mockLiveCameraState, - liveCameraStateIdentifier, - onCopy: (_) => MockLiveCameraState(), - ); - - when(mockApi.getCameraState(cameraIdentifier)) - .thenReturn(liveCameraStateIdentifier); - - expect(await cameraInfo.getCameraState(), equals(mockLiveCameraState)); - verify(mockApi.getCameraState(cameraIdentifier)); - }); - - test('getExposureState makes call to retrieve expected ExposureState', - () async { - final MockTestCameraInfoHostApi mockApi = MockTestCameraInfoHostApi(); - TestCameraInfoHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final CameraInfo cameraInfo = CameraInfo.detached( - instanceManager: instanceManager, - ); - const int cameraInfoIdentifier = 4; - final ExposureState exposureState = ExposureState.detached( - exposureCompensationRange: - ExposureCompensationRange(maxCompensation: 0, minCompensation: 1), - exposureCompensationStep: 4, - instanceManager: instanceManager, - ); - const int exposureStateIdentifier = 45; - - instanceManager.addHostCreatedInstance( - cameraInfo, - cameraInfoIdentifier, - onCopy: (_) => CameraInfo.detached(), - ); - instanceManager.addHostCreatedInstance( - exposureState, - exposureStateIdentifier, - onCopy: (_) => ExposureState.detached( - exposureCompensationRange: ExposureCompensationRange( - maxCompensation: 0, minCompensation: 1), - exposureCompensationStep: 4), - ); - - when(mockApi.getExposureState(cameraInfoIdentifier)) - .thenReturn(exposureStateIdentifier); - expect(await cameraInfo.getExposureState(), equals(exposureState)); - - verify(mockApi.getExposureState(cameraInfoIdentifier)); - }); - - test('getZoomState makes call to retrieve expected ZoomState', () async { - final MockTestCameraInfoHostApi mockApi = MockTestCameraInfoHostApi(); - TestCameraInfoHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final CameraInfo cameraInfo = CameraInfo.detached( - instanceManager: instanceManager, - ); - const int cameraInfoIdentifier = 2; - final MockLiveZoomState mockLiveZoomState = MockLiveZoomState(); - const int mockLiveZoomStateIdentifier = 55; - - instanceManager.addHostCreatedInstance( - cameraInfo, - cameraInfoIdentifier, - onCopy: (_) => CameraInfo.detached(), - ); - instanceManager.addHostCreatedInstance( - mockLiveZoomState, mockLiveZoomStateIdentifier, - onCopy: (_) => MockLiveZoomState()); - - when(mockApi.getZoomState(cameraInfoIdentifier)) - .thenReturn(mockLiveZoomStateIdentifier); - expect(await cameraInfo.getZoomState(), equals(mockLiveZoomState)); - - verify(mockApi.getZoomState(cameraInfoIdentifier)); - }); - - test('flutterApi create makes call to create expected instance type', () { - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final CameraInfoFlutterApi flutterApi = CameraInfoFlutterApiImpl( - instanceManager: instanceManager, - ); - - flutterApi.create(0); - - expect( - instanceManager.getInstanceWithWeakReference(0), isA()); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/camera_info_test.mocks.dart b/packages/camera/camera_android_camerax/test/camera_info_test.mocks.dart deleted file mode 100644 index 6699d63e6885..000000000000 --- a/packages/camera/camera_android_camerax/test/camera_info_test.mocks.dart +++ /dev/null @@ -1,156 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/camera_info_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i5; - -import 'package:camera_android_camerax/src/camera_state.dart' as _i4; -import 'package:camera_android_camerax/src/live_data.dart' as _i3; -import 'package:camera_android_camerax/src/observer.dart' as _i6; -import 'package:camera_android_camerax/src/zoom_state.dart' as _i7; -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestCameraInfoHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestCameraInfoHostApi extends _i1.Mock - implements _i2.TestCameraInfoHostApi { - MockTestCameraInfoHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - int getSensorRotationDegrees(int? identifier) => (super.noSuchMethod( - Invocation.method( - #getSensorRotationDegrees, - [identifier], - ), - returnValue: 0, - ) as int); - - @override - int getCameraState(int? identifier) => (super.noSuchMethod( - Invocation.method( - #getCameraState, - [identifier], - ), - returnValue: 0, - ) as int); - - @override - int getExposureState(int? identifier) => (super.noSuchMethod( - Invocation.method( - #getExposureState, - [identifier], - ), - returnValue: 0, - ) as int); - - @override - int getZoomState(int? identifier) => (super.noSuchMethod( - Invocation.method( - #getZoomState, - [identifier], - ), - returnValue: 0, - ) as int); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [LiveData]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockLiveCameraState extends _i1.Mock - implements _i3.LiveData<_i4.CameraState> { - MockLiveCameraState() { - _i1.throwOnMissingStub(this); - } - - @override - _i5.Future observe(_i6.Observer<_i4.CameraState>? observer) => - (super.noSuchMethod( - Invocation.method( - #observe, - [observer], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future removeObservers() => (super.noSuchMethod( - Invocation.method( - #removeObservers, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); -} - -/// A class which mocks [LiveData]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockLiveZoomState extends _i1.Mock - implements _i3.LiveData<_i7.ZoomState> { - MockLiveZoomState() { - _i1.throwOnMissingStub(this); - } - - @override - _i5.Future observe(_i6.Observer<_i7.ZoomState>? observer) => - (super.noSuchMethod( - Invocation.method( - #observe, - [observer], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); - - @override - _i5.Future removeObservers() => (super.noSuchMethod( - Invocation.method( - #removeObservers, - [], - ), - returnValue: _i5.Future.value(), - returnValueForMissingStub: _i5.Future.value(), - ) as _i5.Future); -} diff --git a/packages/camera/camera_android_camerax/test/camera_selector_test.dart b/packages/camera/camera_android_camerax/test/camera_selector_test.dart deleted file mode 100644 index b5abd136c31c..000000000000 --- a/packages/camera/camera_android_camerax/test/camera_selector_test.dart +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camera_info.dart'; -import 'package:camera_android_camerax/src/camera_selector.dart'; -import 'package:camera_android_camerax/src/camerax_library.g.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'camera_selector_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([TestCameraSelectorHostApi, TestInstanceManagerHostApi]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('CameraSelector', () { - tearDown(() => TestCameraSelectorHostApi.setup(null)); - - test('detachedCreateTest', () async { - final MockTestCameraSelectorHostApi mockApi = - MockTestCameraSelectorHostApi(); - TestCameraSelectorHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - CameraSelector.detached( - instanceManager: instanceManager, - ); - - verifyNever(mockApi.create(argThat(isA()), null)); - }); - - test('createTestWithoutLensSpecified', () async { - final MockTestCameraSelectorHostApi mockApi = - MockTestCameraSelectorHostApi(); - TestCameraSelectorHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - CameraSelector( - instanceManager: instanceManager, - ); - - verify(mockApi.create(argThat(isA()), null)); - }); - - test('createTestWithLensSpecified', () async { - final MockTestCameraSelectorHostApi mockApi = - MockTestCameraSelectorHostApi(); - TestCameraSelectorHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - CameraSelector( - instanceManager: instanceManager, - lensFacing: CameraSelector.lensFacingBack); - - verify( - mockApi.create(argThat(isA()), CameraSelector.lensFacingBack)); - }); - - test('filterTest', () async { - final MockTestCameraSelectorHostApi mockApi = - MockTestCameraSelectorHostApi(); - TestCameraSelectorHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final CameraSelector cameraSelector = CameraSelector.detached( - instanceManager: instanceManager, - ); - const int cameraInfoId = 3; - final CameraInfo cameraInfo = - CameraInfo.detached(instanceManager: instanceManager); - - instanceManager.addHostCreatedInstance( - cameraSelector, - 0, - onCopy: (_) => CameraSelector.detached(), - ); - instanceManager.addHostCreatedInstance( - cameraInfo, - cameraInfoId, - onCopy: (_) => CameraInfo.detached(), - ); - - when(mockApi.filter(instanceManager.getIdentifier(cameraSelector), - [cameraInfoId])).thenReturn([cameraInfoId]); - expect(await cameraSelector.filter([cameraInfo]), - equals([cameraInfo])); - - verify(mockApi.filter(0, [cameraInfoId])); - }); - - test('flutterApiCreateTest', () { - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final CameraSelectorFlutterApi flutterApi = CameraSelectorFlutterApiImpl( - instanceManager: instanceManager, - ); - - flutterApi.create(0, CameraSelector.lensFacingBack); - - expect(instanceManager.getInstanceWithWeakReference(0), - isA()); - expect( - (instanceManager.getInstanceWithWeakReference(0)! as CameraSelector) - .lensFacing, - equals(CameraSelector.lensFacingBack)); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/camera_selector_test.mocks.dart b/packages/camera/camera_android_camerax/test/camera_selector_test.mocks.dart deleted file mode 100644 index 70d0eec28f33..000000000000 --- a/packages/camera/camera_android_camerax/test/camera_selector_test.mocks.dart +++ /dev/null @@ -1,82 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/camera_selector_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestCameraSelectorHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestCameraSelectorHostApi extends _i1.Mock - implements _i2.TestCameraSelectorHostApi { - MockTestCameraSelectorHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void create( - int? identifier, - int? lensFacing, - ) => - super.noSuchMethod( - Invocation.method( - #create, - [ - identifier, - lensFacing, - ], - ), - returnValueForMissingStub: null, - ); - - @override - List filter( - int? identifier, - List? cameraInfoIds, - ) => - (super.noSuchMethod( - Invocation.method( - #filter, - [ - identifier, - cameraInfoIds, - ], - ), - returnValue: [], - ) as List); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} diff --git a/packages/camera/camera_android_camerax/test/camera_state_error_test.dart b/packages/camera/camera_android_camerax/test/camera_state_error_test.dart deleted file mode 100644 index c78bca10cae0..000000000000 --- a/packages/camera/camera_android_camerax/test/camera_state_error_test.dart +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camera_state_error.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; - -import 'camera_state_error_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([TestInstanceManagerHostApi]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('CameraStateError', () { - test( - 'FlutterAPI create makes call to create CameraStateError instance with expected identifier', - () { - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final CameraStateErrorFlutterApiImpl api = CameraStateErrorFlutterApiImpl( - instanceManager: instanceManager, - ); - - const int instanceIdentifier = 0; - const int code = 23; - - api.create( - instanceIdentifier, - code, - ); - - // Test instance type. - final Object? instance = - instanceManager.getInstanceWithWeakReference(instanceIdentifier); - expect( - instance, - isA(), - ); - - // Test instance properties. - final CameraStateError cameraStateError = instance! as CameraStateError; - expect(cameraStateError.code, equals(code)); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/camera_state_error_test.mocks.dart b/packages/camera/camera_android_camerax/test/camera_state_error_test.mocks.dart deleted file mode 100644 index 941d5ffd74ad..000000000000 --- a/packages/camera/camera_android_camerax/test/camera_state_error_test.mocks.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/camera_state_error_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} diff --git a/packages/camera/camera_android_camerax/test/camera_state_test.dart b/packages/camera/camera_android_camerax/test/camera_state_test.dart deleted file mode 100644 index 644d4555e3c8..000000000000 --- a/packages/camera/camera_android_camerax/test/camera_state_test.dart +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camera_state.dart'; -import 'package:camera_android_camerax/src/camera_state_error.dart'; -import 'package:camera_android_camerax/src/camerax_library.g.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; - -import 'camera_state_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([TestInstanceManagerHostApi]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('CameraState', () { - test( - 'FlutterAPI create makes call to create CameraState instance with expected identifier', - () { - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final CameraStateFlutterApiImpl api = CameraStateFlutterApiImpl( - instanceManager: instanceManager, - ); - - // Create CameraStateError for CameraState instance. - const int code = 23; - final CameraStateError cameraStateError = CameraStateError.detached( - instanceManager: instanceManager, - code: code, - ); - final int cameraStateErrorIdentifier = - instanceManager.addDartCreatedInstance(cameraStateError, onCopy: (_) { - return CameraStateError.detached(code: code); - }); - - // Create CameraState. - const int instanceIdentifier = 46; - const CameraStateType cameraStateType = CameraStateType.closed; - api.create( - instanceIdentifier, - CameraStateTypeData(value: cameraStateType), - cameraStateErrorIdentifier, - ); - - // Test instance type. - final Object? instance = - instanceManager.getInstanceWithWeakReference(instanceIdentifier); - expect( - instanceManager.getInstanceWithWeakReference(instanceIdentifier), - isA(), - ); - - // Test instance properties. - final CameraState cameraState = instance! as CameraState; - expect(cameraState.type, equals(cameraStateType)); - expect(cameraState.error, equals(cameraStateError)); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/camera_state_test.mocks.dart b/packages/camera/camera_android_camerax/test/camera_state_test.mocks.dart deleted file mode 100644 index 78223999a16f..000000000000 --- a/packages/camera/camera_android_camerax/test/camera_state_test.mocks.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/camera_state_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} diff --git a/packages/camera/camera_android_camerax/test/camera_test.dart b/packages/camera/camera_android_camerax/test/camera_test.dart deleted file mode 100644 index 22d9dabd40d3..000000000000 --- a/packages/camera/camera_android_camerax/test/camera_test.dart +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camera.dart'; -import 'package:camera_android_camerax/src/camera_control.dart'; -import 'package:camera_android_camerax/src/camera_info.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'camera_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([TestCameraHostApi, TestInstanceManagerHostApi]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('Camera', () { - tearDown(() => TestCameraHostApi.setup(null)); - - test('getCameraInfo makes call to retrieve expected CameraInfo', () async { - final MockTestCameraHostApi mockApi = MockTestCameraHostApi(); - TestCameraHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final Camera camera = Camera.detached( - instanceManager: instanceManager, - ); - const int cameraIdentifier = 24; - final CameraInfo cameraInfo = CameraInfo.detached(); - const int cameraInfoIdentifier = 88; - instanceManager.addHostCreatedInstance( - camera, - cameraIdentifier, - onCopy: (_) => Camera.detached(instanceManager: instanceManager), - ); - instanceManager.addHostCreatedInstance( - cameraInfo, - cameraInfoIdentifier, - onCopy: (_) => CameraInfo.detached(instanceManager: instanceManager), - ); - - when(mockApi.getCameraInfo(cameraIdentifier)) - .thenAnswer((_) => cameraInfoIdentifier); - - expect(await camera.getCameraInfo(), equals(cameraInfo)); - verify(mockApi.getCameraInfo(cameraIdentifier)); - }); - - test('getCameraControl makes call to retrieve expected CameraControl', - () async { - final MockTestCameraHostApi mockApi = MockTestCameraHostApi(); - TestCameraHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final Camera camera = Camera.detached( - instanceManager: instanceManager, - ); - const int cameraIdentifier = 42; - final CameraControl cameraControl = CameraControl.detached(); - const int cameraControlIdentifier = 8; - instanceManager.addHostCreatedInstance( - camera, - cameraIdentifier, - onCopy: (_) => Camera.detached(instanceManager: instanceManager), - ); - instanceManager.addHostCreatedInstance( - cameraControl, - cameraControlIdentifier, - onCopy: (_) => CameraControl.detached(instanceManager: instanceManager), - ); - - when(mockApi.getCameraControl(cameraIdentifier)) - .thenAnswer((_) => cameraControlIdentifier); - - expect(await camera.getCameraControl(), equals(cameraControl)); - verify(mockApi.getCameraControl(cameraIdentifier)); - }); - - test('flutterApiCreate makes call to add instance to instance manager', () { - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final CameraFlutterApiImpl flutterApi = CameraFlutterApiImpl( - instanceManager: instanceManager, - ); - - flutterApi.create(0); - - expect(instanceManager.getInstanceWithWeakReference(0), isA()); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/camera_test.mocks.dart b/packages/camera/camera_android_camerax/test/camera_test.mocks.dart deleted file mode 100644 index f1de6b978106..000000000000 --- a/packages/camera/camera_android_camerax/test/camera_test.mocks.dart +++ /dev/null @@ -1,67 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/camera_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestCameraHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestCameraHostApi extends _i1.Mock implements _i2.TestCameraHostApi { - MockTestCameraHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - int getCameraInfo(int? identifier) => (super.noSuchMethod( - Invocation.method( - #getCameraInfo, - [identifier], - ), - returnValue: 0, - ) as int); - - @override - int getCameraControl(int? identifier) => (super.noSuchMethod( - Invocation.method( - #getCameraControl, - [identifier], - ), - returnValue: 0, - ) as int); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} diff --git a/packages/camera/camera_android_camerax/test/capture_request_options_test.dart b/packages/camera/camera_android_camerax/test/capture_request_options_test.dart deleted file mode 100644 index c048aae22977..000000000000 --- a/packages/camera/camera_android_camerax/test/capture_request_options_test.dart +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camerax_library.g.dart'; -import 'package:camera_android_camerax/src/capture_request_options.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'capture_request_options_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks( - [TestCaptureRequestOptionsHostApi, TestInstanceManagerHostApi]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('CaptureRequestOptions', () { - tearDown(() { - TestCaptureRequestOptionsHostApi.setup(null); - TestInstanceManagerHostApi.setup(null); - }); - - test('detached create does not make call on the Java side', () { - final MockTestCaptureRequestOptionsHostApi mockApi = - MockTestCaptureRequestOptionsHostApi(); - TestCaptureRequestOptionsHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final List<(CaptureRequestKeySupportedType, Object?)> options = - <(CaptureRequestKeySupportedType, Object?)>[ - (CaptureRequestKeySupportedType.controlAeLock, true), - ]; - - CaptureRequestOptions.detached( - requestedOptions: options, - instanceManager: instanceManager, - ); - - verifyNever(mockApi.create( - argThat(isA()), - argThat(isA>()), - )); - }, skip: 'Flaky test: https://github.com/flutter/flutter/issues/164132'); - - test( - 'create makes call on the Java side as expected for suppported null capture request options', - () { - final MockTestCaptureRequestOptionsHostApi mockApi = - MockTestCaptureRequestOptionsHostApi(); - TestCaptureRequestOptionsHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final List<(CaptureRequestKeySupportedType key, Object? value)> - supportedOptionsForTesting = <( - CaptureRequestKeySupportedType key, - Object? value - )>[(CaptureRequestKeySupportedType.controlAeLock, null)]; - - final CaptureRequestOptions instance = CaptureRequestOptions( - requestedOptions: supportedOptionsForTesting, - instanceManager: instanceManager, - ); - - final VerificationResult verificationResult = verify(mockApi.create( - instanceManager.getIdentifier(instance), - captureAny, - )); - final Map captureRequestOptions = - verificationResult.captured.single as Map; - - expect(captureRequestOptions.length, - equals(supportedOptionsForTesting.length)); - for (final (CaptureRequestKeySupportedType key, Object? value) option - in supportedOptionsForTesting) { - final CaptureRequestKeySupportedType optionKey = option.$1; - expect(captureRequestOptions[optionKey.index], isNull); - } - }); - - test( - 'create makes call on the Java side as expected for suppported non-null capture request options', - () { - final MockTestCaptureRequestOptionsHostApi mockApi = - MockTestCaptureRequestOptionsHostApi(); - TestCaptureRequestOptionsHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final List<(CaptureRequestKeySupportedType key, Object? value)> - supportedOptionsForTesting = <( - CaptureRequestKeySupportedType key, - Object? value - )>[(CaptureRequestKeySupportedType.controlAeLock, false)]; - - final CaptureRequestOptions instance = CaptureRequestOptions( - requestedOptions: supportedOptionsForTesting, - instanceManager: instanceManager, - ); - - final VerificationResult verificationResult = verify(mockApi.create( - instanceManager.getIdentifier(instance), - captureAny, - )); - final Map? captureRequestOptions = - verificationResult.captured.single as Map?; - - expect(captureRequestOptions!.length, - equals(supportedOptionsForTesting.length)); - for (final (CaptureRequestKeySupportedType key, Object? value) option - in supportedOptionsForTesting) { - final CaptureRequestKeySupportedType optionKey = option.$1; - final Object? optionValue = option.$2; - - switch (optionKey) { - case CaptureRequestKeySupportedType.controlAeLock: - expect(captureRequestOptions[optionKey.index], - equals(optionValue! as bool)); - // This ignore statement is safe beause this will test when - // a new CaptureRequestKeySupportedType is being added, but the logic in - // in the CaptureRequestOptions class has not yet been updated. - // ignore: no_default_cases, unreachable_switch_default - default: - fail( - 'Option $option contains unrecognized CaptureRequestKeySupportedType key ${option.$1}'); - } - } - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/capture_request_options_test.mocks.dart b/packages/camera/camera_android_camerax/test/capture_request_options_test.mocks.dart deleted file mode 100644 index da704f37cb99..000000000000 --- a/packages/camera/camera_android_camerax/test/capture_request_options_test.mocks.dart +++ /dev/null @@ -1,66 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/capture_request_options_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestCaptureRequestOptionsHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestCaptureRequestOptionsHostApi extends _i1.Mock - implements _i2.TestCaptureRequestOptionsHostApi { - MockTestCaptureRequestOptionsHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void create( - int? identifier, - Map? options, - ) => - super.noSuchMethod( - Invocation.method( - #create, - [ - identifier, - options, - ], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} diff --git a/packages/camera/camera_android_camerax/test/device_orientation_manager_test.dart b/packages/camera/camera_android_camerax/test/device_orientation_manager_test.dart deleted file mode 100644 index 2555302f4092..000000000000 --- a/packages/camera/camera_android_camerax/test/device_orientation_manager_test.dart +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/device_orientation_manager.dart'; -import 'package:camera_android_camerax/src/surface.dart'; -import 'package:camera_platform_interface/camera_platform_interface.dart' - show DeviceOrientationChangedEvent; -import 'package:flutter/services.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'device_orientation_manager_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks( - [TestInstanceManagerHostApi, TestDeviceOrientationManagerHostApi]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('DeviceOrientationManager', () { - tearDown(() => TestProcessCameraProviderHostApi.setup(null)); - - test( - 'startListeningForDeviceOrientationChange makes request to start listening for new device orientations', - () async { - final MockTestDeviceOrientationManagerHostApi mockApi = - MockTestDeviceOrientationManagerHostApi(); - TestDeviceOrientationManagerHostApi.setup(mockApi); - - DeviceOrientationManager.startListeningForDeviceOrientationChange( - true, 90); - verify(mockApi.startListeningForDeviceOrientationChange(true, 90)); - }); - - test( - 'stopListeningForDeviceOrientationChange makes request to stop listening for new device orientations', - () async { - final MockTestDeviceOrientationManagerHostApi mockApi = - MockTestDeviceOrientationManagerHostApi(); - TestDeviceOrientationManagerHostApi.setup(mockApi); - - DeviceOrientationManager.stopListeningForDeviceOrientationChange(); - verify(mockApi.stopListeningForDeviceOrientationChange()); - }); - - test('getDefaultDisplayRotation retrieves expected rotation', () async { - final MockTestDeviceOrientationManagerHostApi mockApi = - MockTestDeviceOrientationManagerHostApi(); - TestDeviceOrientationManagerHostApi.setup(mockApi); - const int expectedRotation = Surface.rotation180; - - when(mockApi.getDefaultDisplayRotation()).thenReturn(expectedRotation); - - expect(await DeviceOrientationManager.getDefaultDisplayRotation(), - equals(expectedRotation)); - verify(mockApi.getDefaultDisplayRotation()); - }); - - test('getUiOrientation returns expected orientation', () async { - final MockTestDeviceOrientationManagerHostApi mockApi = - MockTestDeviceOrientationManagerHostApi(); - TestDeviceOrientationManagerHostApi.setup(mockApi); - const DeviceOrientation expectedOrientation = - DeviceOrientation.landscapeRight; - - when(mockApi.getUiOrientation()).thenReturn('LANDSCAPE_RIGHT'); - - expect(await DeviceOrientationManager.getUiOrientation(), - equals(expectedOrientation)); - verify(mockApi.getUiOrientation()); - }); - - test('onDeviceOrientationChanged adds new orientation to stream', () { - DeviceOrientationManager.deviceOrientationChangedStreamController.stream - .listen((DeviceOrientationChangedEvent event) { - expect(event.orientation, equals(DeviceOrientation.landscapeLeft)); - }); - DeviceOrientationManagerFlutterApiImpl() - .onDeviceOrientationChanged('LANDSCAPE_LEFT'); - }); - - test( - 'onDeviceOrientationChanged throws error if new orientation is invalid', - () { - expect( - () => DeviceOrientationManagerFlutterApiImpl() - .onDeviceOrientationChanged('FAKE_ORIENTATION'), - throwsA(isA().having( - (ArgumentError e) => e.message, - 'message', - '"FAKE_ORIENTATION" is not a valid DeviceOrientation value'))); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/device_orientation_manager_test.mocks.dart b/packages/camera/camera_android_camerax/test/device_orientation_manager_test.mocks.dart deleted file mode 100644 index 9d166bc39e19..000000000000 --- a/packages/camera/camera_android_camerax/test/device_orientation_manager_test.mocks.dart +++ /dev/null @@ -1,100 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/device_orientation_manager_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:mockito/mockito.dart' as _i1; -import 'package:mockito/src/dummies.dart' as _i3; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [TestDeviceOrientationManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestDeviceOrientationManagerHostApi extends _i1.Mock - implements _i2.TestDeviceOrientationManagerHostApi { - MockTestDeviceOrientationManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void startListeningForDeviceOrientationChange( - bool? isFrontFacing, - int? sensorOrientation, - ) => - super.noSuchMethod( - Invocation.method( - #startListeningForDeviceOrientationChange, - [ - isFrontFacing, - sensorOrientation, - ], - ), - returnValueForMissingStub: null, - ); - - @override - void stopListeningForDeviceOrientationChange() => super.noSuchMethod( - Invocation.method( - #stopListeningForDeviceOrientationChange, - [], - ), - returnValueForMissingStub: null, - ); - - @override - int getDefaultDisplayRotation() => (super.noSuchMethod( - Invocation.method( - #getDefaultDisplayRotation, - [], - ), - returnValue: 0, - ) as int); - - @override - String getUiOrientation() => (super.noSuchMethod( - Invocation.method( - #getUiOrientation, - [], - ), - returnValue: _i3.dummyValue( - this, - Invocation.method( - #getUiOrientation, - [], - ), - ), - ) as String); -} diff --git a/packages/camera/camera_android_camerax/test/exposure_state_test.dart b/packages/camera/camera_android_camerax/test/exposure_state_test.dart deleted file mode 100644 index fe1cf0a6261c..000000000000 --- a/packages/camera/camera_android_camerax/test/exposure_state_test.dart +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camerax_library.g.dart'; -import 'package:camera_android_camerax/src/exposure_state.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; - -import 'exposure_state_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([TestInstanceManagerHostApi]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('ExposureState', () { - tearDown(() => TestCameraInfoHostApi.setup(null)); - - test('flutterApi create makes call to create expected ExposureState', () { - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final ExposureStateFlutterApiImpl flutterApi = - ExposureStateFlutterApiImpl( - instanceManager: instanceManager, - ); - const int exposureStateIdentifier = 68; - final ExposureCompensationRange exposureCompensationRange = - ExposureCompensationRange(minCompensation: 5, maxCompensation: 7); - const double exposureCompensationStep = 0.3; - - flutterApi.create(exposureStateIdentifier, exposureCompensationRange, - exposureCompensationStep); - - final ExposureState instance = - instanceManager.getInstanceWithWeakReference(exposureStateIdentifier)! - as ExposureState; - expect(instance.exposureCompensationRange, - equals(exposureCompensationRange)); - expect( - instance.exposureCompensationStep, equals(exposureCompensationStep)); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/exposure_state_test.mocks.dart b/packages/camera/camera_android_camerax/test/exposure_state_test.mocks.dart deleted file mode 100644 index df6f91f55784..000000000000 --- a/packages/camera/camera_android_camerax/test/exposure_state_test.mocks.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/exposure_state_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} diff --git a/packages/camera/camera_android_camerax/test/fallback_strategy_test.dart b/packages/camera/camera_android_camerax/test/fallback_strategy_test.dart deleted file mode 100644 index f54e40df62d2..000000000000 --- a/packages/camera/camera_android_camerax/test/fallback_strategy_test.dart +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camerax_library.g.dart'; -import 'package:camera_android_camerax/src/fallback_strategy.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'fallback_strategy_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([TestFallbackStrategyHostApi, TestInstanceManagerHostApi]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - group('FallbackStrategy', () { - tearDown(() { - TestFallbackStrategyHostApi.setup(null); - TestInstanceManagerHostApi.setup(null); - }); - - test('detached constructor does not call create on the Java side', - () async { - final MockTestFallbackStrategyHostApi mockApi = - MockTestFallbackStrategyHostApi(); - TestFallbackStrategyHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - FallbackStrategy.detached( - quality: VideoQuality.UHD, - fallbackRule: VideoResolutionFallbackRule.higherQualityThan, - instanceManager: instanceManager, - ); - - verifyNever(mockApi.create( - argThat(isA()), - argThat(isA()), - argThat(isA()), - )); - }); - - test('constructor calls create on the Java side', () { - final MockTestFallbackStrategyHostApi mockApi = - MockTestFallbackStrategyHostApi(); - TestFallbackStrategyHostApi.setup(mockApi); - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - const VideoQuality quality = VideoQuality.HD; - - const VideoResolutionFallbackRule fallbackRule = - VideoResolutionFallbackRule.lowerQualityThan; - - final FallbackStrategy instance = FallbackStrategy( - quality: quality, - fallbackRule: fallbackRule, - instanceManager: instanceManager, - ); - - verify(mockApi.create( - instanceManager.getIdentifier(instance), - quality, - fallbackRule, - )); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/fallback_strategy_test.mocks.dart b/packages/camera/camera_android_camerax/test/fallback_strategy_test.mocks.dart deleted file mode 100644 index eaa94632b2c8..000000000000 --- a/packages/camera/camera_android_camerax/test/fallback_strategy_test.mocks.dart +++ /dev/null @@ -1,69 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/fallback_strategy_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i3; -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestFallbackStrategyHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestFallbackStrategyHostApi extends _i1.Mock - implements _i2.TestFallbackStrategyHostApi { - MockTestFallbackStrategyHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void create( - int? identifier, - _i3.VideoQuality? quality, - _i3.VideoResolutionFallbackRule? fallbackRule, - ) => - super.noSuchMethod( - Invocation.method( - #create, - [ - identifier, - quality, - fallbackRule, - ], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} diff --git a/packages/camera/camera_android_camerax/test/focus_metering_action_test.dart b/packages/camera/camera_android_camerax/test/focus_metering_action_test.dart deleted file mode 100644 index afb31c1ab728..000000000000 --- a/packages/camera/camera_android_camerax/test/focus_metering_action_test.dart +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camerax_library.g.dart'; -import 'package:camera_android_camerax/src/focus_metering_action.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:camera_android_camerax/src/metering_point.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'focus_metering_action_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([ - MeteringPoint, - TestFocusMeteringActionHostApi, - TestInstanceManagerHostApi -]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('FocusMeteringAction', () { - tearDown(() => TestCameraHostApi.setup(null)); - - test('detached create does not call create on the Java side', () { - final MockTestFocusMeteringActionHostApi mockApi = - MockTestFocusMeteringActionHostApi(); - TestFocusMeteringActionHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - FocusMeteringAction.detached( - meteringPointInfos: <(MeteringPoint, int?)>[ - (MockMeteringPoint(), FocusMeteringAction.flagAwb) - ], - instanceManager: instanceManager, - ); - - verifyNever(mockApi.create(argThat(isA()), argThat(isA>()), - argThat(isA()))); - }, skip: 'Flaky test: https://github.com/flutter/flutter/issues/164132'); - - test('create calls create on the Java side', () { - final MockTestFocusMeteringActionHostApi mockApi = - MockTestFocusMeteringActionHostApi(); - TestFocusMeteringActionHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final MeteringPoint mockMeteringPoint1 = MockMeteringPoint(); - const int mockMeteringPoint1Mode = FocusMeteringAction.flagAe; - const int mockMeteringPoint1Id = 7; - final MeteringPoint mockMeteringPoint2 = MockMeteringPoint(); - const int mockMeteringPoint2Mode = FocusMeteringAction.flagAwb; - const int mockMeteringPoint2Id = 17; - final List<(MeteringPoint meteringPoint, int? meteringMode)> - meteringPointInfos = - <(MeteringPoint meteringPoint, int? meteringMode)>[ - (mockMeteringPoint1, mockMeteringPoint1Mode), - (mockMeteringPoint2, mockMeteringPoint2Mode) - ]; - const bool disableAutoCancel = true; - - instanceManager - .addHostCreatedInstance(mockMeteringPoint1, mockMeteringPoint1Id, - onCopy: (MeteringPoint original) { - return MockMeteringPoint(); - }); - instanceManager - .addHostCreatedInstance(mockMeteringPoint2, mockMeteringPoint2Id, - onCopy: (MeteringPoint original) { - return MockMeteringPoint(); - }); - - final FocusMeteringAction instance = FocusMeteringAction( - meteringPointInfos: meteringPointInfos, - disableAutoCancel: disableAutoCancel, - instanceManager: instanceManager, - ); - - final VerificationResult verificationResult = verify(mockApi.create( - argThat(equals(instanceManager.getIdentifier(instance))), - captureAny, - argThat(equals(disableAutoCancel)))); - final List captureMeteringPointInfos = - verificationResult.captured.single as List; - expect(captureMeteringPointInfos.length, equals(2)); - expect(captureMeteringPointInfos[0]!.meteringPointId, - equals(mockMeteringPoint1Id)); - expect( - captureMeteringPointInfos[0]!.meteringMode, mockMeteringPoint1Mode); - expect(captureMeteringPointInfos[1]!.meteringPointId, - equals(mockMeteringPoint2Id)); - expect( - captureMeteringPointInfos[1]!.meteringMode, mockMeteringPoint2Mode); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/focus_metering_action_test.mocks.dart b/packages/camera/camera_android_camerax/test/focus_metering_action_test.mocks.dart deleted file mode 100644 index 3b0e4c824076..000000000000 --- a/packages/camera/camera_android_camerax/test/focus_metering_action_test.mocks.dart +++ /dev/null @@ -1,112 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/focus_metering_action_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:camera_android_camerax/src/camera_info.dart' as _i2; -import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i5; -import 'package:camera_android_camerax/src/metering_point.dart' as _i3; -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i4; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -class _FakeCameraInfo_0 extends _i1.SmartFake implements _i2.CameraInfo { - _FakeCameraInfo_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); -} - -/// A class which mocks [MeteringPoint]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockMeteringPoint extends _i1.Mock implements _i3.MeteringPoint { - MockMeteringPoint() { - _i1.throwOnMissingStub(this); - } - - @override - double get x => (super.noSuchMethod( - Invocation.getter(#x), - returnValue: 0.0, - ) as double); - - @override - double get y => (super.noSuchMethod( - Invocation.getter(#y), - returnValue: 0.0, - ) as double); - - @override - _i2.CameraInfo get cameraInfo => (super.noSuchMethod( - Invocation.getter(#cameraInfo), - returnValue: _FakeCameraInfo_0( - this, - Invocation.getter(#cameraInfo), - ), - ) as _i2.CameraInfo); -} - -/// A class which mocks [TestFocusMeteringActionHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestFocusMeteringActionHostApi extends _i1.Mock - implements _i4.TestFocusMeteringActionHostApi { - MockTestFocusMeteringActionHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void create( - int? identifier, - List<_i5.MeteringPointInfo?>? meteringPointInfos, - bool? disableAutoCancel, - ) => - super.noSuchMethod( - Invocation.method( - #create, - [ - identifier, - meteringPointInfos, - disableAutoCancel, - ], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i4.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} diff --git a/packages/camera/camera_android_camerax/test/focus_metering_result_test.dart b/packages/camera/camera_android_camerax/test/focus_metering_result_test.dart deleted file mode 100644 index 591a1c2d32b3..000000000000 --- a/packages/camera/camera_android_camerax/test/focus_metering_result_test.dart +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/focus_metering_result.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:camera_android_camerax/src/metering_point.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'focus_metering_result_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([ - MeteringPoint, - TestFocusMeteringResultHostApi, - TestInstanceManagerHostApi -]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('FocusMeteringResult', () { - tearDown(() => TestCameraHostApi.setup(null)); - - test('isFocusSuccessful returns expected result', () async { - final MockTestFocusMeteringResultHostApi mockApi = - MockTestFocusMeteringResultHostApi(); - TestFocusMeteringResultHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final FocusMeteringResult focusMeteringResult = - FocusMeteringResult.detached( - instanceManager: instanceManager, - ); - const int focusMeteringResultIdentifier = 5; - - instanceManager.addHostCreatedInstance( - focusMeteringResult, - focusMeteringResultIdentifier, - onCopy: (_) => - FocusMeteringResult.detached(instanceManager: instanceManager), - ); - - when(mockApi.isFocusSuccessful(focusMeteringResultIdentifier)) - .thenAnswer((_) => false); - - expect(await focusMeteringResult.isFocusSuccessful(), isFalse); - verify(mockApi.isFocusSuccessful(focusMeteringResultIdentifier)); - }); - - test('flutterApiCreate makes call to add instance to instance manager', () { - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final FocusMeteringResultFlutterApiImpl flutterApi = - FocusMeteringResultFlutterApiImpl( - instanceManager: instanceManager, - ); - const int focusMeteringResultIdentifier = 37; - - flutterApi.create(focusMeteringResultIdentifier); - - expect( - instanceManager - .getInstanceWithWeakReference(focusMeteringResultIdentifier), - isA()); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/focus_metering_result_test.mocks.dart b/packages/camera/camera_android_camerax/test/focus_metering_result_test.mocks.dart deleted file mode 100644 index be52b17bda47..000000000000 --- a/packages/camera/camera_android_camerax/test/focus_metering_result_test.mocks.dart +++ /dev/null @@ -1,102 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/focus_metering_result_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:camera_android_camerax/src/camera_info.dart' as _i2; -import 'package:camera_android_camerax/src/metering_point.dart' as _i3; -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i4; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -class _FakeCameraInfo_0 extends _i1.SmartFake implements _i2.CameraInfo { - _FakeCameraInfo_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); -} - -/// A class which mocks [MeteringPoint]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockMeteringPoint extends _i1.Mock implements _i3.MeteringPoint { - MockMeteringPoint() { - _i1.throwOnMissingStub(this); - } - - @override - double get x => (super.noSuchMethod( - Invocation.getter(#x), - returnValue: 0.0, - ) as double); - - @override - double get y => (super.noSuchMethod( - Invocation.getter(#y), - returnValue: 0.0, - ) as double); - - @override - _i2.CameraInfo get cameraInfo => (super.noSuchMethod( - Invocation.getter(#cameraInfo), - returnValue: _FakeCameraInfo_0( - this, - Invocation.getter(#cameraInfo), - ), - ) as _i2.CameraInfo); -} - -/// A class which mocks [TestFocusMeteringResultHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestFocusMeteringResultHostApi extends _i1.Mock - implements _i4.TestFocusMeteringResultHostApi { - MockTestFocusMeteringResultHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - bool isFocusSuccessful(int? identifier) => (super.noSuchMethod( - Invocation.method( - #isFocusSuccessful, - [identifier], - ), - returnValue: false, - ) as bool); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i4.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} diff --git a/packages/camera/camera_android_camerax/test/image_analysis_test.dart b/packages/camera/camera_android_camerax/test/image_analysis_test.dart deleted file mode 100644 index 0da5fd1f720b..000000000000 --- a/packages/camera/camera_android_camerax/test/image_analysis_test.dart +++ /dev/null @@ -1,190 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/analyzer.dart'; -import 'package:camera_android_camerax/src/image_analysis.dart'; -import 'package:camera_android_camerax/src/image_proxy.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:camera_android_camerax/src/resolution_selector.dart'; -import 'package:camera_android_camerax/src/surface.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'image_analysis_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([ - TestImageAnalysisHostApi, - TestInstanceManagerHostApi, - ResolutionSelector, -]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('ImageAnalysis', () { - tearDown(() { - TestImageAnalysisHostApi.setup(null); - }); - - test('detached create does not call create on the Java side', () { - final MockTestImageAnalysisHostApi mockApi = - MockTestImageAnalysisHostApi(); - TestImageAnalysisHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - ImageAnalysis.detached( - initialTargetRotation: Surface.rotation270, - resolutionSelector: MockResolutionSelector(), - instanceManager: instanceManager, - ); - - verifyNever(mockApi.create(argThat(isA()), argThat(isA()), - argThat(isA()))); - }, skip: 'Flaky test: https://github.com/flutter/flutter/issues/164132'); - - test('create calls create on the Java side', () { - final MockTestImageAnalysisHostApi mockApi = - MockTestImageAnalysisHostApi(); - TestImageAnalysisHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - const int targetRotation = Surface.rotation90; - final MockResolutionSelector mockResolutionSelector = - MockResolutionSelector(); - const int mockResolutionSelectorId = 24; - - instanceManager.addHostCreatedInstance( - mockResolutionSelector, mockResolutionSelectorId, - onCopy: (ResolutionSelector original) { - return MockResolutionSelector(); - }); - - final ImageAnalysis instance = ImageAnalysis( - initialTargetRotation: targetRotation, - resolutionSelector: mockResolutionSelector, - instanceManager: instanceManager, - ); - - verify(mockApi.create( - argThat(equals(instanceManager.getIdentifier(instance))), - argThat(equals(targetRotation)), - argThat(equals(mockResolutionSelectorId)))); - }); - - test( - 'setTargetRotation makes call to set target rotation for ImageAnalysis instance', - () async { - final MockTestImageAnalysisHostApi mockApi = - MockTestImageAnalysisHostApi(); - TestImageAnalysisHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - const int targetRotation = Surface.rotation180; - final ImageAnalysis imageAnalysis = ImageAnalysis.detached( - instanceManager: instanceManager, - ); - instanceManager.addHostCreatedInstance( - imageAnalysis, - 0, - onCopy: (_) => ImageAnalysis.detached(instanceManager: instanceManager), - ); - - await imageAnalysis.setTargetRotation(targetRotation); - - verify(mockApi.setTargetRotation( - instanceManager.getIdentifier(imageAnalysis), targetRotation)); - }); - - test('setAnalyzer makes call to set analyzer on ImageAnalysis instance', - () async { - final MockTestImageAnalysisHostApi mockApi = - MockTestImageAnalysisHostApi(); - TestImageAnalysisHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final ImageAnalysis instance = ImageAnalysis.detached( - resolutionSelector: MockResolutionSelector(), - instanceManager: instanceManager, - ); - const int instanceIdentifier = 0; - instanceManager.addHostCreatedInstance( - instance, - instanceIdentifier, - onCopy: (ImageAnalysis original) => ImageAnalysis.detached( - resolutionSelector: original.resolutionSelector, - instanceManager: instanceManager, - ), - ); - - final Analyzer analyzer = Analyzer.detached( - analyze: (ImageProxy imageProxy) async {}, - instanceManager: instanceManager, - ); - const int analyzerIdentifier = 10; - instanceManager.addHostCreatedInstance( - analyzer, - analyzerIdentifier, - onCopy: (_) => Analyzer.detached( - analyze: (ImageProxy imageProxy) async {}, - instanceManager: instanceManager, - ), - ); - - await instance.setAnalyzer( - analyzer, - ); - - verify(mockApi.setAnalyzer( - instanceIdentifier, - analyzerIdentifier, - )); - }); - - test('clearAnalyzer makes call to clear analyzer on ImageAnalysis instance', - () async { - final MockTestImageAnalysisHostApi mockApi = - MockTestImageAnalysisHostApi(); - TestImageAnalysisHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final ImageAnalysis instance = ImageAnalysis.detached( - resolutionSelector: MockResolutionSelector(), - instanceManager: instanceManager, - ); - const int instanceIdentifier = 0; - instanceManager.addHostCreatedInstance( - instance, - instanceIdentifier, - onCopy: (ImageAnalysis original) => ImageAnalysis.detached( - resolutionSelector: original.resolutionSelector, - instanceManager: instanceManager, - ), - ); - - await instance.clearAnalyzer(); - - verify(mockApi.clearAnalyzer( - instanceIdentifier, - )); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/image_analysis_test.mocks.dart b/packages/camera/camera_android_camerax/test/image_analysis_test.mocks.dart deleted file mode 100644 index 4ceb25d66b97..000000000000 --- a/packages/camera/camera_android_camerax/test/image_analysis_test.mocks.dart +++ /dev/null @@ -1,121 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/image_analysis_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:camera_android_camerax/src/resolution_selector.dart' as _i3; -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestImageAnalysisHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestImageAnalysisHostApi extends _i1.Mock - implements _i2.TestImageAnalysisHostApi { - MockTestImageAnalysisHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void create( - int? identifier, - int? targetRotation, - int? resolutionSelectorId, - ) => - super.noSuchMethod( - Invocation.method( - #create, - [ - identifier, - targetRotation, - resolutionSelectorId, - ], - ), - returnValueForMissingStub: null, - ); - - @override - void setAnalyzer( - int? identifier, - int? analyzerIdentifier, - ) => - super.noSuchMethod( - Invocation.method( - #setAnalyzer, - [ - identifier, - analyzerIdentifier, - ], - ), - returnValueForMissingStub: null, - ); - - @override - void clearAnalyzer(int? identifier) => super.noSuchMethod( - Invocation.method( - #clearAnalyzer, - [identifier], - ), - returnValueForMissingStub: null, - ); - - @override - void setTargetRotation( - int? identifier, - int? rotation, - ) => - super.noSuchMethod( - Invocation.method( - #setTargetRotation, - [ - identifier, - rotation, - ], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [ResolutionSelector]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockResolutionSelector extends _i1.Mock - implements _i3.ResolutionSelector { - MockResolutionSelector() { - _i1.throwOnMissingStub(this); - } -} diff --git a/packages/camera/camera_android_camerax/test/image_capture_test.dart b/packages/camera/camera_android_camerax/test/image_capture_test.dart deleted file mode 100644 index aae531e7073d..000000000000 --- a/packages/camera/camera_android_camerax/test/image_capture_test.dart +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/image_capture.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:camera_android_camerax/src/resolution_selector.dart'; -import 'package:camera_android_camerax/src/surface.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'image_capture_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([ - TestImageCaptureHostApi, - TestInstanceManagerHostApi, - ResolutionSelector -]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('ImageCapture', () { - tearDown(() => TestImageCaptureHostApi.setup(null)); - - test('detached create does not call create on the Java side', () async { - final MockTestImageCaptureHostApi mockApi = MockTestImageCaptureHostApi(); - TestImageCaptureHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - ImageCapture.detached( - instanceManager: instanceManager, - initialTargetRotation: Surface.rotation180, - targetFlashMode: ImageCapture.flashModeOn, - resolutionSelector: MockResolutionSelector(), - ); - - verifyNever(mockApi.create(argThat(isA()), argThat(isA()), - argThat(isA()), argThat(isA()))); - }, skip: 'Flaky test: https://github.com/flutter/flutter/issues/164132'); - - test('create calls create on the Java side', () async { - final MockTestImageCaptureHostApi mockApi = MockTestImageCaptureHostApi(); - TestImageCaptureHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - const int targetRotation = Surface.rotation270; - const int targetFlashMode = ImageCapture.flashModeAuto; - final MockResolutionSelector mockResolutionSelector = - MockResolutionSelector(); - const int mockResolutionSelectorId = 24; - - instanceManager.addHostCreatedInstance( - mockResolutionSelector, mockResolutionSelectorId, - onCopy: (ResolutionSelector original) { - return MockResolutionSelector(); - }); - - ImageCapture( - instanceManager: instanceManager, - initialTargetRotation: targetRotation, - targetFlashMode: targetFlashMode, - resolutionSelector: mockResolutionSelector, - ); - - verify(mockApi.create( - argThat(isA()), - argThat(equals(targetRotation)), - argThat(equals(targetFlashMode)), - argThat(equals(mockResolutionSelectorId)))); - }); - - test('setFlashMode makes call to set flash mode for ImageCapture instance', - () async { - final MockTestImageCaptureHostApi mockApi = MockTestImageCaptureHostApi(); - TestImageCaptureHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - const int flashMode = ImageCapture.flashModeOff; - final ImageCapture imageCapture = ImageCapture.detached( - instanceManager: instanceManager, - ); - instanceManager.addHostCreatedInstance( - imageCapture, - 0, - onCopy: (_) => ImageCapture.detached(instanceManager: instanceManager), - ); - - await imageCapture.setFlashMode(flashMode); - - verify(mockApi.setFlashMode( - instanceManager.getIdentifier(imageCapture), flashMode)); - }); - - test( - 'setTargetRotation makes call to set target rotation for ImageCapture instance', - () async { - final MockTestImageCaptureHostApi mockApi = MockTestImageCaptureHostApi(); - TestImageCaptureHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - const int targetRotation = Surface.rotation180; - final ImageCapture imageCapture = ImageCapture.detached( - instanceManager: instanceManager, - ); - instanceManager.addHostCreatedInstance( - imageCapture, - 0, - onCopy: (_) => ImageCapture.detached(instanceManager: instanceManager), - ); - - await imageCapture.setTargetRotation(targetRotation); - - verify(mockApi.setTargetRotation( - instanceManager.getIdentifier(imageCapture), targetRotation)); - }); - - test('takePicture makes call to capture still image', () async { - final MockTestImageCaptureHostApi mockApi = MockTestImageCaptureHostApi(); - TestImageCaptureHostApi.setup(mockApi); - - const String expectedPicturePath = 'test/path/to/picture'; - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final ImageCapture imageCapture = ImageCapture.detached( - instanceManager: instanceManager, - ); - instanceManager.addHostCreatedInstance( - imageCapture, - 0, - onCopy: (_) => ImageCapture.detached(), - ); - - when(mockApi.takePicture(instanceManager.getIdentifier(imageCapture))) - .thenAnswer((_) async => expectedPicturePath); - expect(await imageCapture.takePicture(), equals(expectedPicturePath)); - verify(mockApi.takePicture(instanceManager.getIdentifier(imageCapture))); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/image_capture_test.mocks.dart b/packages/camera/camera_android_camerax/test/image_capture_test.mocks.dart deleted file mode 100644 index 353b55c6fe31..000000000000 --- a/packages/camera/camera_android_camerax/test/image_capture_test.mocks.dart +++ /dev/null @@ -1,132 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/image_capture_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i3; - -import 'package:camera_android_camerax/src/resolution_selector.dart' as _i5; -import 'package:mockito/mockito.dart' as _i1; -import 'package:mockito/src/dummies.dart' as _i4; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestImageCaptureHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestImageCaptureHostApi extends _i1.Mock - implements _i2.TestImageCaptureHostApi { - MockTestImageCaptureHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void create( - int? identifier, - int? targetRotation, - int? flashMode, - int? resolutionSelectorId, - ) => - super.noSuchMethod( - Invocation.method( - #create, - [ - identifier, - targetRotation, - flashMode, - resolutionSelectorId, - ], - ), - returnValueForMissingStub: null, - ); - - @override - void setFlashMode( - int? identifier, - int? flashMode, - ) => - super.noSuchMethod( - Invocation.method( - #setFlashMode, - [ - identifier, - flashMode, - ], - ), - returnValueForMissingStub: null, - ); - - @override - _i3.Future takePicture(int? identifier) => (super.noSuchMethod( - Invocation.method( - #takePicture, - [identifier], - ), - returnValue: _i3.Future.value(_i4.dummyValue( - this, - Invocation.method( - #takePicture, - [identifier], - ), - )), - ) as _i3.Future); - - @override - void setTargetRotation( - int? identifier, - int? rotation, - ) => - super.noSuchMethod( - Invocation.method( - #setTargetRotation, - [ - identifier, - rotation, - ], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [ResolutionSelector]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockResolutionSelector extends _i1.Mock - implements _i5.ResolutionSelector { - MockResolutionSelector() { - _i1.throwOnMissingStub(this); - } -} diff --git a/packages/camera/camera_android_camerax/test/image_proxy_test.dart b/packages/camera/camera_android_camerax/test/image_proxy_test.dart deleted file mode 100644 index a479412f8404..000000000000 --- a/packages/camera/camera_android_camerax/test/image_proxy_test.dart +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'dart:typed_data'; - -import 'package:camera_android_camerax/src/image_proxy.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:camera_android_camerax/src/plane_proxy.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'image_proxy_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([TestImageProxyHostApi, TestInstanceManagerHostApi]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('ImageProxy', () { - tearDown(() { - TestImageProxyHostApi.setup(null); - }); - - test('getPlanes', () async { - final MockTestImageProxyHostApi mockApi = MockTestImageProxyHostApi(); - TestImageProxyHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final ImageProxy instance = ImageProxy.detached( - instanceManager: instanceManager, format: 2, height: 7, width: 10); - const int instanceIdentifier = 0; - instanceManager.addHostCreatedInstance(instance, instanceIdentifier, - onCopy: (ImageProxy original) => ImageProxy.detached( - instanceManager: instanceManager, - format: original.format, - height: original.height, - width: original.width)); - final PlaneProxy planeProxy = PlaneProxy.detached( - instanceManager: instanceManager, - buffer: Uint8List(3), - pixelStride: 3, - rowStride: 20); - const int planeProxyIdentifier = 48; - instanceManager.addHostCreatedInstance(planeProxy, planeProxyIdentifier, - onCopy: (PlaneProxy original) => PlaneProxy.detached( - instanceManager: instanceManager, - buffer: original.buffer, - pixelStride: original.pixelStride, - rowStride: original.rowStride)); - - final List result = [planeProxyIdentifier]; - when(mockApi.getPlanes( - instanceIdentifier, - )).thenAnswer((_) { - return result; - }); - - final List planes = await instance.getPlanes(); - expect(planes[0], equals(planeProxy)); - - verify(mockApi.getPlanes( - instanceIdentifier, - )); - }); - - test('close', () async { - final MockTestImageProxyHostApi mockApi = MockTestImageProxyHostApi(); - TestImageProxyHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final ImageProxy instance = ImageProxy.detached( - instanceManager: instanceManager, format: 2, height: 7, width: 10); - const int instanceIdentifier = 0; - instanceManager.addHostCreatedInstance(instance, instanceIdentifier, - onCopy: (ImageProxy original) => ImageProxy.detached( - instanceManager: instanceManager, - format: original.format, - height: original.height, - width: original.width)); - - await instance.close(); - - verify(mockApi.close( - instanceIdentifier, - )); - }); - - test('FlutterAPI create', () { - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final ImageProxyFlutterApiImpl api = ImageProxyFlutterApiImpl( - instanceManager: instanceManager, - ); - - const int instanceIdentifier = 0; - const int format = 9; - const int height = 55; - const int width = 11; - - api.create( - instanceIdentifier, - format, - height, - width, - ); - - final ImageProxy imageProxy = - instanceManager.getInstanceWithWeakReference(instanceIdentifier)!; - - expect(imageProxy.format, equals(format)); - expect(imageProxy.height, equals(height)); - expect(imageProxy.width, equals(width)); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/image_proxy_test.mocks.dart b/packages/camera/camera_android_camerax/test/image_proxy_test.mocks.dart deleted file mode 100644 index 5d56a26d1c4d..000000000000 --- a/packages/camera/camera_android_camerax/test/image_proxy_test.mocks.dart +++ /dev/null @@ -1,68 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/image_proxy_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestImageProxyHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestImageProxyHostApi extends _i1.Mock - implements _i2.TestImageProxyHostApi { - MockTestImageProxyHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - List getPlanes(int? identifier) => (super.noSuchMethod( - Invocation.method( - #getPlanes, - [identifier], - ), - returnValue: [], - ) as List); - - @override - void close(int? identifier) => super.noSuchMethod( - Invocation.method( - #close, - [identifier], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} diff --git a/packages/camera/camera_android_camerax/test/instance_manager_test.dart b/packages/camera/camera_android_camerax/test/instance_manager_test.dart deleted file mode 100644 index 9562c41674ae..000000000000 --- a/packages/camera/camera_android_camerax/test/instance_manager_test.dart +++ /dev/null @@ -1,174 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:flutter_test/flutter_test.dart'; - -void main() { - group('InstanceManager', () { - test('addHostCreatedInstance', () { - final Object object = Object(); - - final InstanceManager instanceManager = - InstanceManager(onWeakReferenceRemoved: (_) {}); - - instanceManager.addHostCreatedInstance( - object, - 0, - onCopy: (_) => Object(), - ); - - expect(instanceManager.getIdentifier(object), 0); - expect( - instanceManager.getInstanceWithWeakReference(0), - object, - ); - }); - - test('addHostCreatedInstance prevents already used objects and ids', () { - final Object object = Object(); - - final InstanceManager instanceManager = - InstanceManager(onWeakReferenceRemoved: (_) {}); - - instanceManager.addHostCreatedInstance( - object, - 0, - onCopy: (_) => Object(), - ); - - expect( - () => instanceManager.addHostCreatedInstance( - object, - 0, - onCopy: (_) => Object(), - ), - throwsAssertionError, - ); - - expect( - () => instanceManager.addHostCreatedInstance( - Object(), - 0, - onCopy: (_) => Object(), - ), - throwsAssertionError, - ); - }); - - test('addDartCreatedInstance', () { - final Object object = Object(); - - final InstanceManager instanceManager = - InstanceManager(onWeakReferenceRemoved: (_) {}); - - instanceManager.addDartCreatedInstance( - object, - onCopy: (_) => Object(), - ); - - final int? instanceId = instanceManager.getIdentifier(object); - expect(instanceId, isNotNull); - expect( - instanceManager.getInstanceWithWeakReference(instanceId!), - object, - ); - }); - - test('removeWeakReference', () { - final Object object = Object(); - - int? weakInstanceId; - final InstanceManager instanceManager = - InstanceManager(onWeakReferenceRemoved: (int instanceId) { - weakInstanceId = instanceId; - }); - - instanceManager.addHostCreatedInstance( - object, - 0, - onCopy: (_) => Object(), - ); - - expect(instanceManager.removeWeakReference(object), 0); - expect( - instanceManager.getInstanceWithWeakReference(0), - isA(), - ); - expect(weakInstanceId, 0); - }); - - test('removeWeakReference removes only weak reference', () { - final Object object = Object(); - - final InstanceManager instanceManager = - InstanceManager(onWeakReferenceRemoved: (_) {}); - - instanceManager.addHostCreatedInstance( - object, - 0, - onCopy: (_) => Object(), - ); - - expect(instanceManager.removeWeakReference(object), 0); - final Object copy = instanceManager.getInstanceWithWeakReference( - 0, - )!; - expect(identical(object, copy), isFalse); - }); - - test('removeStrongReference', () { - final Object object = Object(); - - final InstanceManager instanceManager = - InstanceManager(onWeakReferenceRemoved: (_) {}); - - instanceManager.addHostCreatedInstance( - object, - 0, - onCopy: (_) => Object(), - ); - instanceManager.removeWeakReference(object); - expect(instanceManager.remove(0), isA()); - expect(instanceManager.containsIdentifier(0), isFalse); - }); - - test('removeStrongReference removes only strong reference', () { - final Object object = Object(); - - final InstanceManager instanceManager = - InstanceManager(onWeakReferenceRemoved: (_) {}); - - instanceManager.addHostCreatedInstance( - object, - 0, - onCopy: (_) => Object(), - ); - expect(instanceManager.remove(0), isA()); - expect( - instanceManager.getInstanceWithWeakReference(0), - object, - ); - }); - - test('getInstance can add a new weak reference', () { - final Object object = Object(); - - final InstanceManager instanceManager = - InstanceManager(onWeakReferenceRemoved: (_) {}); - - instanceManager.addHostCreatedInstance( - object, - 0, - onCopy: (_) => Object(), - ); - instanceManager.removeWeakReference(object); - - final Object newWeakCopy = instanceManager.getInstanceWithWeakReference( - 0, - )!; - expect(identical(object, newWeakCopy), isFalse); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/live_data_test.dart b/packages/camera/camera_android_camerax/test/live_data_test.dart deleted file mode 100644 index b760baac8669..000000000000 --- a/packages/camera/camera_android_camerax/test/live_data_test.dart +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camera_state.dart'; -import 'package:camera_android_camerax/src/camerax_library.g.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:camera_android_camerax/src/live_data.dart'; -import 'package:camera_android_camerax/src/observer.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'live_data_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([TestLiveDataHostApi, TestInstanceManagerHostApi]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('LiveData', () { - tearDown(() { - TestLiveDataHostApi.setup(null); - }); - - test('observe makes call to add observer to LiveData instance', () async { - final MockTestLiveDataHostApi mockApi = MockTestLiveDataHostApi(); - TestLiveDataHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final LiveData instance = LiveData.detached( - instanceManager: instanceManager, - ); - const int instanceIdentifier = 0; - instanceManager.addHostCreatedInstance( - instance, - instanceIdentifier, - onCopy: (LiveData original) => LiveData.detached( - instanceManager: instanceManager, - ), - ); - - final Observer observer = Observer.detached( - instanceManager: instanceManager, - onChanged: (Object value) {}, - ); - const int observerIdentifier = 20; - instanceManager.addHostCreatedInstance( - observer, - observerIdentifier, - onCopy: (_) => Observer.detached( - instanceManager: instanceManager, - onChanged: (Object value) {}, - ), - ); - - await instance.observe( - observer, - ); - - verify(mockApi.observe( - instanceIdentifier, - observerIdentifier, - )); - }); - - test( - 'removeObservers makes call to remove observers from LiveData instance', - () async { - final MockTestLiveDataHostApi mockApi = MockTestLiveDataHostApi(); - TestLiveDataHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final LiveData instance = LiveData.detached( - instanceManager: instanceManager, - ); - const int instanceIdentifier = 0; - instanceManager.addHostCreatedInstance( - instance, - instanceIdentifier, - onCopy: (LiveData original) => LiveData.detached( - instanceManager: instanceManager, - ), - ); - - await instance.removeObservers(); - - verify(mockApi.removeObservers( - instanceIdentifier, - )); - }); - - test('getValue returns expected value', () async { - final MockTestLiveDataHostApi mockApi = MockTestLiveDataHostApi(); - TestLiveDataHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final LiveData instance = LiveData.detached( - instanceManager: instanceManager, - ); - final CameraState testCameraState = - CameraState.detached(type: CameraStateType.closed); - const int instanceIdentifier = 0; - const int testCameraStateIdentifier = 22; - instanceManager.addHostCreatedInstance( - instance, - instanceIdentifier, - onCopy: (LiveData original) => - LiveData.detached( - instanceManager: instanceManager, - ), - ); - instanceManager.addHostCreatedInstance( - testCameraState, - testCameraStateIdentifier, - onCopy: (CameraState original) => CameraState.detached( - type: original.type, instanceManager: instanceManager), - ); - - when(mockApi.getValue(instanceIdentifier, any)) - .thenReturn(testCameraStateIdentifier); - - expect(await instance.getValue(), equals(testCameraState)); - }); - - test( - 'FlutterAPI create makes call to create LiveData instance with expected identifier', - () async { - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final LiveDataFlutterApiImpl api = LiveDataFlutterApiImpl( - instanceManager: instanceManager, - ); - - const int instanceIdentifier = 0; - - api.create( - instanceIdentifier, - LiveDataSupportedTypeData(value: LiveDataSupportedType.cameraState), - ); - - expect( - instanceManager.getInstanceWithWeakReference(instanceIdentifier), - isA>(), - ); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/live_data_test.mocks.dart b/packages/camera/camera_android_camerax/test/live_data_test.mocks.dart deleted file mode 100644 index 7a331a075035..000000000000 --- a/packages/camera/camera_android_camerax/test/live_data_test.mocks.dart +++ /dev/null @@ -1,89 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/live_data_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i3; -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestLiveDataHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestLiveDataHostApi extends _i1.Mock - implements _i2.TestLiveDataHostApi { - MockTestLiveDataHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void observe( - int? identifier, - int? observerIdentifier, - ) => - super.noSuchMethod( - Invocation.method( - #observe, - [ - identifier, - observerIdentifier, - ], - ), - returnValueForMissingStub: null, - ); - - @override - void removeObservers(int? identifier) => super.noSuchMethod( - Invocation.method( - #removeObservers, - [identifier], - ), - returnValueForMissingStub: null, - ); - - @override - int? getValue( - int? identifier, - _i3.LiveDataSupportedTypeData? type, - ) => - (super.noSuchMethod(Invocation.method( - #getValue, - [ - identifier, - type, - ], - )) as int?); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} diff --git a/packages/camera/camera_android_camerax/test/metering_point_test.dart b/packages/camera/camera_android_camerax/test/metering_point_test.dart deleted file mode 100644 index 24c899df6a58..000000000000 --- a/packages/camera/camera_android_camerax/test/metering_point_test.dart +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camera_info.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:camera_android_camerax/src/metering_point.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'metering_point_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks( - [TestInstanceManagerHostApi, TestMeteringPointHostApi, CameraInfo]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('MeteringPoint', () { - tearDown(() => TestMeteringPointHostApi.setup(null)); - - test('detached create does not call create on the Java side', () async { - final MockTestMeteringPointHostApi mockApi = - MockTestMeteringPointHostApi(); - TestMeteringPointHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - MeteringPoint.detached( - x: 0, - y: 0.3, - size: 4, - cameraInfo: MockCameraInfo(), - instanceManager: instanceManager, - ); - - verifyNever(mockApi.create(argThat(isA()), argThat(isA()), - argThat(isA()), argThat(isA()), argThat(isA()))); - }, skip: 'Flaky test: https://github.com/flutter/flutter/issues/164132'); - - test('create calls create on the Java side', () async { - final MockTestMeteringPointHostApi mockApi = - MockTestMeteringPointHostApi(); - TestMeteringPointHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - const double x = 0.5; - const double y = 0.6; - const double size = 3; - final CameraInfo mockCameraInfo = MockCameraInfo(); - const int mockCameraInfoId = 4; - - instanceManager.addHostCreatedInstance(mockCameraInfo, mockCameraInfoId, - onCopy: (CameraInfo original) => MockCameraInfo()); - - MeteringPoint( - x: x, - y: y, - size: size, - cameraInfo: mockCameraInfo, - instanceManager: instanceManager, - ); - - verify(mockApi.create( - argThat(isA()), - x, - y, - size, - mockCameraInfoId, - )); - }); - - test('getDefaultPointSize returns expected size', () async { - final MockTestMeteringPointHostApi mockApi = - MockTestMeteringPointHostApi(); - TestMeteringPointHostApi.setup(mockApi); - - const double defaultPointSize = 6; - when(mockApi.getDefaultPointSize()).thenAnswer((_) => defaultPointSize); - - expect( - await MeteringPoint.getDefaultPointSize(), equals(defaultPointSize)); - verify(mockApi.getDefaultPointSize()); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/metering_point_test.mocks.dart b/packages/camera/camera_android_camerax/test/metering_point_test.mocks.dart deleted file mode 100644 index e7a3d9fadb13..000000000000 --- a/packages/camera/camera_android_camerax/test/metering_point_test.mocks.dart +++ /dev/null @@ -1,176 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/metering_point_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i6; - -import 'package:camera_android_camerax/src/camera_info.dart' as _i5; -import 'package:camera_android_camerax/src/camera_state.dart' as _i7; -import 'package:camera_android_camerax/src/exposure_state.dart' as _i3; -import 'package:camera_android_camerax/src/live_data.dart' as _i2; -import 'package:camera_android_camerax/src/zoom_state.dart' as _i8; -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i4; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -class _FakeLiveData_0 extends _i1.SmartFake - implements _i2.LiveData { - _FakeLiveData_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); -} - -class _FakeExposureState_1 extends _i1.SmartFake implements _i3.ExposureState { - _FakeExposureState_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i4.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [TestMeteringPointHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestMeteringPointHostApi extends _i1.Mock - implements _i4.TestMeteringPointHostApi { - MockTestMeteringPointHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void create( - int? identifier, - double? x, - double? y, - double? size, - int? cameraInfoId, - ) => - super.noSuchMethod( - Invocation.method( - #create, - [ - identifier, - x, - y, - size, - cameraInfoId, - ], - ), - returnValueForMissingStub: null, - ); - - @override - double getDefaultPointSize() => (super.noSuchMethod( - Invocation.method( - #getDefaultPointSize, - [], - ), - returnValue: 0.0, - ) as double); -} - -/// A class which mocks [CameraInfo]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockCameraInfo extends _i1.Mock implements _i5.CameraInfo { - MockCameraInfo() { - _i1.throwOnMissingStub(this); - } - - @override - _i6.Future getSensorRotationDegrees() => (super.noSuchMethod( - Invocation.method( - #getSensorRotationDegrees, - [], - ), - returnValue: _i6.Future.value(0), - ) as _i6.Future); - - @override - _i6.Future<_i2.LiveData<_i7.CameraState>> getCameraState() => - (super.noSuchMethod( - Invocation.method( - #getCameraState, - [], - ), - returnValue: _i6.Future<_i2.LiveData<_i7.CameraState>>.value( - _FakeLiveData_0<_i7.CameraState>( - this, - Invocation.method( - #getCameraState, - [], - ), - )), - ) as _i6.Future<_i2.LiveData<_i7.CameraState>>); - - @override - _i6.Future<_i3.ExposureState> getExposureState() => (super.noSuchMethod( - Invocation.method( - #getExposureState, - [], - ), - returnValue: _i6.Future<_i3.ExposureState>.value(_FakeExposureState_1( - this, - Invocation.method( - #getExposureState, - [], - ), - )), - ) as _i6.Future<_i3.ExposureState>); - - @override - _i6.Future<_i2.LiveData<_i8.ZoomState>> getZoomState() => (super.noSuchMethod( - Invocation.method( - #getZoomState, - [], - ), - returnValue: _i6.Future<_i2.LiveData<_i8.ZoomState>>.value( - _FakeLiveData_0<_i8.ZoomState>( - this, - Invocation.method( - #getZoomState, - [], - ), - )), - ) as _i6.Future<_i2.LiveData<_i8.ZoomState>>); -} diff --git a/packages/camera/camera_android_camerax/test/observer_test.dart b/packages/camera/camera_android_camerax/test/observer_test.dart deleted file mode 100644 index b0ee0380935c..000000000000 --- a/packages/camera/camera_android_camerax/test/observer_test.dart +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camera_state.dart'; -import 'package:camera_android_camerax/src/camerax_library.g.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:camera_android_camerax/src/observer.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'observer_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([TestObserverHostApi, TestInstanceManagerHostApi]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('Observer', () { - tearDown(() { - TestObserverHostApi.setup(null); - }); - - test('HostApi create makes call to create Observer instance', () { - final MockTestObserverHostApi mockApi = MockTestObserverHostApi(); - TestObserverHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final Observer instance = Observer( - instanceManager: instanceManager, - onChanged: (Object value) {}, - ); - - verify(mockApi.create( - instanceManager.getIdentifier(instance), - )); - }); - - test( - 'HostAPI create makes Observer instance that throws assertion error if onChanged receives unexpected parameter type', - () { - final MockTestObserverHostApi mockApi = MockTestObserverHostApi(); - TestObserverHostApi.setup(mockApi); - - final Observer cameraStateObserver = - Observer.detached(onChanged: (Object value) {}); - - expect( - () => cameraStateObserver.onChanged( - CameraState.detached(type: CameraStateType.pendingOpen)), - throwsAssertionError); - }); - - test( - 'FlutterAPI onChanged makes call with expected parameter to Observer instance onChanged callback', - () { - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - const int instanceIdentifier = 0; - late final Object? callbackParameter; - final Observer instance = Observer.detached( - onChanged: (Object value) { - callbackParameter = value; - }, - instanceManager: instanceManager, - ); - instanceManager.addHostCreatedInstance( - instance, - instanceIdentifier, - onCopy: (Observer original) => - Observer.detached( - onChanged: original.onChanged, - instanceManager: instanceManager, - ), - ); - - final ObserverFlutterApiImpl flutterApi = ObserverFlutterApiImpl( - instanceManager: instanceManager, - ); - - const CameraStateType cameraStateType = CameraStateType.closed; - - final CameraState value = CameraState.detached( - instanceManager: instanceManager, - type: cameraStateType, - ); - const int valueIdentifier = 11; - instanceManager.addHostCreatedInstance( - value, - valueIdentifier, - onCopy: (_) => CameraState.detached( - instanceManager: instanceManager, - type: cameraStateType, - ), - ); - - flutterApi.onChanged( - instanceIdentifier, - valueIdentifier, - ); - - expect(callbackParameter, value); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/observer_test.mocks.dart b/packages/camera/camera_android_camerax/test/observer_test.mocks.dart deleted file mode 100644 index 5631ae84d01e..000000000000 --- a/packages/camera/camera_android_camerax/test/observer_test.mocks.dart +++ /dev/null @@ -1,59 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/observer_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestObserverHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestObserverHostApi extends _i1.Mock - implements _i2.TestObserverHostApi { - MockTestObserverHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void create(int? identifier) => super.noSuchMethod( - Invocation.method( - #create, - [identifier], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} diff --git a/packages/camera/camera_android_camerax/test/pending_recording_test.dart b/packages/camera/camera_android_camerax/test/pending_recording_test.dart deleted file mode 100644 index 8957979cdd81..000000000000 --- a/packages/camera/camera_android_camerax/test/pending_recording_test.dart +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camerax_library.g.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:camera_android_camerax/src/pending_recording.dart'; -import 'package:camera_android_camerax/src/recording.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'pending_recording_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks( - [TestPendingRecordingHostApi, TestInstanceManagerHostApi, Recording]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - test('start calls start on the Java side', () async { - final MockTestPendingRecordingHostApi mockApi = - MockTestPendingRecordingHostApi(); - TestPendingRecordingHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final PendingRecording pendingRecording = - PendingRecording.detached(instanceManager: instanceManager); - const int pendingRecordingId = 2; - instanceManager.addHostCreatedInstance(pendingRecording, pendingRecordingId, - onCopy: (_) => - PendingRecording.detached(instanceManager: instanceManager)); - - final Recording mockRecording = MockRecording(); - const int mockRecordingId = 3; - instanceManager.addHostCreatedInstance(mockRecording, mockRecordingId, - onCopy: (_) => Recording.detached(instanceManager: instanceManager)); - - when(mockApi.start(pendingRecordingId)).thenReturn(mockRecordingId); - expect(await pendingRecording.start(), mockRecording); - verify(mockApi.start(pendingRecordingId)); - }); - - test('flutterApiCreateTest', () async { - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final PendingRecordingFlutterApi flutterApi = - PendingRecordingFlutterApiImpl( - instanceManager: instanceManager, - ); - - flutterApi.create(0); - - expect(instanceManager.getInstanceWithWeakReference(0), - isA()); - }); -} diff --git a/packages/camera/camera_android_camerax/test/pending_recording_test.mocks.dart b/packages/camera/camera_android_camerax/test/pending_recording_test.mocks.dart deleted file mode 100644 index 99a982c2dea9..000000000000 --- a/packages/camera/camera_android_camerax/test/pending_recording_test.mocks.dart +++ /dev/null @@ -1,112 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/pending_recording_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i4; - -import 'package:camera_android_camerax/src/recording.dart' as _i3; -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestPendingRecordingHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestPendingRecordingHostApi extends _i1.Mock - implements _i2.TestPendingRecordingHostApi { - MockTestPendingRecordingHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - int start(int? identifier) => (super.noSuchMethod( - Invocation.method( - #start, - [identifier], - ), - returnValue: 0, - ) as int); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [Recording]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockRecording extends _i1.Mock implements _i3.Recording { - MockRecording() { - _i1.throwOnMissingStub(this); - } - - @override - _i4.Future close() => (super.noSuchMethod( - Invocation.method( - #close, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future pause() => (super.noSuchMethod( - Invocation.method( - #pause, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future resume() => (super.noSuchMethod( - Invocation.method( - #resume, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); - - @override - _i4.Future stop() => (super.noSuchMethod( - Invocation.method( - #stop, - [], - ), - returnValue: _i4.Future.value(), - returnValueForMissingStub: _i4.Future.value(), - ) as _i4.Future); -} diff --git a/packages/camera/camera_android_camerax/test/plane_proxy_test.dart b/packages/camera/camera_android_camerax/test/plane_proxy_test.dart deleted file mode 100644 index acfb2c9fb909..000000000000 --- a/packages/camera/camera_android_camerax/test/plane_proxy_test.dart +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'dart:typed_data'; - -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:camera_android_camerax/src/plane_proxy.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; - -import 'plane_proxy_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([TestInstanceManagerHostApi]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('PlaneProxy', () { - test('FlutterAPI create', () { - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final PlaneProxyFlutterApiImpl api = PlaneProxyFlutterApiImpl( - instanceManager: instanceManager, - ); - - const int instanceIdentifier = 0; - final Uint8List buffer = Uint8List(1); - const int pixelStride = 3; - const int rowStride = 6; - - api.create(instanceIdentifier, buffer, pixelStride, rowStride); - - final PlaneProxy planeProxy = - instanceManager.getInstanceWithWeakReference(instanceIdentifier)!; - - expect(planeProxy.buffer, equals(buffer)); - expect(planeProxy.pixelStride, equals(pixelStride)); - expect(planeProxy.rowStride, equals(rowStride)); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/plane_proxy_test.mocks.dart b/packages/camera/camera_android_camerax/test/plane_proxy_test.mocks.dart deleted file mode 100644 index da1525bfc262..000000000000 --- a/packages/camera/camera_android_camerax/test/plane_proxy_test.mocks.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/plane_proxy_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} diff --git a/packages/camera/camera_android_camerax/test/preview_rotation_test.dart b/packages/camera/camera_android_camerax/test/preview_rotation_test.dart index e06d16cbc0f6..fc651d779ce9 100644 --- a/packages/camera/camera_android_camerax/test/preview_rotation_test.dart +++ b/packages/camera/camera_android_camerax/test/preview_rotation_test.dart @@ -3,14 +3,11 @@ // found in the LICENSE file. import 'package:camera_android_camerax/camera_android_camerax.dart'; -import 'package:camera_android_camerax/src/camera_selector.dart'; -import 'package:camera_android_camerax/src/camerax_library.g.dart'; +import 'package:camera_android_camerax/src/camerax_library.dart'; import 'package:camera_android_camerax/src/camerax_proxy.dart'; -import 'package:camera_android_camerax/src/device_orientation_manager.dart'; -import 'package:camera_android_camerax/src/fallback_strategy.dart'; import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:flutter/services.dart'; -import 'package:flutter/widgets.dart'; +import 'package:flutter/widgets.dart' show RotatedBox, Texture; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; @@ -29,98 +26,293 @@ void main() { /// /// Returns mock ProcessCameraProvider that is used to select test camera. MockProcessCameraProvider - setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( - {required MockCameraSelector mockCameraSelector, - required int sensorRotationDegrees}) { + setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera({ + required MockCameraSelector mockCameraSelector, + required int sensorRotationDegrees, + }) { final MockProcessCameraProvider mockProcessCameraProvider = MockProcessCameraProvider(); final MockCameraInfo mockCameraInfo = MockCameraInfo(); final MockCamera mockCamera = MockCamera(); // Mock retrieving available test camera. - when(mockProcessCameraProvider.bindToLifecycle(any, any)) - .thenAnswer((_) async => mockCamera); + when( + mockProcessCameraProvider.bindToLifecycle(any, any), + ).thenAnswer((_) async => mockCamera); when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); - when(mockProcessCameraProvider.getAvailableCameraInfos()) - .thenAnswer((_) async => [mockCameraInfo]); - when(mockCameraSelector.filter([mockCameraInfo])) - .thenAnswer((_) async => [mockCameraInfo]); - when(mockCameraInfo.getSensorRotationDegrees()) - .thenAnswer((_) async => sensorRotationDegrees); + when( + mockProcessCameraProvider.getAvailableCameraInfos(), + ).thenAnswer((_) async => [mockCameraInfo]); + when( + mockCameraSelector.filter([mockCameraInfo]), + ).thenAnswer((_) async => [mockCameraInfo]); + when( + mockCameraInfo.sensorRotationDegrees, + ).thenReturn(sensorRotationDegrees); // Mock additional ProcessCameraProvider operation that is irrelevant // for the tests in this file. - when(mockCameraInfo.getCameraState()) - .thenAnswer((_) async => MockLiveCameraState()); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => MockLiveCameraState()); return mockProcessCameraProvider; } /// Returns CameraXProxy used to mock all calls to native Android in /// the `availableCameras` and `createCameraWithSettings` methods. - CameraXProxy getProxyForCreatingTestCamera( - {required MockProcessCameraProvider mockProcessCameraProvider, - required CameraSelector Function(int) createCameraSelector, - required bool handlesCropAndRotation, - required Future Function() getUiOrientation}) => + CameraXProxy getProxyForCreatingTestCamera({ + required MockProcessCameraProvider mockProcessCameraProvider, + required CameraSelector Function({ + LensFacing? requireLensFacing, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) createCameraSelector, + required bool handlesCropAndRotation, + required Future Function() getUiOrientation, + }) => CameraXProxy( - getProcessCameraProvider: () async => mockProcessCameraProvider, - createCameraSelector: createCameraSelector, - previewSurfaceProducerHandlesCropAndRotation: (_) => - Future.value(handlesCropAndRotation), - getUiOrientation: getUiOrientation, - createPreview: (_, __) => MockPreview(), - createImageCapture: (_, __) => MockImageCapture(), - createRecorder: (_) => MockRecorder(), - createVideoCapture: (_) async => MockVideoCapture(), - createImageAnalysis: (_, __) => MockImageAnalysis(), - createResolutionStrategy: ( - {bool highestAvailable = false, - Size? boundSize, - int? fallbackRule}) => - MockResolutionStrategy(), - createResolutionSelector: (_, __, ___) => MockResolutionSelector(), - createFallbackStrategy: ( - {required VideoQuality quality, - required VideoResolutionFallbackRule fallbackRule}) => - MockFallbackStrategy(), - createQualitySelector: ( - {required VideoQuality videoQuality, - required FallbackStrategy fallbackStrategy}) => - MockQualitySelector(), - createCameraStateObserver: (_) => MockObserver(), - requestCameraPermissions: (_) => Future.value(), - startListeningForDeviceOrientationChange: (_, __) {}, - setPreviewSurfaceProvider: (_) => Future.value( - 3), // 3 is a random Flutter SurfaceTexture ID for testing - createAspectRatioStrategy: (int aspectRatio, int fallbackRule) => - MockAspectRatioStrategy(), - createResolutionFilterWithOnePreferredSize: - (Size preferredResolution) => MockResolutionFilter(), + getInstanceProcessCameraProvider: ({ + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) async => + mockProcessCameraProvider, + newCameraSelector: createCameraSelector, + newPreview: ({ + int? targetRotation, + ResolutionSelector? resolutionSelector, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockPreview preview = MockPreview(); + when( + preview.surfaceProducerHandlesCropAndRotation(), + ).thenAnswer((_) async => handlesCropAndRotation); + return preview; + }, + newImageCapture: ({ + int? targetRotation, + CameraXFlashMode? flashMode, + ResolutionSelector? resolutionSelector, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + MockImageCapture(), + newRecorder: ({ + int? aspectRatio, + int? targetVideoEncodingBitRate, + QualitySelector? qualitySelector, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + MockRecorder(), + withOutputVideoCapture: ({ + required VideoOutput videoOutput, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockVideoCapture(); + }, + newImageAnalysis: ({ + int? targetRotation, + ResolutionSelector? resolutionSelector, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockImageAnalysis(); + }, + newResolutionStrategy: ({ + required CameraSize boundSize, + required ResolutionStrategyFallbackRule fallbackRule, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockResolutionStrategy(); + }, + newResolutionSelector: ({ + AspectRatioStrategy? aspectRatioStrategy, + ResolutionStrategy? resolutionStrategy, + ResolutionFilter? resolutionFilter, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockResolutionSelector(); + }, + lowerQualityOrHigherThanFallbackStrategy: ({ + required VideoQuality quality, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockFallbackStrategy(); + }, + lowerQualityThanFallbackStrategy: ({ + required VideoQuality quality, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockFallbackStrategy(); + }, + fromCamera2CameraInfo: ({ + required CameraInfo cameraInfo, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockCamera2CameraInfo camera2cameraInfo = + MockCamera2CameraInfo(); + when( + camera2cameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => 90); + return camera2cameraInfo; + }, + fromQualitySelector: ({ + required VideoQuality quality, + FallbackStrategy? fallbackStrategy, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockQualitySelector(); + }, + newObserver: ({ + required void Function(Observer, T) onChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return Observer.detached( + onChanged: onChanged, + pigeon_instanceManager: PigeonInstanceManager( + onWeakReferenceRemoved: (_) {}, + ), + ); + }, + newSystemServicesManager: ({ + required void Function(SystemServicesManager, String) onCameraError, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockSystemServicesManager(); + }, + newDeviceOrientationManager: ({ + required void Function(DeviceOrientationManager, String) + onDeviceOrientationChanged, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockDeviceOrientationManager manager = + MockDeviceOrientationManager(); + when(manager.getUiOrientation()) + .thenAnswer((_) => getUiOrientation()); + return manager; + }, // 3 is a random Flutter SurfaceTexture ID for testing + newAspectRatioStrategy: ({ + required AspectRatio preferredAspectRatio, + required AspectRatioStrategyFallbackRule fallbackRule, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + final MockAspectRatioStrategy mockAspectRatioStrategy = + MockAspectRatioStrategy(); + when( + mockAspectRatioStrategy.getFallbackRule(), + ).thenAnswer((_) async => fallbackRule); + when( + mockAspectRatioStrategy.getPreferredAspectRatio(), + ).thenAnswer((_) async => preferredAspectRatio); + return mockAspectRatioStrategy; + }, + createWithOnePreferredSizeResolutionFilter: ({ + required CameraSize preferredSize, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + return MockResolutionFilter(); + }, ); /// Returns function that a CameraXProxy can use to select the front camera. - MockCameraSelector Function(int cameraSelectorLensDirection) - createCameraSelectorForFrontCamera( - MockCameraSelector mockCameraSelector) { - return (int cameraSelectorLensDirection) { - switch (cameraSelectorLensDirection) { - case CameraSelector.lensFacingFront: + MockCameraSelector Function({ + LensFacing? requireLensFacing, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) createCameraSelectorForFrontCamera(MockCameraSelector mockCameraSelector) { + return ({ + LensFacing? requireLensFacing, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + switch (requireLensFacing) { + case LensFacing.front: return mockCameraSelector; - default: + case LensFacing.back: + case LensFacing.external: + case LensFacing.unknown: + case null: return MockCameraSelector(); } }; } /// Returns function that a CameraXProxy can use to select the back camera. - MockCameraSelector Function(int cameraSelectorLensDirection) - createCameraSelectorForBackCamera(MockCameraSelector mockCameraSelector) { - return (int cameraSelectorLensDirection) { - switch (cameraSelectorLensDirection) { - case CameraSelector.lensFacingBack: + MockCameraSelector Function({ + LensFacing? requireLensFacing, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) createCameraSelectorForBackCamera(MockCameraSelector mockCameraSelector) { + return ({ + LensFacing? requireLensFacing, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) { + switch (requireLensFacing) { + case LensFacing.back: return mockCameraSelector; - default: + case LensFacing.front: + case LensFacing.external: + case LensFacing.unknown: + case null: return MockCameraSelector(); } }; @@ -128,49 +320,65 @@ void main() { /// Error message for detecting an incorrect preview rotation. String getExpectedRotationTestFailureReason( - int expectedQuarterTurns, int actualQuarterTurns) => + int expectedQuarterTurns, + int actualQuarterTurns, + ) => 'Expected the preview to be rotated by $expectedQuarterTurns quarter turns (which is ${expectedQuarterTurns * 90} degrees clockwise) but instead was rotated $actualQuarterTurns quarter turns.'; testWidgets( - 'when handlesCropAndRotation is true, the preview is an unrotated Texture', - (WidgetTester tester) async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 537; - const MediaSettings testMediaSettings = - MediaSettings(); // media settings irrelevant for test - - // Set up test camera (specifics irrelevant for this test) and - // tell camera that handlesCropAndRotation is true. - final MockCameraSelector mockCameraSelector = MockCameraSelector(); - final MockProcessCameraProvider mockProcessCameraProvider = - setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( - mockCameraSelector: mockCameraSelector, - sensorRotationDegrees: /* irrelevant for test */ 90); - camera.proxy = getProxyForCreatingTestCamera( + 'when handlesCropAndRotation is true, the preview is an unrotated Texture', + (WidgetTester tester) async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 537; + const MediaSettings testMediaSettings = + MediaSettings(); // media settings irrelevant for test + + // Set up test camera (specifics irrelevant for this test) and + // tell camera that handlesCropAndRotation is true. + final MockCameraSelector mockCameraSelector = MockCameraSelector(); + final MockProcessCameraProvider mockProcessCameraProvider = + setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( + mockCameraSelector: mockCameraSelector, + sensorRotationDegrees: /* irrelevant for test */ 90, + ); + camera.proxy = getProxyForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProvider, - createCameraSelector: (_) => mockCameraSelector, + createCameraSelector: ({ + LensFacing? requireLensFacing, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) => + mockCameraSelector, handlesCropAndRotation: true, - /* irrelevant for test */ getUiOrientation: () => - Future.value(DeviceOrientation.landscapeLeft)); - - // Get and create test camera. - final List availableCameras = - await camera.availableCameras(); - expect(availableCameras.length, 1); - await camera.createCameraWithSettings( - availableCameras.first, testMediaSettings); - - // Put camera preview in widget tree. - await tester.pumpWidget(camera.buildPreview(cameraId)); - - // Verify Texture was built. - final Texture texture = tester.widget(find.byType(Texture)); - expect(texture.textureId, cameraId); - - // Verify RotatedBox was not built and thus, the Texture is not rotated. - expect(() => tester.widget(find.byType(RotatedBox)), - throwsStateError); - }); + /* irrelevant for test */ getUiOrientation: () async => + _serializeDeviceOrientation(DeviceOrientation.landscapeLeft), + ); + + // Get and create test camera. + final List availableCameras = + await camera.availableCameras(); + expect(availableCameras.length, 1); + await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); + + // Put camera preview in widget tree. + await tester.pumpWidget(camera.buildPreview(cameraId)); + + // Verify Texture was built. + final Texture texture = tester.widget(find.byType(Texture)); + expect(texture.textureId, cameraId); + + // Verify RotatedBox was not built and thus, the Texture is not rotated. + expect( + () => tester.widget(find.byType(RotatedBox)), + throwsStateError, + ); + }, + ); group('when handlesCropAndRotation is false,', () { // Test that preview rotation responds to initial device orientation: @@ -178,8 +386,13 @@ void main() { late AndroidCameraCameraX camera; late int cameraId; late MockCameraSelector mockFrontCameraSelector; - late MockCameraSelector Function(int cameraSelectorLensDirection) - proxyCreateCameraSelectorForFrontCamera; + late MockCameraSelector Function({ + LensFacing? requireLensFacing, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) proxyCreateCameraSelectorForFrontCamera; late MockProcessCameraProvider mockProcessCameraProviderForFrontCamera; late MediaSettings testMediaSettings; @@ -194,444 +407,581 @@ void main() { createCameraSelectorForFrontCamera(mockFrontCameraSelector); mockProcessCameraProviderForFrontCamera = setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( - mockCameraSelector: mockFrontCameraSelector, - sensorRotationDegrees: 270); + mockCameraSelector: mockFrontCameraSelector, + sensorRotationDegrees: 270, + ); // Media settings to create camera; irrelevant for test. testMediaSettings = const MediaSettings(); }); testWidgets( - 'initial device orientation fixed to DeviceOrientation.portraitUp, then the preview Texture is rotated 270 degrees clockwise', - (WidgetTester tester) async { - // Set up test to use front camera, tell camera that handlesCropAndRotation is false, - // set camera initial device orientation to portrait up. - camera.proxy = getProxyForCreatingTestCamera( + 'initial device orientation fixed to DeviceOrientation.portraitUp, then the preview Texture is rotated 270 degrees clockwise', + (WidgetTester tester) async { + // Set up test to use front camera, tell camera that handlesCropAndRotation is false, + // set camera initial device orientation to portrait up. + camera.proxy = getProxyForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, handlesCropAndRotation: false, - getUiOrientation: () => - Future.value(DeviceOrientation.portraitUp)); - - // Get and create test front camera. - final List availableCameras = - await camera.availableCameras(); - expect(availableCameras.length, 1); - await camera.createCameraWithSettings( - availableCameras.first, testMediaSettings); - - // Put camera preview in widget tree. - await tester.pumpWidget(camera.buildPreview(cameraId)); - - // Verify Texture is rotated by ((270 - 0 * 1 + 360) % 360) - 0 = 270 degrees. - const int expectedQuarterTurns = _270DegreesClockwise; - final RotatedBox rotatedBox = - tester.widget(find.byType(RotatedBox)); - expect(rotatedBox.child, isA()); - expect((rotatedBox.child! as Texture).textureId, cameraId); - expect(rotatedBox.quarterTurns, expectedQuarterTurns, + getUiOrientation: () async => + _serializeDeviceOrientation(DeviceOrientation.portraitUp), + ); + + // Get and create test front camera. + final List availableCameras = + await camera.availableCameras(); + expect(availableCameras.length, 1); + await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); + + // Put camera preview in widget tree. + await tester.pumpWidget(camera.buildPreview(cameraId)); + + // Verify Texture is rotated by ((270 - 0 * 1 + 360) % 360) - 0 = 270 degrees. + const int expectedQuarterTurns = _270DegreesClockwise; + final RotatedBox rotatedBox = tester.widget( + find.byType(RotatedBox), + ); + expect(rotatedBox.child, isA()); + expect((rotatedBox.child! as Texture).textureId, cameraId); + expect( + rotatedBox.quarterTurns, + expectedQuarterTurns, reason: getExpectedRotationTestFailureReason( - expectedQuarterTurns, rotatedBox.quarterTurns)); - }); + expectedQuarterTurns, + rotatedBox.quarterTurns, + ), + ); + }, + ); testWidgets( - 'initial device orientation fixed to DeviceOrientation.landscapeRight, then the preview Texture is rotated 90 degrees clockwise', - (WidgetTester tester) async { - // Set up test to use front camera, tell camera that handlesCropAndRotation is false, - // set camera initial device orientation to landscape right. - camera.proxy = getProxyForCreatingTestCamera( + 'initial device orientation fixed to DeviceOrientation.landscapeRight, then the preview Texture is rotated 90 degrees clockwise', + (WidgetTester tester) async { + // Set up test to use front camera, tell camera that handlesCropAndRotation is false, + // set camera initial device orientation to landscape right. + camera.proxy = getProxyForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, handlesCropAndRotation: false, - getUiOrientation: () => Future.value( - DeviceOrientation.landscapeRight)); - - // Get and create test front camera. - final List availableCameras = - await camera.availableCameras(); - expect(availableCameras.length, 1); - await camera.createCameraWithSettings( - availableCameras.first, testMediaSettings); - - // Put camera preview in widget tree. - await tester.pumpWidget(camera.buildPreview(cameraId)); - - // Verify Texture is rotated by ((90 - 270 * 1 + 360) % 360) - 90 = 90 degrees. - const int expectedQuarterTurns = _90DegreesClockwise; - final RotatedBox rotatedBox = - tester.widget(find.byType(RotatedBox)); - expect(rotatedBox.child, isA()); - expect((rotatedBox.child! as Texture).textureId, cameraId); - expect(rotatedBox.quarterTurns, expectedQuarterTurns, + getUiOrientation: () async => _serializeDeviceOrientation( + DeviceOrientation.landscapeRight, + ), + ); + + // Get and create test front camera. + final List availableCameras = + await camera.availableCameras(); + expect(availableCameras.length, 1); + await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); + + // Put camera preview in widget tree. + await tester.pumpWidget(camera.buildPreview(cameraId)); + + // Verify Texture is rotated by ((90 - 270 * 1 + 360) % 360) - 90 = 90 degrees. + const int expectedQuarterTurns = _90DegreesClockwise; + final RotatedBox rotatedBox = tester.widget( + find.byType(RotatedBox), + ); + expect(rotatedBox.child, isA()); + expect((rotatedBox.child! as Texture).textureId, cameraId); + expect( + rotatedBox.quarterTurns, + expectedQuarterTurns, reason: getExpectedRotationTestFailureReason( - expectedQuarterTurns, rotatedBox.quarterTurns)); - }); + expectedQuarterTurns, + rotatedBox.quarterTurns, + ), + ); + }, + ); testWidgets( - 'initial device orientation fixed to DeviceOrientation.portraitDown, then the preview Texture is rotated 270 degrees clockwise', - (WidgetTester tester) async { - // Set up test to use front camera, tell camera that handlesCropAndRotation is false, - // set camera initial device orientation to portrait down. - camera.proxy = getProxyForCreatingTestCamera( + 'initial device orientation fixed to DeviceOrientation.portraitDown, then the preview Texture is rotated 270 degrees clockwise', + (WidgetTester tester) async { + // Set up test to use front camera, tell camera that handlesCropAndRotation is false, + // set camera initial device orientation to portrait down. + camera.proxy = getProxyForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, handlesCropAndRotation: false, - getUiOrientation: () => Future.value( - DeviceOrientation.portraitDown)); - - // Get and create test front camera. - final List availableCameras = - await camera.availableCameras(); - expect(availableCameras.length, 1); - await camera.createCameraWithSettings( - availableCameras.first, testMediaSettings); - - // Put camera preview in widget tree. - await tester.pumpWidget(camera.buildPreview(cameraId)); - - // Verify Texture is rotated by ((270 - 180 * 1 + 360) % 360) - 180 = -90 degrees clockwise = 90 degrees counterclockwise = 270 degrees. - const int expectedQuarterTurns = _270DegreesClockwise; - final RotatedBox rotatedBox = - tester.widget(find.byType(RotatedBox)); - final int clockwiseQuarterTurns = rotatedBox.quarterTurns + 4; - expect(rotatedBox.child, isA()); - expect((rotatedBox.child! as Texture).textureId, cameraId); - expect(clockwiseQuarterTurns, expectedQuarterTurns, + getUiOrientation: () async => + _serializeDeviceOrientation(DeviceOrientation.portraitDown), + ); + + // Get and create test front camera. + final List availableCameras = + await camera.availableCameras(); + expect(availableCameras.length, 1); + await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); + + // Put camera preview in widget tree. + await tester.pumpWidget(camera.buildPreview(cameraId)); + + // Verify Texture is rotated by ((270 - 180 * 1 + 360) % 360) - 180 = -90 degrees clockwise = 90 degrees counterclockwise = 270 degrees. + const int expectedQuarterTurns = _270DegreesClockwise; + final RotatedBox rotatedBox = tester.widget( + find.byType(RotatedBox), + ); + final int clockwiseQuarterTurns = rotatedBox.quarterTurns + 4; + expect(rotatedBox.child, isA()); + expect((rotatedBox.child! as Texture).textureId, cameraId); + expect( + clockwiseQuarterTurns, + expectedQuarterTurns, reason: getExpectedRotationTestFailureReason( - expectedQuarterTurns, rotatedBox.quarterTurns)); - }); + expectedQuarterTurns, + rotatedBox.quarterTurns, + ), + ); + }, + ); testWidgets( - 'initial device orientation fixed to DeviceOrientation.landscapeLeft, then the preview Texture is rotated 90 degrees clockwise', - (WidgetTester tester) async { - // Set up test to use front camera, tell camera that handlesCropAndRotation is false, - // set camera initial device orientation to landscape left. - camera.proxy = getProxyForCreatingTestCamera( + 'initial device orientation fixed to DeviceOrientation.landscapeLeft, then the preview Texture is rotated 90 degrees clockwise', + (WidgetTester tester) async { + // Set up test to use front camera, tell camera that handlesCropAndRotation is false, + // set camera initial device orientation to landscape left. + camera.proxy = getProxyForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, handlesCropAndRotation: false, - getUiOrientation: () => Future.value( - DeviceOrientation.landscapeLeft)); - - // Get and create test front camera. - final List availableCameras = - await camera.availableCameras(); - expect(availableCameras.length, 1); - await camera.createCameraWithSettings( - availableCameras.first, testMediaSettings); - - // Put camera preview in widget tree. - await tester.pumpWidget(camera.buildPreview(cameraId)); - - // Verify Texture is rotated by ((270 - 270 * 1 + 360) % 360) - 270 = -270 degrees clockwise = 270 degrees counterclockwise = 90 degrees. - const int expectedQuarterTurns = _90DegreesClockwise; - final RotatedBox rotatedBox = - tester.widget(find.byType(RotatedBox)); - final int clockwiseQuarterTurns = rotatedBox.quarterTurns + 4; - expect(rotatedBox.child, isA()); - expect((rotatedBox.child! as Texture).textureId, cameraId); - expect(clockwiseQuarterTurns, expectedQuarterTurns, + getUiOrientation: () async => _serializeDeviceOrientation( + DeviceOrientation.landscapeLeft, + ), + ); + + // Get and create test front camera. + final List availableCameras = + await camera.availableCameras(); + expect(availableCameras.length, 1); + await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); + + // Put camera preview in widget tree. + await tester.pumpWidget(camera.buildPreview(cameraId)); + + // Verify Texture is rotated by ((270 - 270 * 1 + 360) % 360) - 270 = -270 degrees clockwise = 270 degrees counterclockwise = 90 degrees. + const int expectedQuarterTurns = _90DegreesClockwise; + final RotatedBox rotatedBox = tester.widget( + find.byType(RotatedBox), + ); + final int clockwiseQuarterTurns = rotatedBox.quarterTurns + 4; + expect(rotatedBox.child, isA()); + expect((rotatedBox.child! as Texture).textureId, cameraId); + expect( + clockwiseQuarterTurns, + expectedQuarterTurns, reason: getExpectedRotationTestFailureReason( - expectedQuarterTurns, rotatedBox.quarterTurns)); - }); + expectedQuarterTurns, + rotatedBox.quarterTurns, + ), + ); + }, + ); }); testWidgets( - 'sensor orientation degrees is 90, camera is front facing, then the preview Texture rotates correctly as the device orientation rotates', - (WidgetTester tester) async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 3372; - - // Create and set up mock CameraSelector and mock ProcessCameraProvider for test front camera - // with sensor orientation degrees 90. - final MockCameraSelector mockFrontCameraSelector = MockCameraSelector(); - final MockCameraSelector Function(int cameraSelectorLensDirection) - proxyCreateCameraSelectorForFrontCamera = - createCameraSelectorForFrontCamera(mockFrontCameraSelector); - final MockProcessCameraProvider mockProcessCameraProviderForFrontCamera = - setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( - mockCameraSelector: mockFrontCameraSelector, - sensorRotationDegrees: 90); + 'sensor orientation degrees is 90, camera is front facing, then the preview Texture rotates correctly as the device orientation rotates', + (WidgetTester tester) async { + final AndroidCameraCameraX camera = AndroidCameraCameraX(); + const int cameraId = 3372; - // Media settings to create camera; irrelevant for test. - const MediaSettings testMediaSettings = MediaSettings(); + // Create and set up mock CameraSelector and mock ProcessCameraProvider for test front camera + // with sensor orientation degrees 90. + final MockCameraSelector mockFrontCameraSelector = MockCameraSelector(); + final MockCameraSelector Function({ + LensFacing? requireLensFacing, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) proxyCreateCameraSelectorForFrontCamera = + createCameraSelectorForFrontCamera(mockFrontCameraSelector); + final MockProcessCameraProvider + mockProcessCameraProviderForFrontCamera = + setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( + mockCameraSelector: mockFrontCameraSelector, + sensorRotationDegrees: 90, + ); - // Set up test to use front camera and tell camera that handlesCropAndRotation is false, - // set camera initial device orientation to landscape left. - camera.proxy = getProxyForCreatingTestCamera( + // Media settings to create camera; irrelevant for test. + const MediaSettings testMediaSettings = MediaSettings(); + + // Set up test to use front camera and tell camera that handlesCropAndRotation is false, + // set camera initial device orientation to landscape left. + camera.proxy = getProxyForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, handlesCropAndRotation: false, getUiOrientation: /* initial device orientation irrelevant for test */ - () => Future.value( - DeviceOrientation.landscapeLeft)); + () async => + _serializeDeviceOrientation(DeviceOrientation.landscapeLeft), + ); - // Get and create test front camera. - final List availableCameras = - await camera.availableCameras(); - expect(availableCameras.length, 1); - await camera.createCameraWithSettings( - availableCameras.first, testMediaSettings); - - // Calculated according to: - // ((90 - currentDeviceOrientation * 1 + 360) % 360) - currentDeviceOrientation. - final Map expectedRotationPerDeviceOrientation = - { - DeviceOrientation.portraitUp: _90DegreesClockwise, - DeviceOrientation.landscapeRight: _270DegreesClockwise, - DeviceOrientation.portraitDown: _90DegreesClockwise, - DeviceOrientation.landscapeLeft: _270DegreesClockwise, - }; + // Get and create test front camera. + final List availableCameras = + await camera.availableCameras(); + expect(availableCameras.length, 1); + await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); + + // Calculated according to: + // ((90 - currentDeviceOrientation * 1 + 360) % 360) - currentDeviceOrientation. + final Map expectedRotationPerDeviceOrientation = + { + DeviceOrientation.portraitUp: _90DegreesClockwise, + DeviceOrientation.landscapeRight: _270DegreesClockwise, + DeviceOrientation.portraitDown: _90DegreesClockwise, + DeviceOrientation.landscapeLeft: _270DegreesClockwise, + }; - // Put camera preview in widget tree. - await tester.pumpWidget(camera.buildPreview(cameraId)); + // Put camera preview in widget tree. + await tester.pumpWidget(camera.buildPreview(cameraId)); - for (final DeviceOrientation currentDeviceOrientation - in expectedRotationPerDeviceOrientation.keys) { - final DeviceOrientationChangedEvent testEvent = - DeviceOrientationChangedEvent(currentDeviceOrientation); - DeviceOrientationManager.deviceOrientationChangedStreamController - .add(testEvent); - - await tester.pumpAndSettle(); - - // Verify Texture is rotated by expected clockwise degrees. - final int expectedQuarterTurns = - expectedRotationPerDeviceOrientation[currentDeviceOrientation]!; - final RotatedBox rotatedBox = - tester.widget(find.byType(RotatedBox)); - final int clockwiseQuarterTurns = rotatedBox.quarterTurns < 0 - ? rotatedBox.quarterTurns + 4 - : rotatedBox.quarterTurns; - expect(rotatedBox.child, isA()); - expect((rotatedBox.child! as Texture).textureId, cameraId); - expect(clockwiseQuarterTurns, expectedQuarterTurns, + for (final DeviceOrientation currentDeviceOrientation + in expectedRotationPerDeviceOrientation.keys) { + final DeviceOrientationChangedEvent testEvent = + DeviceOrientationChangedEvent(currentDeviceOrientation); + AndroidCameraCameraX.deviceOrientationChangedStreamController.add( + testEvent, + ); + + await tester.pumpAndSettle(); + + // Verify Texture is rotated by expected clockwise degrees. + final int expectedQuarterTurns = + expectedRotationPerDeviceOrientation[currentDeviceOrientation]!; + final RotatedBox rotatedBox = tester.widget( + find.byType(RotatedBox), + ); + final int clockwiseQuarterTurns = rotatedBox.quarterTurns < 0 + ? rotatedBox.quarterTurns + 4 + : rotatedBox.quarterTurns; + expect(rotatedBox.child, isA()); + expect((rotatedBox.child! as Texture).textureId, cameraId); + expect( + clockwiseQuarterTurns, + expectedQuarterTurns, reason: - 'When the device orientation is $currentDeviceOrientation, expected the preview to be rotated by $expectedQuarterTurns quarter turns (which is ${expectedQuarterTurns * 90} degrees clockwise) but instead was rotated ${rotatedBox.quarterTurns} quarter turns.'); - } + 'When the device orientation is $currentDeviceOrientation, expected the preview to be rotated by $expectedQuarterTurns quarter turns (which is ${expectedQuarterTurns * 90} degrees clockwise) but instead was rotated ${rotatedBox.quarterTurns} quarter turns.', + ); + } - await DeviceOrientationManager.deviceOrientationChangedStreamController - .close(); - }); + await AndroidCameraCameraX.deviceOrientationChangedStreamController + .close(); + }, + ); // Test the preview rotation responds to the two most common sensor orientations for Android phone cameras; see // https://developer.android.com/media/camera/camera2/camera-preview#camera_orientation. group( - 'initial device orientation is DeviceOrientation.landscapeLeft, camera is back facing,', - () { - late AndroidCameraCameraX camera; - late int cameraId; - late MockCameraSelector mockBackCameraSelector; - late MockCameraSelector Function(int cameraSelectorLensDirection) - proxyCreateCameraSelectorForBackCamera; - late MediaSettings testMediaSettings; - late DeviceOrientation testInitialDeviceOrientation; - - setUp(() { - camera = AndroidCameraCameraX(); - cameraId = 347; - - // Set test camera initial device orientation for test. - testInitialDeviceOrientation = DeviceOrientation.landscapeLeft; - - // Create and set up mock CameraSelector and mock ProcessCameraProvider for test back camera - // with sensor orientation degrees 270. - mockBackCameraSelector = MockCameraSelector(); - proxyCreateCameraSelectorForBackCamera = - createCameraSelectorForBackCamera(mockBackCameraSelector); - - testMediaSettings = const MediaSettings(); - }); - - testWidgets( + 'initial device orientation is DeviceOrientation.landscapeLeft, camera is back facing,', + () { + late AndroidCameraCameraX camera; + late int cameraId; + late MockCameraSelector mockBackCameraSelector; + late MockCameraSelector Function({ + LensFacing? requireLensFacing, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) proxyCreateCameraSelectorForBackCamera; + late MediaSettings testMediaSettings; + late DeviceOrientation testInitialDeviceOrientation; + + setUp(() { + camera = AndroidCameraCameraX(); + cameraId = 347; + + // Set test camera initial device orientation for test. + testInitialDeviceOrientation = DeviceOrientation.landscapeLeft; + + // Create and set up mock CameraSelector and mock ProcessCameraProvider for test back camera + // with sensor orientation degrees 270. + mockBackCameraSelector = MockCameraSelector(); + proxyCreateCameraSelectorForBackCamera = + createCameraSelectorForBackCamera(mockBackCameraSelector); + + testMediaSettings = const MediaSettings(); + }); + + testWidgets( 'sensor orientation degrees is 90, then the preview Texture is rotated 90 degrees clockwise', (WidgetTester tester) async { - // Create mock ProcessCameraProvider that will acknowledge that the test back camera with sensor orientation degrees - // 90 is available. - final MockProcessCameraProvider mockProcessCameraProviderForBackCamera = - setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( - mockCameraSelector: mockBackCameraSelector, - sensorRotationDegrees: 90); - - // Set up test to use back camera, tell camera that handlesCropAndRotation is false, - // set camera initial device orientation to landscape left. - camera.proxy = getProxyForCreatingTestCamera( - mockProcessCameraProvider: mockProcessCameraProviderForBackCamera, - createCameraSelector: proxyCreateCameraSelectorForBackCamera, - handlesCropAndRotation: false, - getUiOrientation: () => - Future.value(testInitialDeviceOrientation)); - - // Get and create test back camera. - final List availableCameras = - await camera.availableCameras(); - expect(availableCameras.length, 1); - await camera.createCameraWithSettings( - availableCameras.first, testMediaSettings); - - // Put camera preview in widget tree. - await tester.pumpWidget(camera.buildPreview(cameraId)); - - // Verify Texture is rotated by ((90 - 270 * -1 + 360) % 360) - 270 = -270 degrees clockwise = 270 degrees counterclockwise = 90 degrees clockwise. - const int expectedQuarterTurns = _90DegreesClockwise; - final RotatedBox rotatedBox = - tester.widget(find.byType(RotatedBox)); - final int clockwiseQuarterTurns = rotatedBox.quarterTurns + 4; - expect(rotatedBox.child, isA()); - expect((rotatedBox.child! as Texture).textureId, cameraId); - expect(clockwiseQuarterTurns, expectedQuarterTurns, - reason: getExpectedRotationTestFailureReason( - expectedQuarterTurns, rotatedBox.quarterTurns)); - }); - - testWidgets( + // Create mock ProcessCameraProvider that will acknowledge that the test back camera with sensor orientation degrees + // 90 is available. + final MockProcessCameraProvider + mockProcessCameraProviderForBackCamera = + setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( + mockCameraSelector: mockBackCameraSelector, + sensorRotationDegrees: 90, + ); + + // Set up test to use back camera, tell camera that handlesCropAndRotation is false, + // set camera initial device orientation to landscape left. + camera.proxy = getProxyForCreatingTestCamera( + mockProcessCameraProvider: mockProcessCameraProviderForBackCamera, + createCameraSelector: proxyCreateCameraSelectorForBackCamera, + handlesCropAndRotation: false, + getUiOrientation: () async => + _serializeDeviceOrientation(testInitialDeviceOrientation), + ); + + // Get and create test back camera. + final List availableCameras = + await camera.availableCameras(); + expect(availableCameras.length, 1); + await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); + + // Put camera preview in widget tree. + await tester.pumpWidget(camera.buildPreview(cameraId)); + + // Verify Texture is rotated by ((90 - 270 * -1 + 360) % 360) - 270 = -270 degrees clockwise = 270 degrees counterclockwise = 90 degrees clockwise. + const int expectedQuarterTurns = _90DegreesClockwise; + final RotatedBox rotatedBox = tester.widget( + find.byType(RotatedBox), + ); + final int clockwiseQuarterTurns = rotatedBox.quarterTurns + 4; + expect(rotatedBox.child, isA()); + expect((rotatedBox.child! as Texture).textureId, cameraId); + expect( + clockwiseQuarterTurns, + expectedQuarterTurns, + reason: getExpectedRotationTestFailureReason( + expectedQuarterTurns, + rotatedBox.quarterTurns, + ), + ); + }, + ); + + testWidgets( 'sensor orientation degrees is 270, then the preview Texture is rotated 270 degrees clockwise', (WidgetTester tester) async { - // Create mock ProcessCameraProvider that will acknowledge that the test back camera with sensor orientation degrees - // 270 is available. - final MockProcessCameraProvider mockProcessCameraProviderForBackCamera = - setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( - mockCameraSelector: mockBackCameraSelector, - sensorRotationDegrees: 270); - - // Set up test to use back camera, tell camera that handlesCropAndRotation is false, - // set camera initial device orientation to landscape left. - camera.proxy = getProxyForCreatingTestCamera( - mockProcessCameraProvider: mockProcessCameraProviderForBackCamera, - createCameraSelector: proxyCreateCameraSelectorForBackCamera, - handlesCropAndRotation: false, - getUiOrientation: () => - Future.value(testInitialDeviceOrientation)); - - // Get and create test back camera. - final List availableCameras = - await camera.availableCameras(); - expect(availableCameras.length, 1); - await camera.createCameraWithSettings( - availableCameras.first, testMediaSettings); - - // Put camera preview in widget tree. - await tester.pumpWidget(camera.buildPreview(cameraId)); - - // Verify Texture is rotated by ((270 - 270 * -1 + 360) % 360) - 270 = -90 degrees clockwise = 90 degrees counterclockwise = 270 degrees clockwise. - const int expectedQuarterTurns = _270DegreesClockwise; - final RotatedBox rotatedBox = - tester.widget(find.byType(RotatedBox)); - final int clockwiseQuarterTurns = rotatedBox.quarterTurns + 4; - expect(rotatedBox.child, isA()); - expect((rotatedBox.child! as Texture).textureId, cameraId); - expect(clockwiseQuarterTurns, expectedQuarterTurns, - reason: getExpectedRotationTestFailureReason( - expectedQuarterTurns, rotatedBox.quarterTurns)); - }); - }); + // Create mock ProcessCameraProvider that will acknowledge that the test back camera with sensor orientation degrees + // 270 is available. + final MockProcessCameraProvider + mockProcessCameraProviderForBackCamera = + setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( + mockCameraSelector: mockBackCameraSelector, + sensorRotationDegrees: 270, + ); + + // Set up test to use back camera, tell camera that handlesCropAndRotation is false, + // set camera initial device orientation to landscape left. + camera.proxy = getProxyForCreatingTestCamera( + mockProcessCameraProvider: mockProcessCameraProviderForBackCamera, + createCameraSelector: proxyCreateCameraSelectorForBackCamera, + handlesCropAndRotation: false, + getUiOrientation: () async => + _serializeDeviceOrientation(testInitialDeviceOrientation), + ); + + // Get and create test back camera. + final List availableCameras = + await camera.availableCameras(); + expect(availableCameras.length, 1); + await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); + + // Put camera preview in widget tree. + await tester.pumpWidget(camera.buildPreview(cameraId)); + + // Verify Texture is rotated by ((270 - 270 * -1 + 360) % 360) - 270 = -90 degrees clockwise = 90 degrees counterclockwise = 270 degrees clockwise. + const int expectedQuarterTurns = _270DegreesClockwise; + final RotatedBox rotatedBox = tester.widget( + find.byType(RotatedBox), + ); + final int clockwiseQuarterTurns = rotatedBox.quarterTurns + 4; + expect(rotatedBox.child, isA()); + expect((rotatedBox.child! as Texture).textureId, cameraId); + expect( + clockwiseQuarterTurns, + expectedQuarterTurns, + reason: getExpectedRotationTestFailureReason( + expectedQuarterTurns, + rotatedBox.quarterTurns, + ), + ); + }, + ); + }, + ); // Test the preview rotation responds to the camera being front or back facing: group( - 'initial device orientation is DeviceOrientation.landscapeRight, sensor orientation degrees is 90,', - () { - late AndroidCameraCameraX camera; - late int cameraId; - late MediaSettings testMediaSettings; - late DeviceOrientation testInitialDeviceOrientation; - late int testSensorOrientation; - - setUp(() { - camera = AndroidCameraCameraX(); - cameraId = 317; - - // Set test camera initial device orientation and sensor orientation for test. - testInitialDeviceOrientation = DeviceOrientation.landscapeRight; - testSensorOrientation = 90; - - // Media settings to create camera; irrelevant for test. - testMediaSettings = const MediaSettings(); - }); - - testWidgets( + 'initial device orientation is DeviceOrientation.landscapeRight, sensor orientation degrees is 90,', + () { + late AndroidCameraCameraX camera; + late int cameraId; + late MediaSettings testMediaSettings; + late DeviceOrientation testInitialDeviceOrientation; + late int testSensorOrientation; + + setUp(() { + camera = AndroidCameraCameraX(); + cameraId = 317; + + // Set test camera initial device orientation and sensor orientation for test. + testInitialDeviceOrientation = DeviceOrientation.landscapeRight; + testSensorOrientation = 90; + + // Media settings to create camera; irrelevant for test. + testMediaSettings = const MediaSettings(); + }); + + testWidgets( 'camera is front facing, then the preview Texture is rotated 270 degrees clockwise', (WidgetTester tester) async { - // Set up test front camera with sensor orientation degrees 90. - final MockCameraSelector mockFrontCameraSelector = MockCameraSelector(); - final MockProcessCameraProvider mockProcessCameraProvider = - setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( - mockCameraSelector: mockFrontCameraSelector, - sensorRotationDegrees: testSensorOrientation); - - // Set up front camera selection and initial device orientation as landscape right. - final MockCameraSelector Function(int cameraSelectorLensDirection) - proxyCreateCameraSelectorForFrontCamera = - createCameraSelectorForFrontCamera(mockFrontCameraSelector); - camera.proxy = getProxyForCreatingTestCamera( - mockProcessCameraProvider: mockProcessCameraProvider, - createCameraSelector: proxyCreateCameraSelectorForFrontCamera, - handlesCropAndRotation: false, - getUiOrientation: () => - Future.value(testInitialDeviceOrientation)); - - // Get and create test camera. - final List availableCameras = - await camera.availableCameras(); - expect(availableCameras.length, 1); - await camera.createCameraWithSettings( - availableCameras.first, testMediaSettings); - - // Put camera preview in widget tree. - await tester.pumpWidget(camera.buildPreview(cameraId)); - - // Verify Texture is rotated by ((90 - 90 * 1 + 360) % 360) - 90 = -90 degrees clockwise = 90 degrees counterclockwise = 270 degrees clockwise. - const int expectedQuarterTurns = _270DegreesClockwise; - final RotatedBox rotatedBox = - tester.widget(find.byType(RotatedBox)); - final int clockwiseQuarterTurns = rotatedBox.quarterTurns + 4; - expect(rotatedBox.child, isA()); - expect((rotatedBox.child! as Texture).textureId, cameraId); - expect(clockwiseQuarterTurns, expectedQuarterTurns, - reason: getExpectedRotationTestFailureReason( - expectedQuarterTurns, rotatedBox.quarterTurns)); - }); - - testWidgets( + // Set up test front camera with sensor orientation degrees 90. + final MockCameraSelector mockFrontCameraSelector = + MockCameraSelector(); + final MockProcessCameraProvider mockProcessCameraProvider = + setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( + mockCameraSelector: mockFrontCameraSelector, + sensorRotationDegrees: testSensorOrientation, + ); + + // Set up front camera selection and initial device orientation as landscape right. + final MockCameraSelector Function({ + LensFacing? requireLensFacing, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) proxyCreateCameraSelectorForFrontCamera = + createCameraSelectorForFrontCamera(mockFrontCameraSelector); + camera.proxy = getProxyForCreatingTestCamera( + mockProcessCameraProvider: mockProcessCameraProvider, + createCameraSelector: proxyCreateCameraSelectorForFrontCamera, + handlesCropAndRotation: false, + getUiOrientation: () async => + _serializeDeviceOrientation(testInitialDeviceOrientation), + ); + + // Get and create test camera. + final List availableCameras = + await camera.availableCameras(); + expect(availableCameras.length, 1); + await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); + + // Put camera preview in widget tree. + await tester.pumpWidget(camera.buildPreview(cameraId)); + + // Verify Texture is rotated by ((90 - 90 * 1 + 360) % 360) - 90 = -90 degrees clockwise = 90 degrees counterclockwise = 270 degrees clockwise. + const int expectedQuarterTurns = _270DegreesClockwise; + final RotatedBox rotatedBox = tester.widget( + find.byType(RotatedBox), + ); + final int clockwiseQuarterTurns = rotatedBox.quarterTurns + 4; + expect(rotatedBox.child, isA()); + expect((rotatedBox.child! as Texture).textureId, cameraId); + expect( + clockwiseQuarterTurns, + expectedQuarterTurns, + reason: getExpectedRotationTestFailureReason( + expectedQuarterTurns, + rotatedBox.quarterTurns, + ), + ); + }, + ); + + testWidgets( 'camera is back facing, then the preview Texture is rotated 90 degrees clockwise', (WidgetTester tester) async { - // Set up test front camera with sensor orientation degrees 90. - final MockCameraSelector mockBackCameraSelector = MockCameraSelector(); - final MockProcessCameraProvider mockProcessCameraProvider = - setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( - mockCameraSelector: mockBackCameraSelector, - sensorRotationDegrees: testSensorOrientation); - - // Set up front camera selection and initial device orientation as landscape right. - final MockCameraSelector Function(int cameraSelectorLensDirection) - proxyCreateCameraSelectorForFrontCamera = - createCameraSelectorForBackCamera(mockBackCameraSelector); - camera.proxy = getProxyForCreatingTestCamera( - mockProcessCameraProvider: mockProcessCameraProvider, - createCameraSelector: proxyCreateCameraSelectorForFrontCamera, - handlesCropAndRotation: false, - getUiOrientation: () => - Future.value(testInitialDeviceOrientation)); - - // Get and create test camera. - final List availableCameras = - await camera.availableCameras(); - expect(availableCameras.length, 1); - await camera.createCameraWithSettings( - availableCameras.first, testMediaSettings); - - // Put camera preview in widget tree. - await tester.pumpWidget(camera.buildPreview(cameraId)); - - // Verify Texture is rotated by ((90 - 90 * -1 + 360) % 360) - 90 = 90 degrees clockwise. - const int expectedQuarterTurns = _90DegreesClockwise; - final RotatedBox rotatedBox = - tester.widget(find.byType(RotatedBox)); - expect(rotatedBox.child, isA()); - expect((rotatedBox.child! as Texture).textureId, cameraId); - expect(rotatedBox.quarterTurns, expectedQuarterTurns, - reason: getExpectedRotationTestFailureReason( - expectedQuarterTurns, rotatedBox.quarterTurns)); - }); - }); + // Set up test front camera with sensor orientation degrees 90. + final MockCameraSelector mockBackCameraSelector = + MockCameraSelector(); + final MockProcessCameraProvider mockProcessCameraProvider = + setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( + mockCameraSelector: mockBackCameraSelector, + sensorRotationDegrees: testSensorOrientation, + ); + + // Set up front camera selection and initial device orientation as landscape right. + final MockCameraSelector Function({ + LensFacing? requireLensFacing, + // ignore: non_constant_identifier_names + BinaryMessenger? pigeon_binaryMessenger, + // ignore: non_constant_identifier_names + PigeonInstanceManager? pigeon_instanceManager, + }) proxyCreateCameraSelectorForFrontCamera = + createCameraSelectorForBackCamera(mockBackCameraSelector); + camera.proxy = getProxyForCreatingTestCamera( + mockProcessCameraProvider: mockProcessCameraProvider, + createCameraSelector: proxyCreateCameraSelectorForFrontCamera, + handlesCropAndRotation: false, + getUiOrientation: () async => + _serializeDeviceOrientation(testInitialDeviceOrientation), + ); + + // Get and create test camera. + final List availableCameras = + await camera.availableCameras(); + expect(availableCameras.length, 1); + await camera.createCameraWithSettings( + availableCameras.first, + testMediaSettings, + ); + + // Put camera preview in widget tree. + await tester.pumpWidget(camera.buildPreview(cameraId)); + + // Verify Texture is rotated by ((90 - 90 * -1 + 360) % 360) - 90 = 90 degrees clockwise. + const int expectedQuarterTurns = _90DegreesClockwise; + final RotatedBox rotatedBox = tester.widget( + find.byType(RotatedBox), + ); + expect(rotatedBox.child, isA()); + expect((rotatedBox.child! as Texture).textureId, cameraId); + expect( + rotatedBox.quarterTurns, + expectedQuarterTurns, + reason: getExpectedRotationTestFailureReason( + expectedQuarterTurns, + rotatedBox.quarterTurns, + ), + ); + }, + ); + }, + ); }); } + +String _serializeDeviceOrientation(DeviceOrientation orientation) { + switch (orientation) { + case DeviceOrientation.portraitUp: + return 'PORTRAIT_UP'; + case DeviceOrientation.landscapeLeft: + return 'LANDSCAPE_LEFT'; + case DeviceOrientation.portraitDown: + return 'PORTRAIT_DOWN'; + case DeviceOrientation.landscapeRight: + return 'LANDSCAPE_RIGHT'; + } +} diff --git a/packages/camera/camera_android_camerax/test/preview_test.dart b/packages/camera/camera_android_camerax/test/preview_test.dart deleted file mode 100644 index 4800b045e2db..000000000000 --- a/packages/camera/camera_android_camerax/test/preview_test.dart +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camerax_library.g.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:camera_android_camerax/src/preview.dart'; -import 'package:camera_android_camerax/src/resolution_selector.dart'; -import 'package:camera_android_camerax/src/surface.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'preview_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks( - [TestInstanceManagerHostApi, TestPreviewHostApi, ResolutionSelector]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('Preview', () { - tearDown(() => TestPreviewHostApi.setup(null)); - - test('detached create does not call create on the Java side', () async { - final MockTestPreviewHostApi mockApi = MockTestPreviewHostApi(); - TestPreviewHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - Preview.detached( - instanceManager: instanceManager, - initialTargetRotation: Surface.rotation90, - resolutionSelector: MockResolutionSelector(), - ); - - verifyNever(mockApi.create(argThat(isA()), argThat(isA()), - argThat(isA()))); - }, skip: 'Flaky test: https://github.com/flutter/flutter/issues/164132'); - - test('create calls create on the Java side', () async { - final MockTestPreviewHostApi mockApi = MockTestPreviewHostApi(); - TestPreviewHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - const int targetRotation = Surface.rotation90; - final MockResolutionSelector mockResolutionSelector = - MockResolutionSelector(); - const int mockResolutionSelectorId = 24; - - instanceManager.addHostCreatedInstance( - mockResolutionSelector, mockResolutionSelectorId, - onCopy: (ResolutionSelector original) { - return MockResolutionSelector(); - }); - - Preview( - instanceManager: instanceManager, - initialTargetRotation: targetRotation, - resolutionSelector: mockResolutionSelector, - ); - - verify(mockApi.create( - argThat(isA()), - argThat(equals(targetRotation)), - argThat(equals(mockResolutionSelectorId)))); - }); - - test( - 'setTargetRotation makes call to set target rotation for Preview instance', - () async { - final MockTestPreviewHostApi mockApi = MockTestPreviewHostApi(); - TestPreviewHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - const int targetRotation = Surface.rotation180; - final Preview preview = Preview.detached( - instanceManager: instanceManager, - ); - instanceManager.addHostCreatedInstance( - preview, - 0, - onCopy: (_) => Preview.detached(instanceManager: instanceManager), - ); - - await preview.setTargetRotation(targetRotation); - - verify(mockApi.setTargetRotation( - instanceManager.getIdentifier(preview), targetRotation)); - }); - - test( - 'setSurfaceProvider makes call to set surface provider for preview instance', - () async { - final MockTestPreviewHostApi mockApi = MockTestPreviewHostApi(); - TestPreviewHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - const int textureId = 8; - final Preview preview = Preview.detached( - instanceManager: instanceManager, - ); - instanceManager.addHostCreatedInstance( - preview, - 0, - onCopy: (_) => Preview.detached(), - ); - - when(mockApi.setSurfaceProvider(instanceManager.getIdentifier(preview))) - .thenReturn(textureId); - expect(await preview.setSurfaceProvider(), equals(textureId)); - - verify( - mockApi.setSurfaceProvider(instanceManager.getIdentifier(preview))); - }); - - test( - 'releaseFlutterSurfaceTexture makes call to release flutter surface texture entry', - () async { - final MockTestPreviewHostApi mockApi = MockTestPreviewHostApi(); - TestPreviewHostApi.setup(mockApi); - - final Preview preview = Preview.detached(); - - preview.releaseFlutterSurfaceTexture(); - - verify(mockApi.releaseFlutterSurfaceTexture()); - }); - - test( - 'getResolutionInfo makes call to get resolution information for preview instance', - () async { - final MockTestPreviewHostApi mockApi = MockTestPreviewHostApi(); - TestPreviewHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final Preview preview = Preview.detached( - instanceManager: instanceManager, - ); - const int resolutionWidth = 10; - const int resolutionHeight = 60; - final ResolutionInfo testResolutionInfo = - ResolutionInfo(width: resolutionWidth, height: resolutionHeight); - - instanceManager.addHostCreatedInstance( - preview, - 0, - onCopy: (_) => Preview.detached(), - ); - - when(mockApi.getResolutionInfo(instanceManager.getIdentifier(preview))) - .thenReturn(testResolutionInfo); - - final ResolutionInfo previewResolutionInfo = - await preview.getResolutionInfo(); - expect(previewResolutionInfo.width, equals(resolutionWidth)); - expect(previewResolutionInfo.height, equals(resolutionHeight)); - - verify(mockApi.getResolutionInfo(instanceManager.getIdentifier(preview))); - }); - - test( - 'surfaceProducerHandlesCropAndRotation makes call to check if Android surface producer automatically corrects camera preview rotation', - () async { - final MockTestPreviewHostApi mockApi = MockTestPreviewHostApi(); - TestPreviewHostApi.setup(mockApi); - final Preview preview = Preview.detached(); - - when(mockApi.surfaceProducerHandlesCropAndRotation()).thenReturn(true); - - expect(await preview.surfaceProducerHandlesCropAndRotation(), true); - - verify(mockApi.surfaceProducerHandlesCropAndRotation()); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/preview_test.mocks.dart b/packages/camera/camera_android_camerax/test/preview_test.mocks.dart deleted file mode 100644 index d8b7a21e44bb..000000000000 --- a/packages/camera/camera_android_camerax/test/preview_test.mocks.dart +++ /dev/null @@ -1,150 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/preview_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i2; -import 'package:camera_android_camerax/src/resolution_selector.dart' as _i4; -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i3; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -class _FakeResolutionInfo_0 extends _i1.SmartFake - implements _i2.ResolutionInfo { - _FakeResolutionInfo_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i3.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [TestPreviewHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestPreviewHostApi extends _i1.Mock - implements _i3.TestPreviewHostApi { - MockTestPreviewHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void create( - int? identifier, - int? rotation, - int? resolutionSelectorId, - ) => - super.noSuchMethod( - Invocation.method( - #create, - [ - identifier, - rotation, - resolutionSelectorId, - ], - ), - returnValueForMissingStub: null, - ); - - @override - int setSurfaceProvider(int? identifier) => (super.noSuchMethod( - Invocation.method( - #setSurfaceProvider, - [identifier], - ), - returnValue: 0, - ) as int); - - @override - void releaseFlutterSurfaceTexture() => super.noSuchMethod( - Invocation.method( - #releaseFlutterSurfaceTexture, - [], - ), - returnValueForMissingStub: null, - ); - - @override - _i2.ResolutionInfo getResolutionInfo(int? identifier) => (super.noSuchMethod( - Invocation.method( - #getResolutionInfo, - [identifier], - ), - returnValue: _FakeResolutionInfo_0( - this, - Invocation.method( - #getResolutionInfo, - [identifier], - ), - ), - ) as _i2.ResolutionInfo); - - @override - void setTargetRotation( - int? identifier, - int? rotation, - ) => - super.noSuchMethod( - Invocation.method( - #setTargetRotation, - [ - identifier, - rotation, - ], - ), - returnValueForMissingStub: null, - ); - - @override - bool surfaceProducerHandlesCropAndRotation() => (super.noSuchMethod( - Invocation.method( - #surfaceProducerHandlesCropAndRotation, - [], - ), - returnValue: false, - ) as bool); -} - -/// A class which mocks [ResolutionSelector]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockResolutionSelector extends _i1.Mock - implements _i4.ResolutionSelector { - MockResolutionSelector() { - _i1.throwOnMissingStub(this); - } -} diff --git a/packages/camera/camera_android_camerax/test/process_camera_provider_test.dart b/packages/camera/camera_android_camerax/test/process_camera_provider_test.dart deleted file mode 100644 index a497956da5f4..000000000000 --- a/packages/camera/camera_android_camerax/test/process_camera_provider_test.dart +++ /dev/null @@ -1,236 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camera.dart'; -import 'package:camera_android_camerax/src/camera_info.dart'; -import 'package:camera_android_camerax/src/camera_selector.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:camera_android_camerax/src/process_camera_provider.dart'; -import 'package:camera_android_camerax/src/use_case.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'process_camera_provider_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks( - [TestInstanceManagerHostApi, TestProcessCameraProviderHostApi]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('ProcessCameraProvider', () { - tearDown(() => TestProcessCameraProviderHostApi.setup(null)); - - test('getInstanceTest', () async { - final MockTestProcessCameraProviderHostApi mockApi = - MockTestProcessCameraProviderHostApi(); - TestProcessCameraProviderHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final ProcessCameraProvider processCameraProvider = - ProcessCameraProvider.detached( - instanceManager: instanceManager, - ); - - instanceManager.addHostCreatedInstance( - processCameraProvider, - 0, - onCopy: (_) => ProcessCameraProvider.detached(), - ); - - when(mockApi.getInstance()).thenAnswer((_) async => 0); - expect( - await ProcessCameraProvider.getInstance( - instanceManager: instanceManager), - equals(processCameraProvider)); - verify(mockApi.getInstance()); - }); - - test('getAvailableCameraInfosTest', () async { - final MockTestProcessCameraProviderHostApi mockApi = - MockTestProcessCameraProviderHostApi(); - TestProcessCameraProviderHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final ProcessCameraProvider processCameraProvider = - ProcessCameraProvider.detached( - instanceManager: instanceManager, - ); - - instanceManager.addHostCreatedInstance( - processCameraProvider, - 0, - onCopy: (_) => ProcessCameraProvider.detached(), - ); - final CameraInfo fakeAvailableCameraInfo = - CameraInfo.detached(instanceManager: instanceManager); - instanceManager.addHostCreatedInstance( - fakeAvailableCameraInfo, - 1, - onCopy: (_) => CameraInfo.detached(), - ); - - when(mockApi.getAvailableCameraInfos(0)).thenReturn([1]); - expect(await processCameraProvider.getAvailableCameraInfos(), - equals([fakeAvailableCameraInfo])); - verify(mockApi.getAvailableCameraInfos(0)); - }); - - test('bindToLifecycleTest', () async { - final MockTestProcessCameraProviderHostApi mockApi = - MockTestProcessCameraProviderHostApi(); - TestProcessCameraProviderHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final ProcessCameraProvider processCameraProvider = - ProcessCameraProvider.detached( - instanceManager: instanceManager, - ); - final CameraSelector fakeCameraSelector = - CameraSelector.detached(instanceManager: instanceManager); - final UseCase fakeUseCase = - UseCase.detached(instanceManager: instanceManager); - final Camera fakeCamera = - Camera.detached(instanceManager: instanceManager); - - instanceManager.addHostCreatedInstance( - processCameraProvider, - 0, - onCopy: (_) => ProcessCameraProvider.detached(), - ); - instanceManager.addHostCreatedInstance( - fakeCameraSelector, - 1, - onCopy: (_) => CameraSelector.detached(), - ); - instanceManager.addHostCreatedInstance( - fakeUseCase, - 2, - onCopy: (_) => UseCase.detached(), - ); - instanceManager.addHostCreatedInstance( - fakeCamera, - 3, - onCopy: (_) => Camera.detached(), - ); - - when(mockApi.bindToLifecycle(0, 1, [2])).thenReturn(3); - expect( - await processCameraProvider - .bindToLifecycle(fakeCameraSelector, [fakeUseCase]), - equals(fakeCamera)); - verify(mockApi.bindToLifecycle(0, 1, [2])); - }); - - test('isBoundTest', () async { - final MockTestProcessCameraProviderHostApi mockApi = - MockTestProcessCameraProviderHostApi(); - TestProcessCameraProviderHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final ProcessCameraProvider processCameraProvider = - ProcessCameraProvider.detached( - instanceManager: instanceManager, - ); - final UseCase fakeUseCase = - UseCase.detached(instanceManager: instanceManager); - - instanceManager.addHostCreatedInstance( - processCameraProvider, - 0, - onCopy: (_) => ProcessCameraProvider.detached(), - ); - instanceManager.addHostCreatedInstance( - fakeUseCase, - 27, - onCopy: (_) => UseCase.detached(), - ); - - when(mockApi.isBound(0, 27)).thenReturn(true); - - expect(await processCameraProvider.isBound(fakeUseCase), isTrue); - verify(mockApi.isBound(0, 27)); - }); - - test('unbindTest', () async { - final MockTestProcessCameraProviderHostApi mockApi = - MockTestProcessCameraProviderHostApi(); - TestProcessCameraProviderHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final ProcessCameraProvider processCameraProvider = - ProcessCameraProvider.detached( - instanceManager: instanceManager, - ); - final UseCase fakeUseCase = - UseCase.detached(instanceManager: instanceManager); - - instanceManager.addHostCreatedInstance( - processCameraProvider, - 0, - onCopy: (_) => ProcessCameraProvider.detached(), - ); - instanceManager.addHostCreatedInstance( - fakeUseCase, - 1, - onCopy: (_) => UseCase.detached(), - ); - - processCameraProvider.unbind([fakeUseCase]); - verify(mockApi.unbind(0, [1])); - }); - - test('unbindAll unbinds UseCases', () async { - final MockTestProcessCameraProviderHostApi mockApi = - MockTestProcessCameraProviderHostApi(); - TestProcessCameraProviderHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final ProcessCameraProvider processCameraProvider = - ProcessCameraProvider.detached( - instanceManager: instanceManager, - ); - - instanceManager.addHostCreatedInstance( - processCameraProvider, - 0, - onCopy: (_) => ProcessCameraProvider.detached(), - ); - - processCameraProvider.unbindAll(); - verify(mockApi.unbindAll(0)); - }); - - test('flutterApiCreateTest', () { - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final ProcessCameraProviderFlutterApiImpl flutterApi = - ProcessCameraProviderFlutterApiImpl( - instanceManager: instanceManager, - ); - - flutterApi.create(0); - - expect(instanceManager.getInstanceWithWeakReference(0), - isA()); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/process_camera_provider_test.mocks.dart b/packages/camera/camera_android_camerax/test/process_camera_provider_test.mocks.dart deleted file mode 100644 index ec1686cd5f54..000000000000 --- a/packages/camera/camera_android_camerax/test/process_camera_provider_test.mocks.dart +++ /dev/null @@ -1,129 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/process_camera_provider_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i3; - -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [TestProcessCameraProviderHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestProcessCameraProviderHostApi extends _i1.Mock - implements _i2.TestProcessCameraProviderHostApi { - MockTestProcessCameraProviderHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - _i3.Future getInstance() => (super.noSuchMethod( - Invocation.method( - #getInstance, - [], - ), - returnValue: _i3.Future.value(0), - ) as _i3.Future); - - @override - List getAvailableCameraInfos(int? identifier) => (super.noSuchMethod( - Invocation.method( - #getAvailableCameraInfos, - [identifier], - ), - returnValue: [], - ) as List); - - @override - int bindToLifecycle( - int? identifier, - int? cameraSelectorIdentifier, - List? useCaseIds, - ) => - (super.noSuchMethod( - Invocation.method( - #bindToLifecycle, - [ - identifier, - cameraSelectorIdentifier, - useCaseIds, - ], - ), - returnValue: 0, - ) as int); - - @override - bool isBound( - int? identifier, - int? useCaseIdentifier, - ) => - (super.noSuchMethod( - Invocation.method( - #isBound, - [ - identifier, - useCaseIdentifier, - ], - ), - returnValue: false, - ) as bool); - - @override - void unbind( - int? identifier, - List? useCaseIds, - ) => - super.noSuchMethod( - Invocation.method( - #unbind, - [ - identifier, - useCaseIds, - ], - ), - returnValueForMissingStub: null, - ); - - @override - void unbindAll(int? identifier) => super.noSuchMethod( - Invocation.method( - #unbindAll, - [identifier], - ), - returnValueForMissingStub: null, - ); -} diff --git a/packages/camera/camera_android_camerax/test/quality_selector_test.dart b/packages/camera/camera_android_camerax/test/quality_selector_test.dart deleted file mode 100644 index bfaa568c254d..000000000000 --- a/packages/camera/camera_android_camerax/test/quality_selector_test.dart +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camera_info.dart'; -import 'package:camera_android_camerax/src/camerax_library.g.dart'; -import 'package:camera_android_camerax/src/fallback_strategy.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:camera_android_camerax/src/quality_selector.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'quality_selector_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([ - CameraInfo, - FallbackStrategy, - TestQualitySelectorHostApi, - TestInstanceManagerHostApi -]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - group('QualitySelector', () { - tearDown(() { - TestQualitySelectorHostApi.setup(null); - TestInstanceManagerHostApi.setup(null); - }); - - test('detached constructor does not make call to create on the Java side', - () { - final MockTestQualitySelectorHostApi mockApi = - MockTestQualitySelectorHostApi(); - TestQualitySelectorHostApi.setup(mockApi); - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - QualitySelector.detached( - qualityList: [ - VideoQualityData(quality: VideoQuality.UHD) - ], - fallbackStrategy: MockFallbackStrategy(), - instanceManager: instanceManager, - ); - - verifyNever(mockApi.create( - argThat(isA()), argThat(isA>()), argThat(isA()))); - }); - - test('single quality constructor calls create on the Java side', () { - final MockTestQualitySelectorHostApi mockApi = - MockTestQualitySelectorHostApi(); - TestQualitySelectorHostApi.setup(mockApi); - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - const VideoQuality videoQuality = VideoQuality.FHD; - final VideoQualityData quality = VideoQualityData(quality: videoQuality); - final FallbackStrategy fallbackStrategy = MockFallbackStrategy(); - const int fallbackStrategyIdentifier = 9; - - instanceManager.addHostCreatedInstance( - fallbackStrategy, - fallbackStrategyIdentifier, - onCopy: (_) => MockFallbackStrategy(), - ); - - final QualitySelector instance = QualitySelector.from( - quality: quality, - fallbackStrategy: fallbackStrategy, - instanceManager: instanceManager, - ); - - final VerificationResult verificationResult = verify(mockApi.create( - instanceManager.getIdentifier(instance), - captureAny, - fallbackStrategyIdentifier, - )); - final List videoQualityData = - verificationResult.captured.single as List; - expect(videoQualityData.length, equals(1)); - expect(videoQualityData.first!.quality, equals(videoQuality)); - }); - - test('quality list constructor calls create on the Java side', () { - final MockTestQualitySelectorHostApi mockApi = - MockTestQualitySelectorHostApi(); - TestQualitySelectorHostApi.setup(mockApi); - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final List qualityList = [ - VideoQualityData(quality: VideoQuality.FHD), - VideoQualityData(quality: VideoQuality.highest), - ]; - - final FallbackStrategy fallbackStrategy = MockFallbackStrategy(); - - const int fallbackStrategyIdentifier = 9; - instanceManager.addHostCreatedInstance( - fallbackStrategy, - fallbackStrategyIdentifier, - onCopy: (_) => MockFallbackStrategy(), - ); - - final QualitySelector instance = QualitySelector.fromOrderedList( - qualityList: qualityList, - fallbackStrategy: fallbackStrategy, - instanceManager: instanceManager, - ); - - final VerificationResult verificationResult = verify(mockApi.create( - instanceManager.getIdentifier(instance), - captureAny, - fallbackStrategyIdentifier, - )); - final List videoQualityData = - verificationResult.captured.single as List; - expect(videoQualityData.length, equals(2)); - expect(videoQualityData.first!.quality, equals(VideoQuality.FHD)); - expect(videoQualityData.last!.quality, equals(VideoQuality.highest)); - }); - - test('getResolution returns expected resolution info', () async { - final MockTestQualitySelectorHostApi mockApi = - MockTestQualitySelectorHostApi(); - TestQualitySelectorHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final QualitySelector instance = QualitySelector.detached( - instanceManager: instanceManager, - qualityList: [ - VideoQualityData(quality: VideoQuality.HD) - ], - fallbackStrategy: MockFallbackStrategy(), - ); - const int instanceIdentifier = 0; - instanceManager.addHostCreatedInstance( - instance, - instanceIdentifier, - onCopy: (QualitySelector original) => QualitySelector.detached( - qualityList: original.qualityList, - fallbackStrategy: original.fallbackStrategy, - instanceManager: instanceManager, - ), - ); - - final CameraInfo cameraInfo = MockCameraInfo(); - const int cameraInfoIdentifier = 6; - instanceManager.addHostCreatedInstance( - cameraInfo, - cameraInfoIdentifier, - onCopy: (_) => MockCameraInfo(), - ); - - const VideoQuality quality = VideoQuality.FHD; - final ResolutionInfo expectedResult = - ResolutionInfo(width: 34, height: 23); - - when(mockApi.getResolution( - cameraInfoIdentifier, - quality, - )).thenAnswer((_) { - return expectedResult; - }); - - final ResolutionInfo result = await QualitySelector.getResolution( - cameraInfo, quality, - instanceManager: instanceManager); - - expect(result.width, expectedResult.width); - expect(result.height, expectedResult.height); - - verify(mockApi.getResolution( - cameraInfoIdentifier, - quality, - )); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/quality_selector_test.mocks.dart b/packages/camera/camera_android_camerax/test/quality_selector_test.mocks.dart deleted file mode 100644 index a4792e154676..000000000000 --- a/packages/camera/camera_android_camerax/test/quality_selector_test.mocks.dart +++ /dev/null @@ -1,223 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/quality_selector_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i6; - -import 'package:camera_android_camerax/src/camera_info.dart' as _i5; -import 'package:camera_android_camerax/src/camera_state.dart' as _i7; -import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i4; -import 'package:camera_android_camerax/src/exposure_state.dart' as _i3; -import 'package:camera_android_camerax/src/fallback_strategy.dart' as _i9; -import 'package:camera_android_camerax/src/live_data.dart' as _i2; -import 'package:camera_android_camerax/src/zoom_state.dart' as _i8; -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i10; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -class _FakeLiveData_0 extends _i1.SmartFake - implements _i2.LiveData { - _FakeLiveData_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); -} - -class _FakeExposureState_1 extends _i1.SmartFake implements _i3.ExposureState { - _FakeExposureState_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); -} - -class _FakeResolutionInfo_2 extends _i1.SmartFake - implements _i4.ResolutionInfo { - _FakeResolutionInfo_2( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); -} - -/// A class which mocks [CameraInfo]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockCameraInfo extends _i1.Mock implements _i5.CameraInfo { - MockCameraInfo() { - _i1.throwOnMissingStub(this); - } - - @override - _i6.Future getSensorRotationDegrees() => (super.noSuchMethod( - Invocation.method( - #getSensorRotationDegrees, - [], - ), - returnValue: _i6.Future.value(0), - ) as _i6.Future); - - @override - _i6.Future<_i2.LiveData<_i7.CameraState>> getCameraState() => - (super.noSuchMethod( - Invocation.method( - #getCameraState, - [], - ), - returnValue: _i6.Future<_i2.LiveData<_i7.CameraState>>.value( - _FakeLiveData_0<_i7.CameraState>( - this, - Invocation.method( - #getCameraState, - [], - ), - )), - ) as _i6.Future<_i2.LiveData<_i7.CameraState>>); - - @override - _i6.Future<_i3.ExposureState> getExposureState() => (super.noSuchMethod( - Invocation.method( - #getExposureState, - [], - ), - returnValue: _i6.Future<_i3.ExposureState>.value(_FakeExposureState_1( - this, - Invocation.method( - #getExposureState, - [], - ), - )), - ) as _i6.Future<_i3.ExposureState>); - - @override - _i6.Future<_i2.LiveData<_i8.ZoomState>> getZoomState() => (super.noSuchMethod( - Invocation.method( - #getZoomState, - [], - ), - returnValue: _i6.Future<_i2.LiveData<_i8.ZoomState>>.value( - _FakeLiveData_0<_i8.ZoomState>( - this, - Invocation.method( - #getZoomState, - [], - ), - )), - ) as _i6.Future<_i2.LiveData<_i8.ZoomState>>); -} - -/// A class which mocks [FallbackStrategy]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockFallbackStrategy extends _i1.Mock implements _i9.FallbackStrategy { - MockFallbackStrategy() { - _i1.throwOnMissingStub(this); - } - - @override - _i4.VideoQuality get quality => (super.noSuchMethod( - Invocation.getter(#quality), - returnValue: _i4.VideoQuality.SD, - ) as _i4.VideoQuality); - - @override - _i4.VideoResolutionFallbackRule get fallbackRule => (super.noSuchMethod( - Invocation.getter(#fallbackRule), - returnValue: _i4.VideoResolutionFallbackRule.higherQualityOrLowerThan, - ) as _i4.VideoResolutionFallbackRule); -} - -/// A class which mocks [TestQualitySelectorHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestQualitySelectorHostApi extends _i1.Mock - implements _i10.TestQualitySelectorHostApi { - MockTestQualitySelectorHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void create( - int? identifier, - List<_i4.VideoQualityData?>? videoQualityDataList, - int? fallbackStrategyId, - ) => - super.noSuchMethod( - Invocation.method( - #create, - [ - identifier, - videoQualityDataList, - fallbackStrategyId, - ], - ), - returnValueForMissingStub: null, - ); - - @override - _i4.ResolutionInfo getResolution( - int? cameraInfoId, - _i4.VideoQuality? quality, - ) => - (super.noSuchMethod( - Invocation.method( - #getResolution, - [ - cameraInfoId, - quality, - ], - ), - returnValue: _FakeResolutionInfo_2( - this, - Invocation.method( - #getResolution, - [ - cameraInfoId, - quality, - ], - ), - ), - ) as _i4.ResolutionInfo); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i10.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} diff --git a/packages/camera/camera_android_camerax/test/recorder_test.dart b/packages/camera/camera_android_camerax/test/recorder_test.dart deleted file mode 100644 index 416ba0f7a47f..000000000000 --- a/packages/camera/camera_android_camerax/test/recorder_test.dart +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camerax_library.g.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:camera_android_camerax/src/pending_recording.dart'; -import 'package:camera_android_camerax/src/quality_selector.dart'; -import 'package:camera_android_camerax/src/recorder.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'recorder_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([ - QualitySelector, - TestInstanceManagerHostApi, - TestFallbackStrategyHostApi, - TestRecorderHostApi, - TestQualitySelectorHostApi, - PendingRecording -]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('Recorder', () { - tearDown(() => TestCameraSelectorHostApi.setup(null)); - - test('detached create does not call create on the Java side', () async { - final MockTestRecorderHostApi mockApi = MockTestRecorderHostApi(); - TestRecorderHostApi.setup(mockApi); - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - Recorder.detached( - instanceManager: instanceManager, aspectRatio: 0, bitRate: 0); - - verifyNever(mockApi.create(argThat(isA()), argThat(isA()), - argThat(isA()), argThat(isA()))); - }, skip: 'Flaky test: https://github.com/flutter/flutter/issues/164132'); - - test('create does call create on the Java side', () async { - final MockTestRecorderHostApi mockApi = MockTestRecorderHostApi(); - TestRecorderHostApi.setup(mockApi); - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - const int aspectRatio = 1; - const int bitRate = 2; - final QualitySelector qualitySelector = MockQualitySelector(); - const int qualitySelectorIdentifier = 33; - - instanceManager.addHostCreatedInstance( - qualitySelector, - qualitySelectorIdentifier, - onCopy: (_) => MockQualitySelector(), - ); - - Recorder( - instanceManager: instanceManager, - aspectRatio: aspectRatio, - bitRate: bitRate, - qualitySelector: qualitySelector); - - verify(mockApi.create(argThat(isA()), aspectRatio, bitRate, - qualitySelectorIdentifier)); - }); - - test('getDefaultQualitySelector returns expected QualitySelector', - () async { - final MockTestQualitySelectorHostApi mockQualitySelectorApi = - MockTestQualitySelectorHostApi(); - final MockTestFallbackStrategyHostApi mockFallbackStrategyApi = - MockTestFallbackStrategyHostApi(); - TestQualitySelectorHostApi.setup(mockQualitySelectorApi); - TestFallbackStrategyHostApi.setup(mockFallbackStrategyApi); - - final QualitySelector defaultQualitySelector = - Recorder.getDefaultQualitySelector(); - final List expectedVideoQualities = [ - VideoQuality.FHD, - VideoQuality.HD, - VideoQuality.SD - ]; - - expect(defaultQualitySelector.qualityList.length, equals(3)); - for (int i = 0; i < 3; i++) { - final VideoQuality currentVideoQuality = - defaultQualitySelector.qualityList[i].quality; - expect(currentVideoQuality, equals(expectedVideoQualities[i])); - } - - expect(defaultQualitySelector.fallbackStrategy!.quality, - equals(VideoQuality.FHD)); - expect(defaultQualitySelector.fallbackStrategy!.fallbackRule, - equals(VideoResolutionFallbackRule.higherQualityOrLowerThan)); - - // Cleanup test Host APIs used only for this test. - TestQualitySelectorHostApi.setup(null); - TestFallbackStrategyHostApi.setup(null); - }); - - test('prepareRecording calls prepareRecording on Java side', () async { - final MockTestRecorderHostApi mockApi = MockTestRecorderHostApi(); - TestRecorderHostApi.setup(mockApi); - when(mockApi.prepareRecording(0, '/test/path')).thenAnswer((_) => 2); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - const String filePath = '/test/path'; - final Recorder recorder = - Recorder.detached(instanceManager: instanceManager); - const int recorderId = 0; - const int mockPendingRecordingId = 2; - - instanceManager.addHostCreatedInstance(recorder, recorderId, - onCopy: (_) => Recorder.detached(instanceManager: instanceManager)); - - final MockPendingRecording mockPendingRecording = MockPendingRecording(); - instanceManager.addHostCreatedInstance( - mockPendingRecording, mockPendingRecordingId, - onCopy: (_) => MockPendingRecording()); - when(mockApi.prepareRecording(recorderId, filePath)) - .thenReturn(mockPendingRecordingId); - final PendingRecording pendingRecording = - await recorder.prepareRecording(filePath); - expect(pendingRecording, mockPendingRecording); - }); - - test( - 'flutterApi create makes call to create Recorder instance with expected identifier', - () { - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final RecorderFlutterApiImpl flutterApi = RecorderFlutterApiImpl( - instanceManager: instanceManager, - ); - const int recorderId = 0; - const int aspectRatio = 1; - const int bitrate = 2; - - flutterApi.create(recorderId, aspectRatio, bitrate); - - expect(instanceManager.getInstanceWithWeakReference(recorderId), - isA()); - expect( - (instanceManager.getInstanceWithWeakReference(recorderId)! - as Recorder) - .aspectRatio, - equals(aspectRatio)); - expect( - (instanceManager.getInstanceWithWeakReference(0)! as Recorder) - .bitRate, - equals(bitrate)); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/recorder_test.mocks.dart b/packages/camera/camera_android_camerax/test/recorder_test.mocks.dart deleted file mode 100644 index 78a8776d360b..000000000000 --- a/packages/camera/camera_android_camerax/test/recorder_test.mocks.dart +++ /dev/null @@ -1,253 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/recorder_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i7; - -import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i2; -import 'package:camera_android_camerax/src/pending_recording.dart' as _i6; -import 'package:camera_android_camerax/src/quality_selector.dart' as _i4; -import 'package:camera_android_camerax/src/recording.dart' as _i3; -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i5; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -class _FakeResolutionInfo_0 extends _i1.SmartFake - implements _i2.ResolutionInfo { - _FakeResolutionInfo_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); -} - -class _FakeRecording_1 extends _i1.SmartFake implements _i3.Recording { - _FakeRecording_1( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); -} - -/// A class which mocks [QualitySelector]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockQualitySelector extends _i1.Mock implements _i4.QualitySelector { - MockQualitySelector() { - _i1.throwOnMissingStub(this); - } - - @override - List<_i2.VideoQualityData> get qualityList => (super.noSuchMethod( - Invocation.getter(#qualityList), - returnValue: <_i2.VideoQualityData>[], - ) as List<_i2.VideoQualityData>); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i5.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [TestFallbackStrategyHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestFallbackStrategyHostApi extends _i1.Mock - implements _i5.TestFallbackStrategyHostApi { - MockTestFallbackStrategyHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void create( - int? identifier, - _i2.VideoQuality? quality, - _i2.VideoResolutionFallbackRule? fallbackRule, - ) => - super.noSuchMethod( - Invocation.method( - #create, - [ - identifier, - quality, - fallbackRule, - ], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [TestRecorderHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestRecorderHostApi extends _i1.Mock - implements _i5.TestRecorderHostApi { - MockTestRecorderHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void create( - int? identifier, - int? aspectRatio, - int? bitRate, - int? qualitySelectorId, - ) => - super.noSuchMethod( - Invocation.method( - #create, - [ - identifier, - aspectRatio, - bitRate, - qualitySelectorId, - ], - ), - returnValueForMissingStub: null, - ); - - @override - int getAspectRatio(int? identifier) => (super.noSuchMethod( - Invocation.method( - #getAspectRatio, - [identifier], - ), - returnValue: 0, - ) as int); - - @override - int getTargetVideoEncodingBitRate(int? identifier) => (super.noSuchMethod( - Invocation.method( - #getTargetVideoEncodingBitRate, - [identifier], - ), - returnValue: 0, - ) as int); - - @override - int prepareRecording( - int? identifier, - String? path, - ) => - (super.noSuchMethod( - Invocation.method( - #prepareRecording, - [ - identifier, - path, - ], - ), - returnValue: 0, - ) as int); -} - -/// A class which mocks [TestQualitySelectorHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestQualitySelectorHostApi extends _i1.Mock - implements _i5.TestQualitySelectorHostApi { - MockTestQualitySelectorHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void create( - int? identifier, - List<_i2.VideoQualityData?>? videoQualityDataList, - int? fallbackStrategyId, - ) => - super.noSuchMethod( - Invocation.method( - #create, - [ - identifier, - videoQualityDataList, - fallbackStrategyId, - ], - ), - returnValueForMissingStub: null, - ); - - @override - _i2.ResolutionInfo getResolution( - int? cameraInfoId, - _i2.VideoQuality? quality, - ) => - (super.noSuchMethod( - Invocation.method( - #getResolution, - [ - cameraInfoId, - quality, - ], - ), - returnValue: _FakeResolutionInfo_0( - this, - Invocation.method( - #getResolution, - [ - cameraInfoId, - quality, - ], - ), - ), - ) as _i2.ResolutionInfo); -} - -/// A class which mocks [PendingRecording]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockPendingRecording extends _i1.Mock implements _i6.PendingRecording { - MockPendingRecording() { - _i1.throwOnMissingStub(this); - } - - @override - _i7.Future<_i3.Recording> start() => (super.noSuchMethod( - Invocation.method( - #start, - [], - ), - returnValue: _i7.Future<_i3.Recording>.value(_FakeRecording_1( - this, - Invocation.method( - #start, - [], - ), - )), - ) as _i7.Future<_i3.Recording>); -} diff --git a/packages/camera/camera_android_camerax/test/recording_test.dart b/packages/camera/camera_android_camerax/test/recording_test.dart deleted file mode 100644 index b0877e9db13c..000000000000 --- a/packages/camera/camera_android_camerax/test/recording_test.dart +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camerax_library.g.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:camera_android_camerax/src/recording.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'recording_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([TestRecordingHostApi, TestInstanceManagerHostApi]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('Recording', () { - tearDown(() => TestRecorderHostApi.setup(null)); - - test('close calls close on Java side', () async { - final MockTestRecordingHostApi mockApi = MockTestRecordingHostApi(); - TestRecordingHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final Recording recording = - Recording.detached(instanceManager: instanceManager); - const int recordingId = 0; - when(mockApi.close(recordingId)).thenAnswer((_) {}); - instanceManager.addHostCreatedInstance(recording, recordingId, - onCopy: (_) => Recording.detached(instanceManager: instanceManager)); - - await recording.close(); - - verify(mockApi.close(recordingId)); - }); - - test('pause calls pause on Java side', () async { - final MockTestRecordingHostApi mockApi = MockTestRecordingHostApi(); - TestRecordingHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final Recording recording = - Recording.detached(instanceManager: instanceManager); - const int recordingId = 0; - when(mockApi.pause(recordingId)).thenAnswer((_) {}); - instanceManager.addHostCreatedInstance(recording, recordingId, - onCopy: (_) => Recording.detached(instanceManager: instanceManager)); - - await recording.pause(); - - verify(mockApi.pause(recordingId)); - }); - - test('resume calls resume on Java side', () async { - final MockTestRecordingHostApi mockApi = MockTestRecordingHostApi(); - TestRecordingHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final Recording recording = - Recording.detached(instanceManager: instanceManager); - const int recordingId = 0; - when(mockApi.resume(recordingId)).thenAnswer((_) {}); - instanceManager.addHostCreatedInstance(recording, recordingId, - onCopy: (_) => Recording.detached(instanceManager: instanceManager)); - - await recording.resume(); - - verify(mockApi.resume(recordingId)); - }); - - test('stop calls stop on Java side', () async { - final MockTestRecordingHostApi mockApi = MockTestRecordingHostApi(); - TestRecordingHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final Recording recording = - Recording.detached(instanceManager: instanceManager); - const int recordingId = 0; - when(mockApi.stop(recordingId)).thenAnswer((_) {}); - instanceManager.addHostCreatedInstance(recording, recordingId, - onCopy: (_) => Recording.detached(instanceManager: instanceManager)); - - await recording.stop(); - - verify(mockApi.stop(recordingId)); - }); - - test('flutterApiCreateTest', () async { - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final RecordingFlutterApi flutterApi = RecordingFlutterApiImpl( - instanceManager: instanceManager, - ); - - flutterApi.create(0); - - expect(instanceManager.getInstanceWithWeakReference(0), isA()); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/recording_test.mocks.dart b/packages/camera/camera_android_camerax/test/recording_test.mocks.dart deleted file mode 100644 index 55f4b48dd3f0..000000000000 --- a/packages/camera/camera_android_camerax/test/recording_test.mocks.dart +++ /dev/null @@ -1,86 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/recording_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestRecordingHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestRecordingHostApi extends _i1.Mock - implements _i2.TestRecordingHostApi { - MockTestRecordingHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void close(int? identifier) => super.noSuchMethod( - Invocation.method( - #close, - [identifier], - ), - returnValueForMissingStub: null, - ); - - @override - void pause(int? identifier) => super.noSuchMethod( - Invocation.method( - #pause, - [identifier], - ), - returnValueForMissingStub: null, - ); - - @override - void resume(int? identifier) => super.noSuchMethod( - Invocation.method( - #resume, - [identifier], - ), - returnValueForMissingStub: null, - ); - - @override - void stop(int? identifier) => super.noSuchMethod( - Invocation.method( - #stop, - [identifier], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} diff --git a/packages/camera/camera_android_camerax/test/resolution_filter_test.dart b/packages/camera/camera_android_camerax/test/resolution_filter_test.dart deleted file mode 100644 index 07a96ff68027..000000000000 --- a/packages/camera/camera_android_camerax/test/resolution_filter_test.dart +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'dart:ui'; - -import 'package:camera_android_camerax/src/camerax_library.g.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:camera_android_camerax/src/resolution_filter.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'resolution_filter_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([ - TestResolutionFilterHostApi, - TestInstanceManagerHostApi, -]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - group('ResolutionFilter', () { - tearDown(() { - TestResolutionFilterHostApi.setup(null); - TestInstanceManagerHostApi.setup(null); - }); - - test( - 'detached ResolutionFilter.onePreferredSize constructor does not make call to Host API createWithOnePreferredSize', - () { - final MockTestResolutionFilterHostApi mockApi = - MockTestResolutionFilterHostApi(); - TestResolutionFilterHostApi.setup(mockApi); - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - const double preferredWidth = 270; - const double preferredHeight = 720; - const Size preferredResolution = Size(preferredWidth, preferredHeight); - - ResolutionFilter.onePreferredSizeDetached( - preferredResolution: preferredResolution, - instanceManager: instanceManager, - ); - - verifyNever(mockApi.createWithOnePreferredSize( - argThat(isA()), - argThat(isA() - .having( - (ResolutionInfo size) => size.width, 'width', preferredWidth) - .having((ResolutionInfo size) => size.height, 'height', - preferredHeight)), - )); - }); - - test('HostApi createWithOnePreferredSize creates expected ResolutionFilter', - () { - final MockTestResolutionFilterHostApi mockApi = - MockTestResolutionFilterHostApi(); - TestResolutionFilterHostApi.setup(mockApi); - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - const double preferredWidth = 890; - const double preferredHeight = 980; - const Size preferredResolution = Size(preferredWidth, preferredHeight); - - final ResolutionFilter instance = ResolutionFilter.onePreferredSize( - preferredResolution: preferredResolution, - instanceManager: instanceManager, - ); - verify(mockApi.createWithOnePreferredSize( - instanceManager.getIdentifier(instance), - argThat(isA() - .having( - (ResolutionInfo size) => size.width, 'width', preferredWidth) - .having((ResolutionInfo size) => size.height, 'height', - preferredHeight)), - )); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/resolution_filter_test.mocks.dart b/packages/camera/camera_android_camerax/test/resolution_filter_test.mocks.dart deleted file mode 100644 index cf859c7b6378..000000000000 --- a/packages/camera/camera_android_camerax/test/resolution_filter_test.mocks.dart +++ /dev/null @@ -1,67 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/resolution_filter_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i3; -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestResolutionFilterHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestResolutionFilterHostApi extends _i1.Mock - implements _i2.TestResolutionFilterHostApi { - MockTestResolutionFilterHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void createWithOnePreferredSize( - int? identifier, - _i3.ResolutionInfo? preferredResolution, - ) => - super.noSuchMethod( - Invocation.method( - #createWithOnePreferredSize, - [ - identifier, - preferredResolution, - ], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} diff --git a/packages/camera/camera_android_camerax/test/resolution_selector_test.dart b/packages/camera/camera_android_camerax/test/resolution_selector_test.dart deleted file mode 100644 index 7aaa37ae1ea0..000000000000 --- a/packages/camera/camera_android_camerax/test/resolution_selector_test.dart +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'dart:ui'; - -import 'package:camera_android_camerax/src/aspect_ratio_strategy.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:camera_android_camerax/src/resolution_filter.dart'; -import 'package:camera_android_camerax/src/resolution_selector.dart'; -import 'package:camera_android_camerax/src/resolution_strategy.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'resolution_selector_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([ - AspectRatioStrategy, - ResolutionFilter, - ResolutionStrategy, - TestResolutionSelectorHostApi, - TestInstanceManagerHostApi, -]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - group('ResolutionSelector', () { - tearDown(() { - TestResolutionSelectorHostApi.setup(null); - TestInstanceManagerHostApi.setup(null); - }); - - test( - 'detached constructor does not make call to create expected AspectRatioStrategy instance', - () async { - final MockTestResolutionSelectorHostApi mockApi = - MockTestResolutionSelectorHostApi(); - TestResolutionSelectorHostApi.setup(mockApi); - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - const int preferredAspectRatio = 1; - - const int fallbackRule = 1; - - AspectRatioStrategy.detached( - preferredAspectRatio: preferredAspectRatio, - fallbackRule: fallbackRule, - instanceManager: instanceManager, - ); - - ResolutionSelector.detached( - resolutionStrategy: MockResolutionStrategy(), - resolutionFilter: MockResolutionFilter(), - aspectRatioStrategy: MockAspectRatioStrategy(), - instanceManager: instanceManager, - ); - - verifyNever(mockApi.create(argThat(isA()), argThat(isA()), - argThat(isA()), argThat(isA()))); - }); - - test('HostApi create creates expected ResolutionSelector instance', () { - final MockTestResolutionSelectorHostApi mockApi = - MockTestResolutionSelectorHostApi(); - TestResolutionSelectorHostApi.setup(mockApi); - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final ResolutionStrategy resolutionStrategy = ResolutionStrategy.detached( - boundSize: const Size(50, 30), - fallbackRule: ResolutionStrategy.fallbackRuleClosestLower, - instanceManager: instanceManager, - ); - const int resolutionStrategyIdentifier = 14; - instanceManager.addHostCreatedInstance( - resolutionStrategy, - resolutionStrategyIdentifier, - onCopy: (ResolutionStrategy original) => ResolutionStrategy.detached( - boundSize: original.boundSize, - fallbackRule: original.fallbackRule, - instanceManager: instanceManager, - ), - ); - - final ResolutionFilter resolutionFilter = - ResolutionFilter.onePreferredSizeDetached( - preferredResolution: const Size(30, 40)); - const int resolutionFilterIdentifier = 54; - instanceManager.addHostCreatedInstance( - resolutionFilter, - resolutionFilterIdentifier, - onCopy: (ResolutionFilter original) => - ResolutionFilter.onePreferredSizeDetached( - preferredResolution: original.preferredResolution, - instanceManager: instanceManager, - ), - ); - - final AspectRatioStrategy aspectRatioStrategy = - AspectRatioStrategy.detached( - preferredAspectRatio: AspectRatio.ratio4To3, - fallbackRule: AspectRatioStrategy.fallbackRuleAuto, - instanceManager: instanceManager, - ); - const int aspectRatioStrategyIdentifier = 15; - instanceManager.addHostCreatedInstance( - aspectRatioStrategy, - aspectRatioStrategyIdentifier, - onCopy: (AspectRatioStrategy original) => AspectRatioStrategy.detached( - preferredAspectRatio: original.preferredAspectRatio, - fallbackRule: original.fallbackRule, - instanceManager: instanceManager, - ), - ); - - final ResolutionSelector instance = ResolutionSelector( - resolutionStrategy: resolutionStrategy, - resolutionFilter: resolutionFilter, - aspectRatioStrategy: aspectRatioStrategy, - instanceManager: instanceManager, - ); - - verify(mockApi.create( - instanceManager.getIdentifier(instance), - resolutionStrategyIdentifier, - resolutionFilterIdentifier, - aspectRatioStrategyIdentifier, - )); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/resolution_selector_test.mocks.dart b/packages/camera/camera_android_camerax/test/resolution_selector_test.mocks.dart deleted file mode 100644 index c36ae699e8ad..000000000000 --- a/packages/camera/camera_android_camerax/test/resolution_selector_test.mocks.dart +++ /dev/null @@ -1,138 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/resolution_selector_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:ui' as _i2; - -import 'package:camera_android_camerax/src/aspect_ratio_strategy.dart' as _i3; -import 'package:camera_android_camerax/src/resolution_filter.dart' as _i4; -import 'package:camera_android_camerax/src/resolution_strategy.dart' as _i5; -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i6; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -class _FakeSize_0 extends _i1.SmartFake implements _i2.Size { - _FakeSize_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); -} - -/// A class which mocks [AspectRatioStrategy]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockAspectRatioStrategy extends _i1.Mock - implements _i3.AspectRatioStrategy { - MockAspectRatioStrategy() { - _i1.throwOnMissingStub(this); - } - - @override - int get preferredAspectRatio => (super.noSuchMethod( - Invocation.getter(#preferredAspectRatio), - returnValue: 0, - ) as int); - - @override - int get fallbackRule => (super.noSuchMethod( - Invocation.getter(#fallbackRule), - returnValue: 0, - ) as int); -} - -/// A class which mocks [ResolutionFilter]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockResolutionFilter extends _i1.Mock implements _i4.ResolutionFilter { - MockResolutionFilter() { - _i1.throwOnMissingStub(this); - } - - @override - _i2.Size get preferredResolution => (super.noSuchMethod( - Invocation.getter(#preferredResolution), - returnValue: _FakeSize_0( - this, - Invocation.getter(#preferredResolution), - ), - ) as _i2.Size); -} - -/// A class which mocks [ResolutionStrategy]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockResolutionStrategy extends _i1.Mock - implements _i5.ResolutionStrategy { - MockResolutionStrategy() { - _i1.throwOnMissingStub(this); - } -} - -/// A class which mocks [TestResolutionSelectorHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestResolutionSelectorHostApi extends _i1.Mock - implements _i6.TestResolutionSelectorHostApi { - MockTestResolutionSelectorHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void create( - int? identifier, - int? resolutionStrategyIdentifier, - int? resolutionSelectorIdentifier, - int? aspectRatioStrategyIdentifier, - ) => - super.noSuchMethod( - Invocation.method( - #create, - [ - identifier, - resolutionStrategyIdentifier, - resolutionSelectorIdentifier, - aspectRatioStrategyIdentifier, - ], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i6.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} diff --git a/packages/camera/camera_android_camerax/test/resolution_strategy_test.dart b/packages/camera/camera_android_camerax/test/resolution_strategy_test.dart deleted file mode 100644 index 9c098b946075..000000000000 --- a/packages/camera/camera_android_camerax/test/resolution_strategy_test.dart +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'dart:ui'; - -import 'package:camera_android_camerax/src/camerax_library.g.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:camera_android_camerax/src/resolution_strategy.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'resolution_strategy_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([ - TestResolutionStrategyHostApi, - TestInstanceManagerHostApi, -]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - group('ResolutionStrategy', () { - tearDown(() { - TestResolutionStrategyHostApi.setup(null); - TestInstanceManagerHostApi.setup(null); - }); - - test( - 'detached resolutionStrategy constructors do not make call to Host API create', - () { - final MockTestResolutionStrategyHostApi mockApi = - MockTestResolutionStrategyHostApi(); - TestResolutionStrategyHostApi.setup(mockApi); - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - const Size boundSize = Size(70, 20); - const int fallbackRule = 1; - - ResolutionStrategy.detached( - boundSize: boundSize, - fallbackRule: fallbackRule, - instanceManager: instanceManager, - ); - - verifyNever(mockApi.create( - argThat(isA()), - argThat(isA() - .having((ResolutionInfo size) => size.width, 'width', 50) - .having((ResolutionInfo size) => size.height, 'height', 30)), - fallbackRule, - )); - - ResolutionStrategy.detachedHighestAvailableStrategy( - instanceManager: instanceManager, - ); - - verifyNever(mockApi.create( - argThat(isA()), - null, - null, - )); - }); - - test('HostApi create creates expected ResolutionStrategies', () { - final MockTestResolutionStrategyHostApi mockApi = - MockTestResolutionStrategyHostApi(); - TestResolutionStrategyHostApi.setup(mockApi); - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - const Size boundSize = Size(50, 30); - const int fallbackRule = 0; - - final ResolutionStrategy instance = ResolutionStrategy( - boundSize: boundSize, - fallbackRule: fallbackRule, - instanceManager: instanceManager, - ); - - verify(mockApi.create( - instanceManager.getIdentifier(instance), - argThat(isA() - .having((ResolutionInfo size) => size.width, 'width', 50) - .having((ResolutionInfo size) => size.height, 'height', 30)), - fallbackRule, - )); - - final ResolutionStrategy highestAvailableInstance = - ResolutionStrategy.highestAvailableStrategy( - instanceManager: instanceManager, - ); - - verify(mockApi.create( - instanceManager.getIdentifier(highestAvailableInstance), - null, - null, - )); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/resolution_strategy_test.mocks.dart b/packages/camera/camera_android_camerax/test/resolution_strategy_test.mocks.dart deleted file mode 100644 index 3fc3b8ce5c35..000000000000 --- a/packages/camera/camera_android_camerax/test/resolution_strategy_test.mocks.dart +++ /dev/null @@ -1,69 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/resolution_strategy_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i3; -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestResolutionStrategyHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestResolutionStrategyHostApi extends _i1.Mock - implements _i2.TestResolutionStrategyHostApi { - MockTestResolutionStrategyHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void create( - int? identifier, - _i3.ResolutionInfo? boundSize, - int? fallbackRule, - ) => - super.noSuchMethod( - Invocation.method( - #create, - [ - identifier, - boundSize, - fallbackRule, - ], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} diff --git a/packages/camera/camera_android_camerax/test/system_services_test.dart b/packages/camera/camera_android_camerax/test/system_services_test.dart deleted file mode 100644 index 030f9aee5b26..000000000000 --- a/packages/camera/camera_android_camerax/test/system_services_test.dart +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camerax_library.g.dart' - show CameraPermissionsErrorData; -import 'package:camera_android_camerax/src/system_services.dart'; -import 'package:camera_platform_interface/camera_platform_interface.dart' - show CameraException; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'system_services_test.mocks.dart'; -import 'test_camerax_library.g.dart'; - -@GenerateMocks([TestInstanceManagerHostApi, TestSystemServicesHostApi]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('SystemServices', () { - tearDown(() => TestProcessCameraProviderHostApi.setup(null)); - - test( - 'requestCameraPermissionsFromInstance completes normally without errors test', - () async { - final MockTestSystemServicesHostApi mockApi = - MockTestSystemServicesHostApi(); - TestSystemServicesHostApi.setup(mockApi); - - when(mockApi.requestCameraPermissions(true)) - .thenAnswer((_) async => null); - - await SystemServices.requestCameraPermissions(true); - verify(mockApi.requestCameraPermissions(true)); - }); - - test( - 'requestCameraPermissionsFromInstance throws CameraException if there was a request error', - () { - final MockTestSystemServicesHostApi mockApi = - MockTestSystemServicesHostApi(); - TestSystemServicesHostApi.setup(mockApi); - final CameraPermissionsErrorData error = CameraPermissionsErrorData( - errorCode: 'Test error code', - description: 'Test error description', - ); - - when(mockApi.requestCameraPermissions(true)) - .thenAnswer((_) async => error); - - expect( - () async => SystemServices.requestCameraPermissions(true), - throwsA(isA() - .having((CameraException e) => e.code, 'code', 'Test error code') - .having((CameraException e) => e.description, 'description', - 'Test error description'))); - verify(mockApi.requestCameraPermissions(true)); - }); - - test('onCameraError adds new error to stream', () { - const String testErrorDescription = 'Test error description!'; - SystemServices.cameraErrorStreamController.stream - .listen((String errorDescription) { - expect(errorDescription, equals(testErrorDescription)); - }); - SystemServicesFlutterApiImpl().onCameraError(testErrorDescription); - }); - - test('getTempFilePath completes normally', () async { - final MockTestSystemServicesHostApi mockApi = - MockTestSystemServicesHostApi(); - TestSystemServicesHostApi.setup(mockApi); - const String testPath = '/test/path/'; - const String testPrefix = 'MOV'; - const String testSuffix = '.mp4'; - - when(mockApi.getTempFilePath(testPrefix, testSuffix)) - .thenReturn(testPath + testPrefix + testSuffix); - expect(await SystemServices.getTempFilePath(testPrefix, testSuffix), - testPath + testPrefix + testSuffix); - verify(mockApi.getTempFilePath(testPrefix, testSuffix)); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/system_services_test.mocks.dart b/packages/camera/camera_android_camerax/test/system_services_test.mocks.dart deleted file mode 100644 index ec97625adb94..000000000000 --- a/packages/camera/camera_android_camerax/test/system_services_test.mocks.dart +++ /dev/null @@ -1,90 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/system_services_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i3; - -import 'package:camera_android_camerax/src/camerax_library.g.dart' as _i4; -import 'package:mockito/mockito.dart' as _i1; -import 'package:mockito/src/dummies.dart' as _i5; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [TestSystemServicesHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestSystemServicesHostApi extends _i1.Mock - implements _i2.TestSystemServicesHostApi { - MockTestSystemServicesHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - _i3.Future<_i4.CameraPermissionsErrorData?> requestCameraPermissions( - bool? enableAudio) => - (super.noSuchMethod( - Invocation.method( - #requestCameraPermissions, - [enableAudio], - ), - returnValue: _i3.Future<_i4.CameraPermissionsErrorData?>.value(), - ) as _i3.Future<_i4.CameraPermissionsErrorData?>); - - @override - String getTempFilePath( - String? prefix, - String? suffix, - ) => - (super.noSuchMethod( - Invocation.method( - #getTempFilePath, - [ - prefix, - suffix, - ], - ), - returnValue: _i5.dummyValue( - this, - Invocation.method( - #getTempFilePath, - [ - prefix, - suffix, - ], - ), - ), - ) as String); -} diff --git a/packages/camera/camera_android_camerax/test/test_camerax_library.g.dart b/packages/camera/camera_android_camerax/test/test_camerax_library.g.dart deleted file mode 100644 index 1007d975ebca..000000000000 --- a/packages/camera/camera_android_camerax/test/test_camerax_library.g.dart +++ /dev/null @@ -1,2583 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -// Autogenerated from Pigeon (v9.2.5), do not edit directly. -// See also: https://pub.dev/packages/pigeon -// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, unnecessary_import -// ignore_for_file: avoid_relative_lib_imports -import 'dart:async'; -import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; -import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; -import 'package:flutter/services.dart'; -import 'package:flutter_test/flutter_test.dart'; - -import 'package:camera_android_camerax/src/camerax_library.g.dart'; - -abstract class TestInstanceManagerHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - /// Clear the native `InstanceManager`. - /// - /// This is typically only used after a hot restart. - void clear(); - - static void setup(TestInstanceManagerHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.InstanceManagerHostApi.clear', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - // ignore message - api.clear(); - return []; - }); - } - } - } -} - -abstract class TestJavaObjectHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - void dispose(int identifier); - - static void setup(TestJavaObjectHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.JavaObjectHostApi.dispose', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.JavaObjectHostApi.dispose was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.JavaObjectHostApi.dispose was null, expected non-null int.'); - api.dispose(arg_identifier!); - return []; - }); - } - } - } -} - -abstract class TestCameraInfoHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - int getSensorRotationDegrees(int identifier); - - int getCameraState(int identifier); - - int getExposureState(int identifier); - - int getZoomState(int identifier); - - static void setup(TestCameraInfoHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraInfoHostApi.getSensorRotationDegrees', - codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.CameraInfoHostApi.getSensorRotationDegrees was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.CameraInfoHostApi.getSensorRotationDegrees was null, expected non-null int.'); - final int output = api.getSensorRotationDegrees(arg_identifier!); - return [output]; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraInfoHostApi.getCameraState', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.CameraInfoHostApi.getCameraState was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.CameraInfoHostApi.getCameraState was null, expected non-null int.'); - final int output = api.getCameraState(arg_identifier!); - return [output]; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraInfoHostApi.getExposureState', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.CameraInfoHostApi.getExposureState was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.CameraInfoHostApi.getExposureState was null, expected non-null int.'); - final int output = api.getExposureState(arg_identifier!); - return [output]; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraInfoHostApi.getZoomState', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.CameraInfoHostApi.getZoomState was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.CameraInfoHostApi.getZoomState was null, expected non-null int.'); - final int output = api.getZoomState(arg_identifier!); - return [output]; - }); - } - } - } -} - -abstract class TestCameraSelectorHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - void create(int identifier, int? lensFacing); - - List filter(int identifier, List cameraInfoIds); - - static void setup(TestCameraSelectorHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraSelectorHostApi.create', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.CameraSelectorHostApi.create was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.CameraSelectorHostApi.create was null, expected non-null int.'); - final int? arg_lensFacing = (args[1] as int?); - api.create(arg_identifier!, arg_lensFacing); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraSelectorHostApi.filter', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.CameraSelectorHostApi.filter was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.CameraSelectorHostApi.filter was null, expected non-null int.'); - final List? arg_cameraInfoIds = - (args[1] as List?)?.cast(); - assert(arg_cameraInfoIds != null, - 'Argument for dev.flutter.pigeon.CameraSelectorHostApi.filter was null, expected non-null List.'); - final List output = - api.filter(arg_identifier!, arg_cameraInfoIds!); - return [output]; - }); - } - } - } -} - -abstract class TestProcessCameraProviderHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - Future getInstance(); - - List getAvailableCameraInfos(int identifier); - - int bindToLifecycle( - int identifier, int cameraSelectorIdentifier, List useCaseIds); - - bool isBound(int identifier, int useCaseIdentifier); - - void unbind(int identifier, List useCaseIds); - - void unbindAll(int identifier); - - static void setup(TestProcessCameraProviderHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ProcessCameraProviderHostApi.getInstance', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - // ignore message - final int output = await api.getInstance(); - return [output]; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ProcessCameraProviderHostApi.getAvailableCameraInfos', - codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.getAvailableCameraInfos was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.getAvailableCameraInfos was null, expected non-null int.'); - final List output = - api.getAvailableCameraInfos(arg_identifier!); - return [output]; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ProcessCameraProviderHostApi.bindToLifecycle', - codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.bindToLifecycle was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.bindToLifecycle was null, expected non-null int.'); - final int? arg_cameraSelectorIdentifier = (args[1] as int?); - assert(arg_cameraSelectorIdentifier != null, - 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.bindToLifecycle was null, expected non-null int.'); - final List? arg_useCaseIds = - (args[2] as List?)?.cast(); - assert(arg_useCaseIds != null, - 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.bindToLifecycle was null, expected non-null List.'); - final int output = api.bindToLifecycle( - arg_identifier!, arg_cameraSelectorIdentifier!, arg_useCaseIds!); - return [output]; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ProcessCameraProviderHostApi.isBound', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.isBound was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.isBound was null, expected non-null int.'); - final int? arg_useCaseIdentifier = (args[1] as int?); - assert(arg_useCaseIdentifier != null, - 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.isBound was null, expected non-null int.'); - final bool output = - api.isBound(arg_identifier!, arg_useCaseIdentifier!); - return [output]; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ProcessCameraProviderHostApi.unbind', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.unbind was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.unbind was null, expected non-null int.'); - final List? arg_useCaseIds = - (args[1] as List?)?.cast(); - assert(arg_useCaseIds != null, - 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.unbind was null, expected non-null List.'); - api.unbind(arg_identifier!, arg_useCaseIds!); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ProcessCameraProviderHostApi.unbindAll', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.unbindAll was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ProcessCameraProviderHostApi.unbindAll was null, expected non-null int.'); - api.unbindAll(arg_identifier!); - return []; - }); - } - } - } -} - -abstract class TestCameraHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - int getCameraInfo(int identifier); - - int getCameraControl(int identifier); - - static void setup(TestCameraHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraHostApi.getCameraInfo', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.CameraHostApi.getCameraInfo was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.CameraHostApi.getCameraInfo was null, expected non-null int.'); - final int output = api.getCameraInfo(arg_identifier!); - return [output]; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraHostApi.getCameraControl', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.CameraHostApi.getCameraControl was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.CameraHostApi.getCameraControl was null, expected non-null int.'); - final int output = api.getCameraControl(arg_identifier!); - return [output]; - }); - } - } - } -} - -class _TestSystemServicesHostApiCodec extends StandardMessageCodec { - const _TestSystemServicesHostApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is CameraPermissionsErrorData) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); - } else { - super.writeValue(buffer, value); - } - } - - @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return CameraPermissionsErrorData.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } - } -} - -abstract class TestSystemServicesHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = _TestSystemServicesHostApiCodec(); - - Future requestCameraPermissions( - bool enableAudio); - - String getTempFilePath(String prefix, String suffix); - - static void setup(TestSystemServicesHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.SystemServicesHostApi.requestCameraPermissions', - codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.SystemServicesHostApi.requestCameraPermissions was null.'); - final List args = (message as List?)!; - final bool? arg_enableAudio = (args[0] as bool?); - assert(arg_enableAudio != null, - 'Argument for dev.flutter.pigeon.SystemServicesHostApi.requestCameraPermissions was null, expected non-null bool.'); - final CameraPermissionsErrorData? output = - await api.requestCameraPermissions(arg_enableAudio!); - return [output]; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.SystemServicesHostApi.getTempFilePath', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.SystemServicesHostApi.getTempFilePath was null.'); - final List args = (message as List?)!; - final String? arg_prefix = (args[0] as String?); - assert(arg_prefix != null, - 'Argument for dev.flutter.pigeon.SystemServicesHostApi.getTempFilePath was null, expected non-null String.'); - final String? arg_suffix = (args[1] as String?); - assert(arg_suffix != null, - 'Argument for dev.flutter.pigeon.SystemServicesHostApi.getTempFilePath was null, expected non-null String.'); - final String output = api.getTempFilePath(arg_prefix!, arg_suffix!); - return [output]; - }); - } - } - } -} - -abstract class TestDeviceOrientationManagerHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - void startListeningForDeviceOrientationChange( - bool isFrontFacing, int sensorOrientation); - - void stopListeningForDeviceOrientationChange(); - - int getDefaultDisplayRotation(); - - String getUiOrientation(); - - static void setup(TestDeviceOrientationManagerHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.DeviceOrientationManagerHostApi.startListeningForDeviceOrientationChange', - codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.DeviceOrientationManagerHostApi.startListeningForDeviceOrientationChange was null.'); - final List args = (message as List?)!; - final bool? arg_isFrontFacing = (args[0] as bool?); - assert(arg_isFrontFacing != null, - 'Argument for dev.flutter.pigeon.DeviceOrientationManagerHostApi.startListeningForDeviceOrientationChange was null, expected non-null bool.'); - final int? arg_sensorOrientation = (args[1] as int?); - assert(arg_sensorOrientation != null, - 'Argument for dev.flutter.pigeon.DeviceOrientationManagerHostApi.startListeningForDeviceOrientationChange was null, expected non-null int.'); - api.startListeningForDeviceOrientationChange( - arg_isFrontFacing!, arg_sensorOrientation!); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.DeviceOrientationManagerHostApi.stopListeningForDeviceOrientationChange', - codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - // ignore message - api.stopListeningForDeviceOrientationChange(); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.DeviceOrientationManagerHostApi.getDefaultDisplayRotation', - codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - // ignore message - final int output = api.getDefaultDisplayRotation(); - return [output]; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.DeviceOrientationManagerHostApi.getUiOrientation', - codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - // ignore message - final String output = api.getUiOrientation(); - return [output]; - }); - } - } - } -} - -class _TestPreviewHostApiCodec extends StandardMessageCodec { - const _TestPreviewHostApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is ResolutionInfo) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); - } else { - super.writeValue(buffer, value); - } - } - - @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return ResolutionInfo.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } - } -} - -abstract class TestPreviewHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = _TestPreviewHostApiCodec(); - - void create(int identifier, int? rotation, int? resolutionSelectorId); - - int setSurfaceProvider(int identifier); - - void releaseFlutterSurfaceTexture(); - - ResolutionInfo getResolutionInfo(int identifier); - - void setTargetRotation(int identifier, int rotation); - - bool surfaceProducerHandlesCropAndRotation(); - - static void setup(TestPreviewHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.PreviewHostApi.create', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.PreviewHostApi.create was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.PreviewHostApi.create was null, expected non-null int.'); - final int? arg_rotation = (args[1] as int?); - final int? arg_resolutionSelectorId = (args[2] as int?); - api.create(arg_identifier!, arg_rotation, arg_resolutionSelectorId); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.PreviewHostApi.setSurfaceProvider', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.PreviewHostApi.setSurfaceProvider was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.PreviewHostApi.setSurfaceProvider was null, expected non-null int.'); - final int output = api.setSurfaceProvider(arg_identifier!); - return [output]; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.PreviewHostApi.releaseFlutterSurfaceTexture', - codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - // ignore message - api.releaseFlutterSurfaceTexture(); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.PreviewHostApi.getResolutionInfo', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.PreviewHostApi.getResolutionInfo was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.PreviewHostApi.getResolutionInfo was null, expected non-null int.'); - final ResolutionInfo output = api.getResolutionInfo(arg_identifier!); - return [output]; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.PreviewHostApi.setTargetRotation', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.PreviewHostApi.setTargetRotation was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.PreviewHostApi.setTargetRotation was null, expected non-null int.'); - final int? arg_rotation = (args[1] as int?); - assert(arg_rotation != null, - 'Argument for dev.flutter.pigeon.PreviewHostApi.setTargetRotation was null, expected non-null int.'); - api.setTargetRotation(arg_identifier!, arg_rotation!); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.PreviewHostApi.surfaceProducerHandlesCropAndRotation', - codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - // ignore message - final bool output = api.surfaceProducerHandlesCropAndRotation(); - return [output]; - }); - } - } - } -} - -abstract class TestVideoCaptureHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - int withOutput(int videoOutputId); - - int getOutput(int identifier); - - void setTargetRotation(int identifier, int rotation); - - static void setup(TestVideoCaptureHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.VideoCaptureHostApi.withOutput', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.VideoCaptureHostApi.withOutput was null.'); - final List args = (message as List?)!; - final int? arg_videoOutputId = (args[0] as int?); - assert(arg_videoOutputId != null, - 'Argument for dev.flutter.pigeon.VideoCaptureHostApi.withOutput was null, expected non-null int.'); - final int output = api.withOutput(arg_videoOutputId!); - return [output]; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.VideoCaptureHostApi.getOutput', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.VideoCaptureHostApi.getOutput was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.VideoCaptureHostApi.getOutput was null, expected non-null int.'); - final int output = api.getOutput(arg_identifier!); - return [output]; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.VideoCaptureHostApi.setTargetRotation', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.VideoCaptureHostApi.setTargetRotation was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.VideoCaptureHostApi.setTargetRotation was null, expected non-null int.'); - final int? arg_rotation = (args[1] as int?); - assert(arg_rotation != null, - 'Argument for dev.flutter.pigeon.VideoCaptureHostApi.setTargetRotation was null, expected non-null int.'); - api.setTargetRotation(arg_identifier!, arg_rotation!); - return []; - }); - } - } - } -} - -abstract class TestRecorderHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - void create( - int identifier, int? aspectRatio, int? bitRate, int? qualitySelectorId); - - int getAspectRatio(int identifier); - - int getTargetVideoEncodingBitRate(int identifier); - - int prepareRecording(int identifier, String path); - - static void setup(TestRecorderHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.RecorderHostApi.create', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.RecorderHostApi.create was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.RecorderHostApi.create was null, expected non-null int.'); - final int? arg_aspectRatio = (args[1] as int?); - final int? arg_bitRate = (args[2] as int?); - final int? arg_qualitySelectorId = (args[3] as int?); - api.create(arg_identifier!, arg_aspectRatio, arg_bitRate, - arg_qualitySelectorId); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.RecorderHostApi.getAspectRatio', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.RecorderHostApi.getAspectRatio was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.RecorderHostApi.getAspectRatio was null, expected non-null int.'); - final int output = api.getAspectRatio(arg_identifier!); - return [output]; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.RecorderHostApi.getTargetVideoEncodingBitRate', - codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.RecorderHostApi.getTargetVideoEncodingBitRate was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.RecorderHostApi.getTargetVideoEncodingBitRate was null, expected non-null int.'); - final int output = api.getTargetVideoEncodingBitRate(arg_identifier!); - return [output]; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.RecorderHostApi.prepareRecording', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.RecorderHostApi.prepareRecording was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.RecorderHostApi.prepareRecording was null, expected non-null int.'); - final String? arg_path = (args[1] as String?); - assert(arg_path != null, - 'Argument for dev.flutter.pigeon.RecorderHostApi.prepareRecording was null, expected non-null String.'); - final int output = api.prepareRecording(arg_identifier!, arg_path!); - return [output]; - }); - } - } - } -} - -abstract class TestPendingRecordingHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - int start(int identifier); - - static void setup(TestPendingRecordingHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.PendingRecordingHostApi.start', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.PendingRecordingHostApi.start was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.PendingRecordingHostApi.start was null, expected non-null int.'); - final int output = api.start(arg_identifier!); - return [output]; - }); - } - } - } -} - -abstract class TestRecordingHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - void close(int identifier); - - void pause(int identifier); - - void resume(int identifier); - - void stop(int identifier); - - static void setup(TestRecordingHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.RecordingHostApi.close', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.RecordingHostApi.close was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.RecordingHostApi.close was null, expected non-null int.'); - api.close(arg_identifier!); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.RecordingHostApi.pause', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.RecordingHostApi.pause was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.RecordingHostApi.pause was null, expected non-null int.'); - api.pause(arg_identifier!); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.RecordingHostApi.resume', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.RecordingHostApi.resume was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.RecordingHostApi.resume was null, expected non-null int.'); - api.resume(arg_identifier!); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.RecordingHostApi.stop', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.RecordingHostApi.stop was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.RecordingHostApi.stop was null, expected non-null int.'); - api.stop(arg_identifier!); - return []; - }); - } - } - } -} - -abstract class TestImageCaptureHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - void create(int identifier, int? targetRotation, int? flashMode, - int? resolutionSelectorId); - - void setFlashMode(int identifier, int flashMode); - - Future takePicture(int identifier); - - void setTargetRotation(int identifier, int rotation); - - static void setup(TestImageCaptureHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ImageCaptureHostApi.create', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.ImageCaptureHostApi.create was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ImageCaptureHostApi.create was null, expected non-null int.'); - final int? arg_targetRotation = (args[1] as int?); - final int? arg_flashMode = (args[2] as int?); - final int? arg_resolutionSelectorId = (args[3] as int?); - api.create(arg_identifier!, arg_targetRotation, arg_flashMode, - arg_resolutionSelectorId); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ImageCaptureHostApi.setFlashMode', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.ImageCaptureHostApi.setFlashMode was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ImageCaptureHostApi.setFlashMode was null, expected non-null int.'); - final int? arg_flashMode = (args[1] as int?); - assert(arg_flashMode != null, - 'Argument for dev.flutter.pigeon.ImageCaptureHostApi.setFlashMode was null, expected non-null int.'); - api.setFlashMode(arg_identifier!, arg_flashMode!); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ImageCaptureHostApi.takePicture', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.ImageCaptureHostApi.takePicture was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ImageCaptureHostApi.takePicture was null, expected non-null int.'); - final String output = await api.takePicture(arg_identifier!); - return [output]; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ImageCaptureHostApi.setTargetRotation', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.ImageCaptureHostApi.setTargetRotation was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ImageCaptureHostApi.setTargetRotation was null, expected non-null int.'); - final int? arg_rotation = (args[1] as int?); - assert(arg_rotation != null, - 'Argument for dev.flutter.pigeon.ImageCaptureHostApi.setTargetRotation was null, expected non-null int.'); - api.setTargetRotation(arg_identifier!, arg_rotation!); - return []; - }); - } - } - } -} - -class _TestResolutionStrategyHostApiCodec extends StandardMessageCodec { - const _TestResolutionStrategyHostApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is ResolutionInfo) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); - } else { - super.writeValue(buffer, value); - } - } - - @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return ResolutionInfo.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } - } -} - -abstract class TestResolutionStrategyHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = - _TestResolutionStrategyHostApiCodec(); - - void create(int identifier, ResolutionInfo? boundSize, int? fallbackRule); - - static void setup(TestResolutionStrategyHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ResolutionStrategyHostApi.create', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.ResolutionStrategyHostApi.create was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ResolutionStrategyHostApi.create was null, expected non-null int.'); - final ResolutionInfo? arg_boundSize = (args[1] as ResolutionInfo?); - final int? arg_fallbackRule = (args[2] as int?); - api.create(arg_identifier!, arg_boundSize, arg_fallbackRule); - return []; - }); - } - } - } -} - -abstract class TestResolutionSelectorHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - void create(int identifier, int? resolutionStrategyIdentifier, - int? resolutionSelectorIdentifier, int? aspectRatioStrategyIdentifier); - - static void setup(TestResolutionSelectorHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ResolutionSelectorHostApi.create', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.ResolutionSelectorHostApi.create was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ResolutionSelectorHostApi.create was null, expected non-null int.'); - final int? arg_resolutionStrategyIdentifier = (args[1] as int?); - final int? arg_resolutionSelectorIdentifier = (args[2] as int?); - final int? arg_aspectRatioStrategyIdentifier = (args[3] as int?); - api.create( - arg_identifier!, - arg_resolutionStrategyIdentifier, - arg_resolutionSelectorIdentifier, - arg_aspectRatioStrategyIdentifier); - return []; - }); - } - } - } -} - -abstract class TestAspectRatioStrategyHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - void create(int identifier, int preferredAspectRatio, int fallbackRule); - - static void setup(TestAspectRatioStrategyHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.AspectRatioStrategyHostApi.create', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.AspectRatioStrategyHostApi.create was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.AspectRatioStrategyHostApi.create was null, expected non-null int.'); - final int? arg_preferredAspectRatio = (args[1] as int?); - assert(arg_preferredAspectRatio != null, - 'Argument for dev.flutter.pigeon.AspectRatioStrategyHostApi.create was null, expected non-null int.'); - final int? arg_fallbackRule = (args[2] as int?); - assert(arg_fallbackRule != null, - 'Argument for dev.flutter.pigeon.AspectRatioStrategyHostApi.create was null, expected non-null int.'); - api.create( - arg_identifier!, arg_preferredAspectRatio!, arg_fallbackRule!); - return []; - }); - } - } - } -} - -abstract class TestImageAnalysisHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - void create(int identifier, int? targetRotation, int? resolutionSelectorId); - - void setAnalyzer(int identifier, int analyzerIdentifier); - - void clearAnalyzer(int identifier); - - void setTargetRotation(int identifier, int rotation); - - static void setup(TestImageAnalysisHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ImageAnalysisHostApi.create', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.ImageAnalysisHostApi.create was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ImageAnalysisHostApi.create was null, expected non-null int.'); - final int? arg_targetRotation = (args[1] as int?); - final int? arg_resolutionSelectorId = (args[2] as int?); - api.create( - arg_identifier!, arg_targetRotation, arg_resolutionSelectorId); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ImageAnalysisHostApi.setAnalyzer', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.ImageAnalysisHostApi.setAnalyzer was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ImageAnalysisHostApi.setAnalyzer was null, expected non-null int.'); - final int? arg_analyzerIdentifier = (args[1] as int?); - assert(arg_analyzerIdentifier != null, - 'Argument for dev.flutter.pigeon.ImageAnalysisHostApi.setAnalyzer was null, expected non-null int.'); - api.setAnalyzer(arg_identifier!, arg_analyzerIdentifier!); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ImageAnalysisHostApi.clearAnalyzer', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.ImageAnalysisHostApi.clearAnalyzer was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ImageAnalysisHostApi.clearAnalyzer was null, expected non-null int.'); - api.clearAnalyzer(arg_identifier!); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ImageAnalysisHostApi.setTargetRotation', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.ImageAnalysisHostApi.setTargetRotation was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ImageAnalysisHostApi.setTargetRotation was null, expected non-null int.'); - final int? arg_rotation = (args[1] as int?); - assert(arg_rotation != null, - 'Argument for dev.flutter.pigeon.ImageAnalysisHostApi.setTargetRotation was null, expected non-null int.'); - api.setTargetRotation(arg_identifier!, arg_rotation!); - return []; - }); - } - } - } -} - -abstract class TestAnalyzerHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - void create(int identifier); - - static void setup(TestAnalyzerHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.AnalyzerHostApi.create', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.AnalyzerHostApi.create was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.AnalyzerHostApi.create was null, expected non-null int.'); - api.create(arg_identifier!); - return []; - }); - } - } - } -} - -abstract class TestObserverHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - void create(int identifier); - - static void setup(TestObserverHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ObserverHostApi.create', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.ObserverHostApi.create was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ObserverHostApi.create was null, expected non-null int.'); - api.create(arg_identifier!); - return []; - }); - } - } - } -} - -class _TestLiveDataHostApiCodec extends StandardMessageCodec { - const _TestLiveDataHostApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is LiveDataSupportedTypeData) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); - } else { - super.writeValue(buffer, value); - } - } - - @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return LiveDataSupportedTypeData.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } - } -} - -abstract class TestLiveDataHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = _TestLiveDataHostApiCodec(); - - void observe(int identifier, int observerIdentifier); - - void removeObservers(int identifier); - - int? getValue(int identifier, LiveDataSupportedTypeData type); - - static void setup(TestLiveDataHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.LiveDataHostApi.observe', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.LiveDataHostApi.observe was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.LiveDataHostApi.observe was null, expected non-null int.'); - final int? arg_observerIdentifier = (args[1] as int?); - assert(arg_observerIdentifier != null, - 'Argument for dev.flutter.pigeon.LiveDataHostApi.observe was null, expected non-null int.'); - api.observe(arg_identifier!, arg_observerIdentifier!); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.LiveDataHostApi.removeObservers', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.LiveDataHostApi.removeObservers was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.LiveDataHostApi.removeObservers was null, expected non-null int.'); - api.removeObservers(arg_identifier!); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.LiveDataHostApi.getValue', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.LiveDataHostApi.getValue was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.LiveDataHostApi.getValue was null, expected non-null int.'); - final LiveDataSupportedTypeData? arg_type = - (args[1] as LiveDataSupportedTypeData?); - assert(arg_type != null, - 'Argument for dev.flutter.pigeon.LiveDataHostApi.getValue was null, expected non-null LiveDataSupportedTypeData.'); - final int? output = api.getValue(arg_identifier!, arg_type!); - return [output]; - }); - } - } - } -} - -abstract class TestImageProxyHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - List getPlanes(int identifier); - - void close(int identifier); - - static void setup(TestImageProxyHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ImageProxyHostApi.getPlanes', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.ImageProxyHostApi.getPlanes was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ImageProxyHostApi.getPlanes was null, expected non-null int.'); - final List output = api.getPlanes(arg_identifier!); - return [output]; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ImageProxyHostApi.close', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.ImageProxyHostApi.close was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ImageProxyHostApi.close was null, expected non-null int.'); - api.close(arg_identifier!); - return []; - }); - } - } - } -} - -class _TestQualitySelectorHostApiCodec extends StandardMessageCodec { - const _TestQualitySelectorHostApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is ResolutionInfo) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); - } else if (value is VideoQualityData) { - buffer.putUint8(129); - writeValue(buffer, value.encode()); - } else { - super.writeValue(buffer, value); - } - } - - @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return ResolutionInfo.decode(readValue(buffer)!); - case 129: - return VideoQualityData.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } - } -} - -abstract class TestQualitySelectorHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = _TestQualitySelectorHostApiCodec(); - - void create(int identifier, List videoQualityDataList, - int? fallbackStrategyId); - - ResolutionInfo getResolution(int cameraInfoId, VideoQuality quality); - - static void setup(TestQualitySelectorHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.QualitySelectorHostApi.create', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.QualitySelectorHostApi.create was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.QualitySelectorHostApi.create was null, expected non-null int.'); - final List? arg_videoQualityDataList = - (args[1] as List?)?.cast(); - assert(arg_videoQualityDataList != null, - 'Argument for dev.flutter.pigeon.QualitySelectorHostApi.create was null, expected non-null List.'); - final int? arg_fallbackStrategyId = (args[2] as int?); - api.create(arg_identifier!, arg_videoQualityDataList!, - arg_fallbackStrategyId); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.QualitySelectorHostApi.getResolution', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.QualitySelectorHostApi.getResolution was null.'); - final List args = (message as List?)!; - final int? arg_cameraInfoId = (args[0] as int?); - assert(arg_cameraInfoId != null, - 'Argument for dev.flutter.pigeon.QualitySelectorHostApi.getResolution was null, expected non-null int.'); - final VideoQuality? arg_quality = - args[1] == null ? null : VideoQuality.values[args[1] as int]; - assert(arg_quality != null, - 'Argument for dev.flutter.pigeon.QualitySelectorHostApi.getResolution was null, expected non-null VideoQuality.'); - final ResolutionInfo output = - api.getResolution(arg_cameraInfoId!, arg_quality!); - return [output]; - }); - } - } - } -} - -abstract class TestFallbackStrategyHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - void create(int identifier, VideoQuality quality, - VideoResolutionFallbackRule fallbackRule); - - static void setup(TestFallbackStrategyHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FallbackStrategyHostApi.create', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.FallbackStrategyHostApi.create was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.FallbackStrategyHostApi.create was null, expected non-null int.'); - final VideoQuality? arg_quality = - args[1] == null ? null : VideoQuality.values[args[1] as int]; - assert(arg_quality != null, - 'Argument for dev.flutter.pigeon.FallbackStrategyHostApi.create was null, expected non-null VideoQuality.'); - final VideoResolutionFallbackRule? arg_fallbackRule = args[2] == null - ? null - : VideoResolutionFallbackRule.values[args[2] as int]; - assert(arg_fallbackRule != null, - 'Argument for dev.flutter.pigeon.FallbackStrategyHostApi.create was null, expected non-null VideoResolutionFallbackRule.'); - api.create(arg_identifier!, arg_quality!, arg_fallbackRule!); - return []; - }); - } - } - } -} - -abstract class TestCameraControlHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - Future enableTorch(int identifier, bool torch); - - Future setZoomRatio(int identifier, double ratio); - - Future startFocusAndMetering(int identifier, int focusMeteringActionId); - - Future cancelFocusAndMetering(int identifier); - - Future setExposureCompensationIndex(int identifier, int index); - - static void setup(TestCameraControlHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraControlHostApi.enableTorch', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.CameraControlHostApi.enableTorch was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.CameraControlHostApi.enableTorch was null, expected non-null int.'); - final bool? arg_torch = (args[1] as bool?); - assert(arg_torch != null, - 'Argument for dev.flutter.pigeon.CameraControlHostApi.enableTorch was null, expected non-null bool.'); - await api.enableTorch(arg_identifier!, arg_torch!); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraControlHostApi.setZoomRatio', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.CameraControlHostApi.setZoomRatio was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.CameraControlHostApi.setZoomRatio was null, expected non-null int.'); - final double? arg_ratio = (args[1] as double?); - assert(arg_ratio != null, - 'Argument for dev.flutter.pigeon.CameraControlHostApi.setZoomRatio was null, expected non-null double.'); - await api.setZoomRatio(arg_identifier!, arg_ratio!); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraControlHostApi.startFocusAndMetering', - codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.CameraControlHostApi.startFocusAndMetering was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.CameraControlHostApi.startFocusAndMetering was null, expected non-null int.'); - final int? arg_focusMeteringActionId = (args[1] as int?); - assert(arg_focusMeteringActionId != null, - 'Argument for dev.flutter.pigeon.CameraControlHostApi.startFocusAndMetering was null, expected non-null int.'); - final int? output = await api.startFocusAndMetering( - arg_identifier!, arg_focusMeteringActionId!); - return [output]; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraControlHostApi.cancelFocusAndMetering', - codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.CameraControlHostApi.cancelFocusAndMetering was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.CameraControlHostApi.cancelFocusAndMetering was null, expected non-null int.'); - await api.cancelFocusAndMetering(arg_identifier!); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CameraControlHostApi.setExposureCompensationIndex', - codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.CameraControlHostApi.setExposureCompensationIndex was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.CameraControlHostApi.setExposureCompensationIndex was null, expected non-null int.'); - final int? arg_index = (args[1] as int?); - assert(arg_index != null, - 'Argument for dev.flutter.pigeon.CameraControlHostApi.setExposureCompensationIndex was null, expected non-null int.'); - final int? output = await api.setExposureCompensationIndex( - arg_identifier!, arg_index!); - return [output]; - }); - } - } - } -} - -class _TestFocusMeteringActionHostApiCodec extends StandardMessageCodec { - const _TestFocusMeteringActionHostApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is MeteringPointInfo) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); - } else { - super.writeValue(buffer, value); - } - } - - @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return MeteringPointInfo.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } - } -} - -abstract class TestFocusMeteringActionHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = - _TestFocusMeteringActionHostApiCodec(); - - void create(int identifier, List meteringPointInfos, - bool? disableAutoCancel); - - static void setup(TestFocusMeteringActionHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FocusMeteringActionHostApi.create', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.FocusMeteringActionHostApi.create was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.FocusMeteringActionHostApi.create was null, expected non-null int.'); - final List? arg_meteringPointInfos = - (args[1] as List?)?.cast(); - assert(arg_meteringPointInfos != null, - 'Argument for dev.flutter.pigeon.FocusMeteringActionHostApi.create was null, expected non-null List.'); - final bool? arg_disableAutoCancel = (args[2] as bool?); - api.create( - arg_identifier!, arg_meteringPointInfos!, arg_disableAutoCancel); - return []; - }); - } - } - } -} - -abstract class TestFocusMeteringResultHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - bool isFocusSuccessful(int identifier); - - static void setup(TestFocusMeteringResultHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.FocusMeteringResultHostApi.isFocusSuccessful', - codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.FocusMeteringResultHostApi.isFocusSuccessful was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.FocusMeteringResultHostApi.isFocusSuccessful was null, expected non-null int.'); - final bool output = api.isFocusSuccessful(arg_identifier!); - return [output]; - }); - } - } - } -} - -abstract class TestMeteringPointHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - void create( - int identifier, double x, double y, double? size, int cameraInfoId); - - double getDefaultPointSize(); - - static void setup(TestMeteringPointHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.MeteringPointHostApi.create', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.MeteringPointHostApi.create was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.MeteringPointHostApi.create was null, expected non-null int.'); - final double? arg_x = (args[1] as double?); - assert(arg_x != null, - 'Argument for dev.flutter.pigeon.MeteringPointHostApi.create was null, expected non-null double.'); - final double? arg_y = (args[2] as double?); - assert(arg_y != null, - 'Argument for dev.flutter.pigeon.MeteringPointHostApi.create was null, expected non-null double.'); - final double? arg_size = (args[3] as double?); - final int? arg_cameraInfoId = (args[4] as int?); - assert(arg_cameraInfoId != null, - 'Argument for dev.flutter.pigeon.MeteringPointHostApi.create was null, expected non-null int.'); - api.create( - arg_identifier!, arg_x!, arg_y!, arg_size, arg_cameraInfoId!); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.MeteringPointHostApi.getDefaultPointSize', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - // ignore message - final double output = api.getDefaultPointSize(); - return [output]; - }); - } - } - } -} - -class _TestCaptureRequestOptionsHostApiCodec extends StandardMessageCodec { - const _TestCaptureRequestOptionsHostApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is CameraPermissionsErrorData) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); - } else if (value is CameraStateTypeData) { - buffer.putUint8(129); - writeValue(buffer, value.encode()); - } else if (value is ExposureCompensationRange) { - buffer.putUint8(130); - writeValue(buffer, value.encode()); - } else if (value is LiveDataSupportedTypeData) { - buffer.putUint8(131); - writeValue(buffer, value.encode()); - } else if (value is MeteringPointInfo) { - buffer.putUint8(132); - writeValue(buffer, value.encode()); - } else if (value is ResolutionInfo) { - buffer.putUint8(133); - writeValue(buffer, value.encode()); - } else if (value is VideoQualityData) { - buffer.putUint8(134); - writeValue(buffer, value.encode()); - } else if (value is VideoRecordEventData) { - buffer.putUint8(135); - writeValue(buffer, value.encode()); - } else { - super.writeValue(buffer, value); - } - } - - @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return CameraPermissionsErrorData.decode(readValue(buffer)!); - case 129: - return CameraStateTypeData.decode(readValue(buffer)!); - case 130: - return ExposureCompensationRange.decode(readValue(buffer)!); - case 131: - return LiveDataSupportedTypeData.decode(readValue(buffer)!); - case 132: - return MeteringPointInfo.decode(readValue(buffer)!); - case 133: - return ResolutionInfo.decode(readValue(buffer)!); - case 134: - return VideoQualityData.decode(readValue(buffer)!); - case 135: - return VideoRecordEventData.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } - } -} - -abstract class TestCaptureRequestOptionsHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = - _TestCaptureRequestOptionsHostApiCodec(); - - void create(int identifier, Map options); - - static void setup(TestCaptureRequestOptionsHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.CaptureRequestOptionsHostApi.create', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.CaptureRequestOptionsHostApi.create was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.CaptureRequestOptionsHostApi.create was null, expected non-null int.'); - final Map? arg_options = - (args[1] as Map?)?.cast(); - assert(arg_options != null, - 'Argument for dev.flutter.pigeon.CaptureRequestOptionsHostApi.create was null, expected non-null Map.'); - api.create(arg_identifier!, arg_options!); - return []; - }); - } - } - } -} - -abstract class TestCamera2CameraControlHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - void create(int identifier, int cameraControlIdentifier); - - Future addCaptureRequestOptions( - int identifier, int captureRequestOptionsIdentifier); - - static void setup(TestCamera2CameraControlHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.Camera2CameraControlHostApi.create', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.Camera2CameraControlHostApi.create was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.Camera2CameraControlHostApi.create was null, expected non-null int.'); - final int? arg_cameraControlIdentifier = (args[1] as int?); - assert(arg_cameraControlIdentifier != null, - 'Argument for dev.flutter.pigeon.Camera2CameraControlHostApi.create was null, expected non-null int.'); - api.create(arg_identifier!, arg_cameraControlIdentifier!); - return []; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.Camera2CameraControlHostApi.addCaptureRequestOptions', - codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.Camera2CameraControlHostApi.addCaptureRequestOptions was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.Camera2CameraControlHostApi.addCaptureRequestOptions was null, expected non-null int.'); - final int? arg_captureRequestOptionsIdentifier = (args[1] as int?); - assert(arg_captureRequestOptionsIdentifier != null, - 'Argument for dev.flutter.pigeon.Camera2CameraControlHostApi.addCaptureRequestOptions was null, expected non-null int.'); - await api.addCaptureRequestOptions( - arg_identifier!, arg_captureRequestOptionsIdentifier!); - return []; - }); - } - } - } -} - -class _TestResolutionFilterHostApiCodec extends StandardMessageCodec { - const _TestResolutionFilterHostApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is ResolutionInfo) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); - } else { - super.writeValue(buffer, value); - } - } - - @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return ResolutionInfo.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } - } -} - -abstract class TestResolutionFilterHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = - _TestResolutionFilterHostApiCodec(); - - void createWithOnePreferredSize( - int identifier, ResolutionInfo preferredResolution); - - static void setup(TestResolutionFilterHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.ResolutionFilterHostApi.createWithOnePreferredSize', - codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.ResolutionFilterHostApi.createWithOnePreferredSize was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.ResolutionFilterHostApi.createWithOnePreferredSize was null, expected non-null int.'); - final ResolutionInfo? arg_preferredResolution = - (args[1] as ResolutionInfo?); - assert(arg_preferredResolution != null, - 'Argument for dev.flutter.pigeon.ResolutionFilterHostApi.createWithOnePreferredSize was null, expected non-null ResolutionInfo.'); - api.createWithOnePreferredSize( - arg_identifier!, arg_preferredResolution!); - return []; - }); - } - } - } -} - -abstract class TestCamera2CameraInfoHostApi { - static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => - TestDefaultBinaryMessengerBinding.instance; - static const MessageCodec codec = StandardMessageCodec(); - - int createFrom(int cameraInfoIdentifier); - - int getSupportedHardwareLevel(int identifier); - - String getCameraId(int identifier); - - int getSensorOrientation(int identifier); - - static void setup(TestCamera2CameraInfoHostApi? api, - {BinaryMessenger? binaryMessenger}) { - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.Camera2CameraInfoHostApi.createFrom', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.Camera2CameraInfoHostApi.createFrom was null.'); - final List args = (message as List?)!; - final int? arg_cameraInfoIdentifier = (args[0] as int?); - assert(arg_cameraInfoIdentifier != null, - 'Argument for dev.flutter.pigeon.Camera2CameraInfoHostApi.createFrom was null, expected non-null int.'); - final int output = api.createFrom(arg_cameraInfoIdentifier!); - return [output]; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.Camera2CameraInfoHostApi.getSupportedHardwareLevel', - codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.Camera2CameraInfoHostApi.getSupportedHardwareLevel was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.Camera2CameraInfoHostApi.getSupportedHardwareLevel was null, expected non-null int.'); - final int output = api.getSupportedHardwareLevel(arg_identifier!); - return [output]; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.Camera2CameraInfoHostApi.getCameraId', codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.Camera2CameraInfoHostApi.getCameraId was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.Camera2CameraInfoHostApi.getCameraId was null, expected non-null int.'); - final String output = api.getCameraId(arg_identifier!); - return [output]; - }); - } - } - { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.Camera2CameraInfoHostApi.getSensorOrientation', - codec, - binaryMessenger: binaryMessenger); - if (api == null) { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, null); - } else { - _testBinaryMessengerBinding!.defaultBinaryMessenger - .setMockDecodedMessageHandler(channel, - (Object? message) async { - assert(message != null, - 'Argument for dev.flutter.pigeon.Camera2CameraInfoHostApi.getSensorOrientation was null.'); - final List args = (message as List?)!; - final int? arg_identifier = (args[0] as int?); - assert(arg_identifier != null, - 'Argument for dev.flutter.pigeon.Camera2CameraInfoHostApi.getSensorOrientation was null, expected non-null int.'); - final int output = api.getSensorOrientation(arg_identifier!); - return [output]; - }); - } - } - } -} diff --git a/packages/camera/camera_android_camerax/test/video_capture_test.dart b/packages/camera/camera_android_camerax/test/video_capture_test.dart deleted file mode 100644 index c5fd1f078b91..000000000000 --- a/packages/camera/camera_android_camerax/test/video_capture_test.dart +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/camerax_library.g.dart'; -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:camera_android_camerax/src/recorder.dart'; -import 'package:camera_android_camerax/src/surface.dart'; -import 'package:camera_android_camerax/src/video_capture.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; -import 'package:mockito/mockito.dart'; - -import 'test_camerax_library.g.dart'; -import 'video_capture_test.mocks.dart'; - -@GenerateMocks( - [TestVideoCaptureHostApi, TestInstanceManagerHostApi, Recorder]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - test('withOutput calls the Java side and returns correct video capture', - () async { - final MockTestVideoCaptureHostApi mockApi = MockTestVideoCaptureHostApi(); - TestVideoCaptureHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final Recorder mockRecorder = MockRecorder(); - const int mockRecorderId = 2; - instanceManager.addHostCreatedInstance(mockRecorder, mockRecorderId, - onCopy: (_) => MockRecorder()); - - final VideoCapture videoCapture = - VideoCapture.detached(instanceManager: instanceManager); - const int videoCaptureId = 3; - instanceManager.addHostCreatedInstance(videoCapture, videoCaptureId, - onCopy: (_) => VideoCapture.detached(instanceManager: instanceManager)); - - when(mockApi.withOutput(mockRecorderId)).thenReturn(videoCaptureId); - - expect( - await VideoCapture.withOutput(mockRecorder, - instanceManager: instanceManager), - videoCapture); - verify(mockApi.withOutput(mockRecorderId)); - }); - - test( - 'setTargetRotation makes call to set target rotation for VideoCapture instance', - () async { - final MockTestVideoCaptureHostApi mockApi = MockTestVideoCaptureHostApi(); - TestVideoCaptureHostApi.setup(mockApi); - - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - const int targetRotation = Surface.rotation180; - final VideoCapture videoCapture = VideoCapture.detached( - instanceManager: instanceManager, - ); - instanceManager.addHostCreatedInstance( - videoCapture, - 0, - onCopy: (_) => VideoCapture.detached(instanceManager: instanceManager), - ); - - await videoCapture.setTargetRotation(targetRotation); - - verify(mockApi.setTargetRotation( - instanceManager.getIdentifier(videoCapture), targetRotation)); - }); - - test('getOutput calls the Java side and returns correct Recorder', () async { - final MockTestVideoCaptureHostApi mockApi = MockTestVideoCaptureHostApi(); - TestVideoCaptureHostApi.setup(mockApi); - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final VideoCapture videoCapture = - VideoCapture.detached(instanceManager: instanceManager); - const int videoCaptureId = 2; - instanceManager.addHostCreatedInstance(videoCapture, videoCaptureId, - onCopy: (_) => VideoCapture.detached(instanceManager: instanceManager)); - - final Recorder mockRecorder = MockRecorder(); - const int mockRecorderId = 3; - instanceManager.addHostCreatedInstance(mockRecorder, mockRecorderId, - onCopy: (_) => Recorder.detached(instanceManager: instanceManager)); - - when(mockApi.getOutput(videoCaptureId)).thenReturn(mockRecorderId); - expect(await videoCapture.getOutput(), mockRecorder); - verify(mockApi.getOutput(videoCaptureId)); - }); - - test('flutterApiCreateTest', () async { - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - - final VideoCaptureFlutterApi flutterApi = VideoCaptureFlutterApiImpl( - instanceManager: instanceManager, - ); - - flutterApi.create(0); - - expect( - instanceManager.getInstanceWithWeakReference(0), isA()); - }); -} diff --git a/packages/camera/camera_android_camerax/test/video_capture_test.mocks.dart b/packages/camera/camera_android_camerax/test/video_capture_test.mocks.dart deleted file mode 100644 index 88ad98d462d0..000000000000 --- a/packages/camera/camera_android_camerax/test/video_capture_test.mocks.dart +++ /dev/null @@ -1,126 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/video_capture_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i5; - -import 'package:camera_android_camerax/src/pending_recording.dart' as _i2; -import 'package:camera_android_camerax/src/recorder.dart' as _i4; -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i3; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -class _FakePendingRecording_0 extends _i1.SmartFake - implements _i2.PendingRecording { - _FakePendingRecording_0( - Object parent, - Invocation parentInvocation, - ) : super( - parent, - parentInvocation, - ); -} - -/// A class which mocks [TestVideoCaptureHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestVideoCaptureHostApi extends _i1.Mock - implements _i3.TestVideoCaptureHostApi { - MockTestVideoCaptureHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - int withOutput(int? videoOutputId) => (super.noSuchMethod( - Invocation.method( - #withOutput, - [videoOutputId], - ), - returnValue: 0, - ) as int); - - @override - int getOutput(int? identifier) => (super.noSuchMethod( - Invocation.method( - #getOutput, - [identifier], - ), - returnValue: 0, - ) as int); - - @override - void setTargetRotation( - int? identifier, - int? rotation, - ) => - super.noSuchMethod( - Invocation.method( - #setTargetRotation, - [ - identifier, - rotation, - ], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i3.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [Recorder]. -/// -/// See the documentation for Mockito's code generation for more information. -// ignore: must_be_immutable -class MockRecorder extends _i1.Mock implements _i4.Recorder { - MockRecorder() { - _i1.throwOnMissingStub(this); - } - - @override - _i5.Future<_i2.PendingRecording> prepareRecording(String? path) => - (super.noSuchMethod( - Invocation.method( - #prepareRecording, - [path], - ), - returnValue: - _i5.Future<_i2.PendingRecording>.value(_FakePendingRecording_0( - this, - Invocation.method( - #prepareRecording, - [path], - ), - )), - ) as _i5.Future<_i2.PendingRecording>); -} diff --git a/packages/camera/camera_android_camerax/test/zoom_state_test.dart b/packages/camera/camera_android_camerax/test/zoom_state_test.dart deleted file mode 100644 index c36fa8689b39..000000000000 --- a/packages/camera/camera_android_camerax/test/zoom_state_test.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2013 The Flutter Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import 'package:camera_android_camerax/src/instance_manager.dart'; -import 'package:camera_android_camerax/src/zoom_state.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mockito/annotations.dart'; - -import 'test_camerax_library.g.dart'; -import 'zoom_state_test.mocks.dart'; - -@GenerateMocks([TestInstanceManagerHostApi]) -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - - // Mocks the call to clear the native InstanceManager. - TestInstanceManagerHostApi.setup(MockTestInstanceManagerHostApi()); - - group('ZoomState', () { - test('flutterApi create makes call to create expected ZoomState', () { - final InstanceManager instanceManager = InstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final ZoomStateFlutterApiImpl flutterApi = ZoomStateFlutterApiImpl( - instanceManager: instanceManager, - ); - const int zoomStateIdentifier = 68; - const double minZoomRatio = 0; - const double maxZoomRatio = 1; - - flutterApi.create(zoomStateIdentifier, minZoomRatio, maxZoomRatio); - - final ZoomState instance = instanceManager - .getInstanceWithWeakReference(zoomStateIdentifier)! as ZoomState; - expect(instance.minZoomRatio, equals(minZoomRatio)); - expect(instance.maxZoomRatio, equals(maxZoomRatio)); - }); - }); -} diff --git a/packages/camera/camera_android_camerax/test/zoom_state_test.mocks.dart b/packages/camera/camera_android_camerax/test/zoom_state_test.mocks.dart deleted file mode 100644 index d7ebec42469a..000000000000 --- a/packages/camera/camera_android_camerax/test/zoom_state_test.mocks.dart +++ /dev/null @@ -1,40 +0,0 @@ -// Mocks generated by Mockito 5.4.4 from annotations -// in camera_android_camerax/test/zoom_state_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'package:mockito/mockito.dart' as _i1; - -import 'test_camerax_library.g.dart' as _i2; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class - -/// A class which mocks [TestInstanceManagerHostApi]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockTestInstanceManagerHostApi extends _i1.Mock - implements _i2.TestInstanceManagerHostApi { - MockTestInstanceManagerHostApi() { - _i1.throwOnMissingStub(this); - } - - @override - void clear() => super.noSuchMethod( - Invocation.method( - #clear, - [], - ), - returnValueForMissingStub: null, - ); -}