diff --git a/.ci.yaml b/.ci.yaml index 35d4b2ec2000..df3291f8b147 100644 --- a/.ci.yaml +++ b/.ci.yaml @@ -327,10 +327,10 @@ targets: timeout: 30 properties: target_file: analyze_legacy.yaml - channel: "3.35.7" + channel: "3.38.10" env_variables: >- { - "CHANNEL": "3.35.7" + "CHANNEL": "3.38.10" } - name: Linux analyze_legacy N-2 @@ -338,10 +338,10 @@ targets: timeout: 30 properties: target_file: analyze_legacy.yaml - channel: "3.32.8" + channel: "3.35.7" env_variables: >- { - "CHANNEL": "3.32.8" + "CHANNEL": "3.35.7" } - name: Linux_android custom_package_tests master diff --git a/.ci/flutter_master.version b/.ci/flutter_master.version index c540c5dee9c3..21aae04dd65f 100644 --- a/.ci/flutter_master.version +++ b/.ci/flutter_master.version @@ -1 +1 @@ -d438df35f998afd21dbab98081a4211305e766a2 +82d96ef98a33f3f35dabf7795e701f8a4d2d4bec diff --git a/.ci/flutter_stable.version b/.ci/flutter_stable.version index 0cbbf6674df9..ad241bc2bef7 100644 --- a/.ci/flutter_stable.version +++ b/.ci/flutter_stable.version @@ -1 +1 @@ -19074d12f7eaf6a8180cd4036a430c1d76de904e +2c9eb20739dfec95e2c74bd3dfa4601b0a8a36aa diff --git a/.ci/scripts/create_all_packages_app.sh b/.ci/scripts/create_all_packages_app.sh index a295e876bc54..fa68c1c62111 100755 --- a/.ci/scripts/create_all_packages_app.sh +++ b/.ci/scripts/create_all_packages_app.sh @@ -10,10 +10,11 @@ exclusions=("script/configs/exclude_all_packages_app.yaml") # Add a wasm-specific exclusion file if "--wasm" is specified. if [[ "$1" == "--wasm" ]]; then exclusions+=",script/configs/exclude_all_packages_app_wasm.yaml" + shift 1 fi # Delete ./all_packages if it exists already rm -rf ./all_packages dart ./script/tool/bin/flutter_plugin_tools.dart create-all-packages-app \ - --output-dir=. --exclude "$exclusions" + --output-dir=. --exclude "$exclusions" "$@" diff --git a/.ci/scripts/enable_swift_package_manager.sh b/.ci/scripts/enable_swift_package_manager.sh new file mode 100755 index 000000000000..d8d789e7da95 --- /dev/null +++ b/.ci/scripts/enable_swift_package_manager.sh @@ -0,0 +1,7 @@ +#!/bin/bash +# Copyright 2013 The Flutter Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. +set -e + +flutter config --enable-swift-package-manager diff --git a/.ci/scripts/plugin_tools_tests.sh b/.ci/scripts/plugin_tools_tests.sh index fa2e98342442..a7658d18e504 100755 --- a/.ci/scripts/plugin_tools_tests.sh +++ b/.ci/scripts/plugin_tools_tests.sh @@ -5,4 +5,4 @@ set -e cd script/tool -dart pub run test +dart test diff --git a/.ci/targets/ios_build_all_packages.yaml b/.ci/targets/ios_build_all_packages.yaml index cae80e605d3e..3085f2bada5d 100644 --- a/.ci/targets/ios_build_all_packages.yaml +++ b/.ci/targets/ios_build_all_packages.yaml @@ -2,12 +2,11 @@ tasks: - name: prepare tool script: .ci/scripts/prepare_tool.sh infra_step: true # Note infra steps failing prevents "always" from running. - - name: download Dart and iOS deps - script: .ci/scripts/tool_runner.sh - args: ["fetch-deps", "--ios", "--supporting-target-platforms-only"] - infra_step: true - name: create all_packages app script: .ci/scripts/create_all_packages_app.sh + # build-examples builds with Swift Package Manager, so run build-all without + # it to test both modes in CI. + args: ["--no-swift-package-manager"] infra_step: true # Note infra steps failing prevents "always" from running. - name: build all_packages for iOS debug script: .ci/scripts/build_all_packages_app.sh diff --git a/.ci/targets/ios_platform_tests.yaml b/.ci/targets/ios_platform_tests.yaml index 262de31fb93f..4e10a6f091b7 100644 --- a/.ci/targets/ios_platform_tests.yaml +++ b/.ci/targets/ios_platform_tests.yaml @@ -2,12 +2,16 @@ tasks: - name: prepare tool script: .ci/scripts/prepare_tool.sh infra_step: true # Note infra steps failing prevents "always" from running. + - name: enable Swift Package Manager + # For consistency between stable and master channels, enable SwiftPM. + # TODO(stuartmorgan): Remove this step once it's the default on stable. + script: .ci/scripts/enable_swift_package_manager.sh - name: create simulator script: .ci/scripts/create_simulator.sh infra_step: true # Note infra steps failing prevents "always" from running. - name: download Dart and iOS deps script: .ci/scripts/tool_runner.sh - args: ["fetch-deps", "--ios", "--supporting-target-platforms-only"] + args: ["fetch-deps", "--ios", "--supporting-target-platforms-only", "--swift-package-manager"] infra_step: true - name: build examples script: .ci/scripts/tool_runner.sh diff --git a/.ci/targets/macos_build_all_packages.yaml b/.ci/targets/macos_build_all_packages.yaml index b576457a1eef..115d4a2c6a28 100644 --- a/.ci/targets/macos_build_all_packages.yaml +++ b/.ci/targets/macos_build_all_packages.yaml @@ -2,12 +2,11 @@ tasks: - name: prepare tool script: .ci/scripts/prepare_tool.sh infra_step: true # Note infra steps failing prevents "always" from running. - - name: download Dart and macOS deps - script: .ci/scripts/tool_runner.sh - args: ["fetch-deps", "--macos", "--supporting-target-platforms-only"] - infra_step: true - name: create all_packages app script: .ci/scripts/create_all_packages_app.sh + # build-examples builds with Swift Package Manager, so run build-all without + # it to test both modes in CI. + args: ["--no-swift-package-manager"] infra_step: true # Note infra steps failing prevents "always" from running. - name: build all_packages for macOS debug script: .ci/scripts/build_all_packages_app.sh diff --git a/.ci/targets/macos_platform_tests.yaml b/.ci/targets/macos_platform_tests.yaml index 6756fa7e490f..fd2a1767cc2f 100644 --- a/.ci/targets/macos_platform_tests.yaml +++ b/.ci/targets/macos_platform_tests.yaml @@ -2,9 +2,13 @@ tasks: - name: prepare tool script: .ci/scripts/prepare_tool.sh infra_step: true # Note infra steps failing prevents "always" from running. + - name: enable Swift Package Manager + # For consistency between stable and master channels, enable SwiftPM. + # TODO(stuartmorgan): Remove this step once it's the default on stable. + script: .ci/scripts/enable_swift_package_manager.sh - name: download Dart and macOS deps script: .ci/scripts/tool_runner.sh - args: ["fetch-deps", "--macos", "--supporting-target-platforms-only"] + args: ["fetch-deps", "--macos", "--supporting-target-platforms-only", "--swift-package-manager"] infra_step: true - name: build examples script: .ci/scripts/tool_runner.sh diff --git a/.ci/targets/macos_repo_checks.yaml b/.ci/targets/macos_repo_checks.yaml index 95fa5774f69e..8a349dec1c7d 100644 --- a/.ci/targets/macos_repo_checks.yaml +++ b/.ci/targets/macos_repo_checks.yaml @@ -13,5 +13,5 @@ tasks: always: true - name: validate iOS and macOS podspecs script: .ci/scripts/tool_runner.sh - args: ["podspec-check", "--exclude=script/configs/exclude_xcode_deprecation.yaml"] + args: ["podspec-check"] always: true diff --git a/.ci/targets/repo_checks.yaml b/.ci/targets/repo_checks.yaml index eb4071651fe5..924468351134 100644 --- a/.ci/targets/repo_checks.yaml +++ b/.ci/targets/repo_checks.yaml @@ -28,7 +28,7 @@ tasks: script: .ci/scripts/tool_runner.sh args: - "pubspec-check" - - "--min-min-flutter-version=3.32.0" + - "--min-min-flutter-version=3.35.0" - "--allow-dependencies=script/configs/allowed_unpinned_deps.yaml" - "--allow-pinned-dependencies=script/configs/allowed_pinned_deps.yaml" always: true diff --git a/.gemini/config.yaml b/.gemini/config.yaml index ecd4cfa8238a..35254d877a8c 100644 --- a/.gemini/config.yaml +++ b/.gemini/config.yaml @@ -11,6 +11,7 @@ code_review: # These tend to be verbose, and since we expect PR authors to clearly # describe their PRs this would be at best duplicative. summary: false + include_drafts: false ignore_patterns: - .ci/flutter_master.version - .ci/flutter_stable.version diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 93e584bd981c..e4cbdb490fc3 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -5,13 +5,13 @@ ## Pre-Review Checklist - [ ] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. +- [ ] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [ ] I read the [Tree Hygiene] page, which explains my responsibilities. - [ ] I read and followed the [relevant style guides] and ran [the auto-formatter]. - [ ] I signed the [CLA]. - [ ] The title of the PR starts with the name of the package surrounded by square brackets, e.g. `[shared_preferences]` - [ ] I [linked to at least one issue that this PR fixes] in the description above. -- [ ] I updated `pubspec.yaml` with an appropriate new version according to the [pub versioning philosophy], or I have commented below to indicate which [version change exemption] this PR falls under[^1]. -- [ ] I updated `CHANGELOG.md` to add a description of the change, [following repository CHANGELOG style], or I have commented below to indicate which [CHANGELOG exemption] this PR falls under[^1]. +- [ ] I followed [the version and CHANGELOG instructions], using [semantic versioning] and the [repository CHANGELOG style], or I have commented below to indicate which documented exception this PR falls under[^1]. - [ ] I updated/added any relevant documentation (doc comments with `///`). - [ ] I added new tests to check the change I am making, or I have commented below to indicate which [test exemption] this PR falls under[^1]. - [ ] All existing and new tests are passing. @@ -24,14 +24,14 @@ If you need help, consider asking for advice on the #hackers-new channel on [Dis [Contributor Guide]: https://github.com/flutter/packages/blob/main/CONTRIBUTING.md +[AI contribution guidelines]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#ai-contribution-guidelines [Tree Hygiene]: https://github.com/flutter/flutter/blob/master/docs/contributing/Tree-hygiene.md [relevant style guides]: https://github.com/flutter/packages/blob/main/CONTRIBUTING.md#style [the auto-formatter]: https://github.com/flutter/packages/blob/main/script/tool/README.md#format-code [CLA]: https://cla.developers.google.com/ [Discord]: https://github.com/flutter/flutter/blob/master/docs/contributing/Chat.md [linked to at least one issue that this PR fixes]: https://github.com/flutter/flutter/blob/master/docs/contributing/Tree-hygiene.md#overview -[pub versioning philosophy]: https://dart.dev/tools/pub/versioning -[version change exemption]: https://github.com/flutter/flutter/blob/master/docs/ecosystem/contributing/README.md#version -[following repository CHANGELOG style]: https://github.com/flutter/flutter/blob/master/docs/ecosystem/contributing/README.md#changelog-style -[CHANGELOG exemption]: https://github.com/flutter/flutter/blob/master/docs/ecosystem/contributing/README.md#changelog +[the version and CHANGELOG instructions]: https://github.com/flutter/flutter/blob/master/docs/ecosystem/contributing/README.md#version-and-changelog-updates +[semantic versioning]: https://dart.dev/tools/pub/versioning#semantic-versions +[repository CHANGELOG style]: https://github.com/flutter/flutter/blob/master/docs/ecosystem/contributing/README.md#changelog-style [test exemption]: https://github.com/flutter/flutter/blob/master/docs/contributing/Tree-hygiene.md#tests diff --git a/.github/labeler.yml b/.github/labeler.yml index ecd5359bbc91..a6ad7f620776 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -18,6 +18,11 @@ - any-glob-to-any-file: - third_party/packages/cupertino_icons/**/* +'p: cupertino_ui': + - changed-files: + - any-glob-to-any-file: + - third_party/packages/cupertino_ui/**/* + 'p: espresso': - changed-files: - any-glob-to-any-file: @@ -109,6 +114,11 @@ - any-glob-to-any-file: - packages/local_auth/**/* +'p: material_ui': + - changed-files: + - any-glob-to-any-file: + - packages/material_ui/**/* + 'p: metrics_center': - changed-files: - any-glob-to-any-file: @@ -266,9 +276,11 @@ - changed-files: - any-glob-to-any-file: - packages/animations/**/* + - packages/cupertino_ui/**/* - packages/flutter_lints/**/* - packages/go_router/**/* - packages/go_router_builder/**/* - packages/google_fonts/**/* + - packages/material_ui/**/* - packages/two_dimensional_scrollables/**/* - third_party/packages/cupertino_icons/**/* diff --git a/.github/remove_cicd.yml b/.github/remove_cicd.yml new file mode 100644 index 000000000000..6f5ff9d0596f --- /dev/null +++ b/.github/remove_cicd.yml @@ -0,0 +1,65 @@ +# Copyright 2024 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. + +name: Remove outdated CICD Label + +on: + pull_request_target: + types: [synchronize] + +permissions: + pull-requests: write + issues: write + +jobs: + remove_cicd_label: + if: contains(github.event.pull_request.labels.*.name, 'CICD') + runs-on: ubuntu-latest + steps: + - name: Check if label was added before push + id: check_timing + run: | + # Get push time (commit date of the head SHA) + PUSH_TIME='${{ github.event.pull_request.updated_at }}' + echo "Push time: $PUSH_TIME" + + # Get latest CICD labeling event time from the last 100 events + LABEL_TIME=$(gh api graphql -f query=' + query($owner: String!, $repo: String!, $pr: Int!) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $pr) { + timelineItems(last: 100, itemTypes: [LABELED_EVENT]) { + nodes { + ... on LabeledEvent { + label { name } + createdAt + } + } + } + } + } + }' -f owner=${{ github.repository_owner }} -f repo=${{ github.event.repository.name }} -F pr=${{ github.event.pull_request.number }} \ + --jq '.data.repository.pullRequest.timelineItems.nodes | map(select(.label.name == "CICD")) | last | .createdAt') + echo "Label time: $LABEL_TIME" + + if [[ -z "$LABEL_TIME" ]]; then + # Label exists on PR (checked by job 'if') but not in last 100 events -> must be very old + echo "should_remove=true" >> "$GITHUB_OUTPUT" + echo "Result: Label found on PR but not in recent timeline events. Assuming it is old." + elif [[ "$LABEL_TIME" < "$PUSH_TIME" ]]; then + echo "should_remove=true" >> "$GITHUB_OUTPUT" + echo "Result: Label added at $LABEL_TIME is older than push at $PUSH_TIME. Removing." + else + echo "should_remove=false" >> "$GITHUB_OUTPUT" + echo "Result: Label added at $LABEL_TIME is newer than or same as push at $PUSH_TIME. Skipping removal." + fi + env: + GITHUB_TOKEN: ${{ github.token }} + + - name: Remove outdated CICD label + if: steps.check_timing.outputs.should_remove == 'true' + run: | + gh pr edit ${{ github.event.pull_request.number }} -R ${{ github.repository }} --remove-label "CICD" + env: + GITHUB_TOKEN: ${{ github.token }} diff --git a/.github/workflows/batch_release_pr.yml b/.github/workflows/batch_release_pr.yml index 420009798588..2baaf81fa0ba 100644 --- a/.github/workflows/batch_release_pr.yml +++ b/.github/workflows/batch_release_pr.yml @@ -1,43 +1,68 @@ -name: "Creates Batch Release for A Package" +name: "Creates Batch Release for a Package" on: repository_dispatch: - types: [batch_release_pr] + types: [batch-release-pr] jobs: - create_release_pr: + create_batch_release_branch: runs-on: ubuntu-latest + permissions: + contents: write # Grants write permission to create a branch. env: BRANCH_NAME: ${{ github.event.client_payload.package }}-${{ github.run_id }}-${{ github.run_attempt }} + outputs: + branch_created: ${{ steps.check-branch-exists.outputs.exists }} steps: - name: checkout repository - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd + - name: "Install Flutter" + uses: ./.github/workflows/internals/install_flutter - name: Set up tools run: dart pub get working-directory: ${{ github.workspace }}/script/tool # This step is to create a branch for batch release # A branch may not be created if there is nothing to release. # In that case, the workflow will exit and complete successfully. - - name: create batch release PR + - name: create batch release branch run: | git config --global user.name ${{ secrets.USER_NAME }} git config --global user.email ${{ secrets.USER_EMAIL }} - dart ./script/tool/lib/src/main.dart branch-for-batch-release --packages=${{ github.event.client_payload.package }} --branch=${{ env.BRANCH_NAME }} --remote=origin + dart ./script/tool/lib/src/main.dart branch-for-batch-release --packages=${GITHUB_EVENT_CLIENT_PAYLOAD_PACKAGE} --branch=${BRANCH_NAME} --remote=origin + env: + GITHUB_EVENT_CLIENT_PAYLOAD_PACKAGE: ${{ github.event.client_payload.package }} - name: Check if branch was created id: check-branch-exists - uses: GuillaumeFalourd/branch-exists@v1.1 - with: - branch: ${{ env.BRANCH_NAME }} + run: | + if git show-ref --verify --quiet refs/heads/${BRANCH_NAME}; then + echo "exists=true" >> $GITHUB_OUTPUT + else + echo "exists=false" >> $GITHUB_OUTPUT + fi - - name: Create Pull Request - if: steps.check-branch-exists.outputs.exists == 'true' - uses: peter-evans/create-pull-request@v7 + create_release_pr: + needs: create_batch_release_branch + if: needs.create_batch_release_branch.outputs.branch_created == 'true' + runs-on: ubuntu-latest + permissions: + # The create-pull-request action needs both content and pull-requests permissions. + pull-requests: write + contents: write + env: + BRANCH_NAME: ${{ github.event.client_payload.package }}-${{ github.run_id }}-${{ github.run_attempt }} + steps: + - name: checkout repository + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd with: - token: ${{ secrets.GITHUB_TOKEN }} - commit-message: "[${{ github.event.client_payload.package }}] Batch release" - title: "[${{ github.event.client_payload.package }}] Batch release" - body: "This PR was created automatically to batch release the `${{ github.event.client_payload.package }}`." - branch: ${{ env.BRANCH_NAME }} - base: release + ref: ${{ env.BRANCH_NAME }} + - name: Create batch release PR + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + gh pr create \ + --base "release-${{ github.event.client_payload.package }}" \ + --head "${{ env.BRANCH_NAME }}" \ + --title "[${{ github.event.client_payload.package }}] Batch release" \ + --body "This PR was created automatically to batch release the \`${{ github.event.client_payload.package }}\`." diff --git a/.github/workflows/go_router_batch.yml b/.github/workflows/go_router_batch.yml index f07cb5b242c2..3687b074108d 100644 --- a/.github/workflows/go_router_batch.yml +++ b/.github/workflows/go_router_batch.yml @@ -1,6 +1,7 @@ name: "Creates Batch Release for go_router" on: + workflow_dispatch: schedule: # Run every Monday at 8:00 AM - cron: "0 8 * * 1" @@ -8,10 +9,11 @@ on: jobs: dispatch_release_pr: runs-on: ubuntu-latest + permissions: + contents: write steps: - name: Repository Dispatch - uses: peter-evans/repository-dispatch@v4 + uses: peter-evans/repository-dispatch@5fc4efd1a4797ddb68ffd0714a238564e4cc0e6f with: - token: "${{ secrets.GITHUB_TOKEN }}" - event-type: batch_release_pr + event-type: batch-release-pr client-payload: '{"package": "go_router"}' diff --git a/.github/workflows/internals/install_flutter/action.yml b/.github/workflows/internals/install_flutter/action.yml new file mode 100644 index 000000000000..e04d0cee3e54 --- /dev/null +++ b/.github/workflows/internals/install_flutter/action.yml @@ -0,0 +1,20 @@ +name: "Install Flutter" +description: "Installs a pinned version of Flutter" +runs: + using: "composite" + steps: + - name: "Install Flutter" + # This uses a pinned version of Flutter rather than `stable` so that it is + # not subject to out-of-band failures when new releases happen. It does + # not use the auto-rolled pin because there's no way for the autoroller + # to test the actual release flow, so changes would still show up in + # post-submit. A manually-rolled pin means that any changes here must be + # made deliberately, so that the person updating it knows to watch the + # next actual auto-release to ensure that it works, and knows to revert + # the change if it doesn't. + shell: bash + run: | + cd $HOME + git clone https://github.com/flutter/flutter.git --depth 1 -b 3.41.0 _flutter + echo "$HOME/_flutter/bin" >> $GITHUB_PATH + cd $GITHUB_WORKSPACE diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 835b40c18e3d..c86bbd62a607 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -16,29 +16,13 @@ jobs: contents: write runs-on: ubuntu-latest steps: - - name: "Install Flutter" - # Github Actions don't support templates so it is hard to share this snippet with another action - # If we eventually need to use this in more workflow, we could create a shell script that contains this - # snippet. - # - # This uses a pinned version of Flutter rather than `stable` so that it is - # not subject to out-of-band failures when new releases happen. It does - # not use the auto-rolled pin because there's no way for the autoroller - # to test the actual release flow, so changes would still show up in - # post-submit. A manually-rolled pin means that any changes here must be - # made deliberately, so that the person updating it knows to watch the - # next actual auto-release to ensure that it works, and knows to revert - # the change if it doesn't. - run: | - cd $HOME - git clone https://github.com/flutter/flutter.git --depth 1 -b 3.38.1 _flutter - echo "$HOME/_flutter/bin" >> $GITHUB_PATH - cd $GITHUB_WORKSPACE # Checks out a copy of the repo. - name: Check out code - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd with: fetch-depth: 0 # Fetch all history so the tool can get all the tags to determine version. + - name: "Install Flutter" + uses: ./.github/workflows/internals/install_flutter - name: Set up tools run: dart pub get working-directory: ${{ github.workspace }}/script/tool @@ -56,7 +40,7 @@ jobs: # because there doesn't appear to be anything to wait for. To avoid that, # explicitly wait for one LUCI test by name first. - name: Wait for test check-in - uses: lewagon/wait-on-check-action@0dceb95e7c4cad8cc7422aee3885998f5cab9c79 + uses: lewagon/wait-on-check-action@74049309dfeff245fe8009a0137eacf28136cb3c with: ref: ${{ github.sha }} check-name: 'Linux ci_yaml packages roller' @@ -68,7 +52,7 @@ jobs: # This workflow should be the last to run. So wait for all the other tests to succeed. - name: Wait on all tests - uses: lewagon/wait-on-check-action@0dceb95e7c4cad8cc7422aee3885998f5cab9c79 + uses: lewagon/wait-on-check-action@74049309dfeff245fe8009a0137eacf28136cb3c with: ref: ${{ github.sha }} running-workflow-name: 'release' diff --git a/.github/workflows/release_from_branches.yml b/.github/workflows/release_from_branches.yml new file mode 100644 index 000000000000..a235a2576ef3 --- /dev/null +++ b/.github/workflows/release_from_branches.yml @@ -0,0 +1,12 @@ +name: Batch Release +on: + push: + branches: + - 'release-go_router' +jobs: + release: + uses: ./.github/workflows/resuable_release.yml + with: + is-batch-release: true + branch-name: '${{ github.ref_name }}' + secrets: inherit diff --git a/.github/workflows/reusable_release.yml b/.github/workflows/reusable_release.yml new file mode 100644 index 000000000000..6d519bec1e0b --- /dev/null +++ b/.github/workflows/reusable_release.yml @@ -0,0 +1,84 @@ +name: Reusable Release +on: + workflow_call: + inputs: + is-batch-release: + required: true + type: boolean + branch-name: + required: true + type: string +# Declare default permissions as read only. +permissions: read-all +jobs: + release: + if: github.repository_owner == 'flutter' + name: release + permissions: + # Release needs to push a tag back to the repo. + contents: write + runs-on: ubuntu-latest + steps: + # Checks out a copy of the repo. + - name: Check out code + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd + with: + fetch-depth: 0 # Fetch all history so the tool can get all the tags to determine version. + ref: ${{ inputs.branch-name }} + - name: "Install Flutter" + uses: ./.github/workflows/internals/install_flutter + - name: Set up tools + run: dart pub get + working-directory: ${{ github.workspace }}/script/tool + + # Give some time for LUCI checks to start becoming populated. + # Because of latency in Github Webhooks, we need to wait for a while + # before being able to look at checks scheduled by LUCI. + - name: Give webhooks a minute + run: sleep 60s + shell: bash + + # The next step waits for all tests, but when there are issues with the + # hooks it can take a long time for the tests to even be registered. If + # "Wait on all tests" runs before that happens, it will pass immediately + # because there doesn't appear to be anything to wait for. To avoid that, + # explicitly wait for one LUCI test by name first. + - name: Wait for test check-in + uses: lewagon/wait-on-check-action@74049309dfeff245fe8009a0137eacf28136cb3c + with: + ref: ${{ github.sha }} + check-name: 'Linux ci_yaml packages roller' + repo-token: ${{ secrets.GITHUB_TOKEN }} + wait-interval: 30 # seconds + allowed-conclusions: success,neutral + # verbose:true will produce too many logs that hang github actions web UI. + verbose: false + + # This workflow should be the last to run. So wait for all the other tests to succeed. + - name: Wait on all tests + uses: lewagon/wait-on-check-action@74049309dfeff245fe8009a0137eacf28136cb3c + with: + ref: ${{ github.sha }} + running-workflow-name: 'release' + repo-token: ${{ secrets.GITHUB_TOKEN }} + wait-interval: 180 # seconds + allowed-conclusions: success,neutral + # verbose:true will produce too many logs that hang github actions web UI. + verbose: false + + - name: run release + run: | + git config --global user.name "${{ secrets.USER_NAME }}" + git config --global user.email "${{ secrets.USER_EMAIL }}" + + # Build the flag string based on the input + BATCH_FLAG="" + if [ "${{ inputs.is-batch-release }}" = "true" ]; then + BATCH_FLAG="--batch-release-branch=${INPUTS_BRANCH_NAME}" + fi + dart ./script/tool/lib/src/main.dart publish \ + --all-changed \ + $BATCH_FLAG \ + --base-sha=HEAD~ \ + --skip-confirmation + env: { PUB_CREDENTIALS: "${{ secrets.PUB_CREDENTIALS }}", INPUTS_BRANCH_NAME: "${{ inputs.branch-name }}" } diff --git a/.github/workflows/sync_release_pr.yml b/.github/workflows/sync_release_pr.yml new file mode 100644 index 000000000000..66233b6839d9 --- /dev/null +++ b/.github/workflows/sync_release_pr.yml @@ -0,0 +1,29 @@ +name: "Sync Release to Main" + +on: + push: + branches: + # As packages opt into batched releases, they need to be added here + - 'release-go_router' + +jobs: + create_sync_pr: + runs-on: ubuntu-latest + permissions: + # The create-pull-request action needs both content and pull-requests permissions. + contents: write + pull-requests: write + steps: + - name: Checkout repository + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd + + - name: Create Pull Request + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + gh pr create \ + --base "main" \ + --head "${{ github.ref_name }}" \ + --title "Sync ${{ github.ref_name }} to main" \ + --body "This automated PR syncs the changes from the release branch ${{ github.ref_name }} back to the main branch." \ + --label "post-${{ github.ref_name }}" diff --git a/AUTHORS b/AUTHORS index c5b332610c80..253669739d88 100644 --- a/AUTHORS +++ b/AUTHORS @@ -81,3 +81,8 @@ Hashir Shoaib Ricardo Dalarme Andrei Kabylin Ernesto Ramirez +Rui Craveiro +LeanCode +Piotr Denert +Marcin Chudy +Paweł Jakubowski diff --git a/CODEOWNERS b/CODEOWNERS index 31e44140f8e1..a49a588717fc 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -7,6 +7,7 @@ packages/animations/** @hannah-hyj packages/camera/** @bparrishMines packages/cross_file/** @stuartmorgan-g +packages/cupertino_ui/** @dkwingsmt packages/extension_google_sign_in_as_googleapis_auth/** @stuartmorgan-g packages/file_selector/** @stuartmorgan-g packages/flutter_lints/** @chunhtai @@ -22,6 +23,7 @@ packages/image_picker/** @tarrinneal packages/interactive_media_ads/** @bparrishMines packages/in_app_purchase/** @bparrishMines packages/local_auth/** @stuartmorgan-g +packages/material_ui/** @qunccccccc packages/metrics_center/** @bkonyi packages/multicast_dns/** @vashworth packages/path_provider/** @stuartmorgan-g @@ -42,7 +44,7 @@ packages/video_player/** @tarrinneal packages/web_benchmarks/** @yjbanov packages/webview_flutter/** @bparrishMines packages/xdg_directories/** @stuartmorgan-g -third_party/packages/cupertino_icons/** @MitchellGoodwin +third_party/packages/cupertino_icons/** @victorsanni third_party/packages/cupertino_icons/test/goldens/** @LongCatIsLooong third_party/packages/flutter_svg/** @domesticmouse third_party/packages/flutter_svg_test/** @domesticmouse @@ -76,31 +78,33 @@ packages/image_picker/image_picker_android/** @gmackall packages/in_app_purchase/in_app_purchase_android/** @gmackall packages/local_auth/local_auth_android/** @mboetger packages/path_provider/path_provider_android/** @camsim99 -packages/quick_actions/quick_actions_android/** @reidbaker +packages/quick_actions/quick_actions_android/** @jesswrd packages/shared_preferences/shared_preferences_android/** @jesswrd packages/url_launcher/url_launcher_android/** @gmackall -packages/video_player/video_player_android/** @reidbaker +packages/video_player/video_player_android/** @mboetger # Owned by ecosystem team for now during the wrapper evaluation. packages/webview_flutter/webview_flutter_android/** @bparrishMines # - Darwin -packages/camera/camera_avfoundation/** @hellohuanlin @vashworth -packages/file_selector/file_selector_ios/** @vashworth -packages/file_selector/file_selector_macos/** @vashworth -packages/google_maps_flutter/google_maps_flutter_ios/** @vashworth -packages/google_sign_in/google_sign_in_ios/** @LongCatIsLooong -packages/image_picker/image_picker_ios/** @vashworth @louisehsu -packages/image_picker/image_picker_macos/** @vashworth @louisehsu +packages/camera/camera_avfoundation/** @hellohuanlin @louisehsu +packages/file_selector/file_selector_ios/** @okorohelijah @vashworth +packages/file_selector/file_selector_macos/** @okorohelijah @vashworth +packages/google_maps_flutter/google_maps_flutter_ios/** @vashworth @LongCatIsLooong +packages/google_maps_flutter/google_maps_flutter_ios_sdk9/** @vashworth @LongCatIsLooong +packages/google_maps_flutter/google_maps_flutter_ios_sdk10/** @vashworth @LongCatIsLooong +packages/google_sign_in/google_sign_in_ios/** @LongCatIsLooong @okorohelijah +packages/image_picker/image_picker_ios/** @okorohelijah @vashworth +packages/image_picker/image_picker_macos/** @okorohelijah @vashworth packages/in_app_purchase/in_app_purchase_storekit/** @louisehsu @LongCatIsLooong -packages/local_auth/local_auth_darwin/** @vashworth @okorohelijah -packages/path_provider/path_provider_foundation/** @vashworth +packages/local_auth/local_auth_darwin/** @louisehsu @okorohelijah +packages/path_provider/path_provider_foundation/** @LongCatIsLooong @vashworth packages/pointer_interceptor/pointer_interceptor_ios/** @louisehsu @hellohuanlin -packages/quick_actions/quick_actions_ios/** @LongCatIsLooong @hellohuanlin +packages/quick_actions/quick_actions_ios/** @louisehsu @LongCatIsLooong packages/shared_preferences/shared_preferences_foundation/** @tarrinneal -packages/url_launcher/url_launcher_ios/** @hellohuanlin @LongCatIsLooong -packages/url_launcher/url_launcher_macos/** @hellohuanlin @LongCatIsLooong -packages/video_player/video_player_avfoundation/** @LongCatIsLooong @hellohuanlin -packages/webview_flutter/webview_flutter_wkwebview/** @louisehsu +packages/url_launcher/url_launcher_ios/** @vashworth @LongCatIsLooong +packages/url_launcher/url_launcher_macos/** @vashworth @LongCatIsLooong +packages/video_player/video_player_avfoundation/** @hellohuanlin @louisehsu +packages/webview_flutter/webview_flutter_wkwebview/** @LongCatIsLooong @hellohuanlin # - Linux packages/file_selector/file_selector_linux/** @robert-ancell @stuartmorgan-g diff --git a/README.md b/README.md index 412f66ad3d88..b499d7543344 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ These are the packages hosted in this repository: | [camera](./packages/camera/) | [![pub package](https://img.shields.io/pub/v/camera.svg)](https://pub.dev/packages/camera) | [![pub points](https://img.shields.io/pub/points/camera)](https://pub.dev/packages/camera/score) | [![downloads](https://img.shields.io/pub/dm/camera)](https://pub.dev/packages/camera/score) | [![GitHub issues by-label](https://img.shields.io/github/issues/flutter/flutter/p%3A%20camera?label=)](https://github.com/flutter/flutter/labels/p%3A%20camera) | [![GitHub pull requests by-label](https://img.shields.io/github/issues-pr/flutter/packages/p%3A%20camera?label=)](https://github.com/flutter/packages/labels/p%3A%20camera) | | [cross\_file](./packages/cross_file/) | [![pub package](https://img.shields.io/pub/v/cross_file.svg)](https://pub.dev/packages/cross_file) | [![pub points](https://img.shields.io/pub/points/cross_file)](https://pub.dev/packages/cross_file/score) | [![downloads](https://img.shields.io/pub/dm/cross_file)](https://pub.dev/packages/cross_file/score) | [![GitHub issues by-label](https://img.shields.io/github/issues/flutter/flutter/p%3A%20cross_file?label=)](https://github.com/flutter/flutter/labels/p%3A%20cross_file) | [![GitHub pull requests by-label](https://img.shields.io/github/issues-pr/flutter/packages/p%3A%20cross_file?label=)](https://github.com/flutter/packages/labels/p%3A%20cross_file) | | [cupertino\_icons](./third_party/packages/cupertino_icons/) | [![pub package](https://img.shields.io/pub/v/cupertino_icons.svg)](https://pub.dev/packages/cupertino_icons) | [![pub points](https://img.shields.io/pub/points/cupertino_icons)](https://pub.dev/packages/cupertino_icons/score) | [![downloads](https://img.shields.io/pub/dm/cupertino_icons)](https://pub.dev/packages/cupertino_icons/score) | [![GitHub issues by-label](https://img.shields.io/github/issues/flutter/flutter/p%3A%20cupertino_icons?label=)](https://github.com/flutter/flutter/labels/p%3A%20cupertino_icons) | [![GitHub pull requests by-label](https://img.shields.io/github/issues-pr/flutter/packages/p%3A%20cupertino_icons?label=)](https://github.com/flutter/packages/labels/p%3A%20cupertino_icons) | +| [cupertino\_ui](./packages/cupertino_ui/) | [![pub package](https://img.shields.io/pub/v/cupertino_ui.svg)](https://pub.dev/packages/cupertino_ui) | [![pub points](https://img.shields.io/pub/points/cupertino_ui)](https://pub.dev/packages/cupertino_ui/score) | [![downloads](https://img.shields.io/pub/dm/cupertino_ui)](https://pub.dev/packages/cupertino_ui/score) | [![GitHub issues by-label](https://img.shields.io/github/issues/flutter/flutter/p%3A%20cupertino_ui?label=)](https://github.com/flutter/flutter/labels/p%3A%20cupertino_ui) | [![GitHub pull requests by-label](https://img.shields.io/github/issues-pr/flutter/packages/p%3A%20cupertino_ui?label=)](https://github.com/flutter/packages/labels/p%3A%20cupertino_ui) | | [espresso](./packages/espresso/) | [![pub package](https://img.shields.io/pub/v/espresso.svg)](https://pub.dev/packages/espresso) | [![pub points](https://img.shields.io/pub/points/espresso)](https://pub.dev/packages/espresso/score) | [![downloads](https://img.shields.io/pub/dm/espresso)](https://pub.dev/packages/espresso/score) | [![GitHub issues by-label](https://img.shields.io/github/issues/flutter/flutter/p%3A%20espresso?label=)](https://github.com/flutter/flutter/labels/p%3A%20espresso) | [![GitHub pull requests by-label](https://img.shields.io/github/issues-pr/flutter/packages/p%3A%20espresso?label=)](https://github.com/flutter/packages/labels/p%3A%20espresso) | | [extension\_google\_sign\_in\_as\_googleapis\_auth](./packages/extension_google_sign_in_as_googleapis_auth/) | [![pub package](https://img.shields.io/pub/v/extension_google_sign_in_as_googleapis_auth.svg)](https://pub.dev/packages/extension_google_sign_in_as_googleapis_auth) | [![pub points](https://img.shields.io/pub/points/extension_google_sign_in_as_googleapis_auth)](https://pub.dev/packages/extension_google_sign_in_as_googleapis_auth/score) | [![downloads](https://img.shields.io/pub/dm/extension_google_sign_in_as_googleapis_auth)](https://pub.dev/packages/extension_google_sign_in_as_googleapis_auth/score) | [![GitHub issues by-label](https://img.shields.io/github/issues/flutter/flutter/p%3A%20extension_google_sign_in_as_googleapis_auth?label=)](https://github.com/flutter/flutter/labels/p%3A%20extension_google_sign_in_as_googleapis_auth) | [![GitHub pull requests by-label](https://img.shields.io/github/issues-pr/flutter/packages/p%3A%20extension_google_sign_in_as_googleapis_auth?label=)](https://github.com/flutter/packages/labels/p%3A%20extension_google_sign_in_as_googleapis_auth) | | [file\_selector](./packages/file_selector/) | [![pub package](https://img.shields.io/pub/v/file_selector.svg)](https://pub.dev/packages/file_selector) | [![pub points](https://img.shields.io/pub/points/file_selector)](https://pub.dev/packages/file_selector/score) | [![downloads](https://img.shields.io/pub/dm/file_selector)](https://pub.dev/packages/file_selector/score) | [![GitHub issues by-label](https://img.shields.io/github/issues/flutter/flutter/p%3A%20file_selector?label=)](https://github.com/flutter/flutter/labels/p%3A%20file_selector) | [![GitHub pull requests by-label](https://img.shields.io/github/issues-pr/flutter/packages/p%3A%20file_selector?label=)](https://github.com/flutter/packages/labels/p%3A%20file_selector) | @@ -58,6 +59,7 @@ These are the packages hosted in this repository: | [interactive\_media\_ads](./packages/interactive_media_ads/) | [![pub package](https://img.shields.io/pub/v/interactive_media_ads.svg)](https://pub.dev/packages/interactive_media_ads) | [![pub points](https://img.shields.io/pub/points/interactive_media_ads)](https://pub.dev/packages/interactive_media_ads/score) | [![downloads](https://img.shields.io/pub/dm/interactive_media_ads)](https://pub.dev/packages/interactive_media_ads/score) | [![GitHub issues by-label](https://img.shields.io/github/issues/flutter/flutter/p%3A%20interactive_media_ads?label=)](https://github.com/flutter/flutter/labels/p%3A%20interactive_media_ads) | [![GitHub pull requests by-label](https://img.shields.io/github/issues-pr/flutter/packages/p%3A%20interactive_media_ads?label=)](https://github.com/flutter/packages/labels/p%3A%20interactive_media_ads) | | [in\_app\_purchase](./packages/in_app_purchase/) | [![pub package](https://img.shields.io/pub/v/in_app_purchase.svg)](https://pub.dev/packages/in_app_purchase) | [![pub points](https://img.shields.io/pub/points/in_app_purchase)](https://pub.dev/packages/in_app_purchase/score) | [![downloads](https://img.shields.io/pub/dm/in_app_purchase)](https://pub.dev/packages/in_app_purchase/score) | [![GitHub issues by-label](https://img.shields.io/github/issues/flutter/flutter/p%3A%20in_app_purchase?label=)](https://github.com/flutter/flutter/labels/p%3A%20in_app_purchase) | [![GitHub pull requests by-label](https://img.shields.io/github/issues-pr/flutter/packages/p%3A%20in_app_purchase?label=)](https://github.com/flutter/packages/labels/p%3A%20in_app_purchase) | | [local\_auth](./packages/local_auth/) | [![pub package](https://img.shields.io/pub/v/local_auth.svg)](https://pub.dev/packages/local_auth) | [![pub points](https://img.shields.io/pub/points/local_auth)](https://pub.dev/packages/local_auth/score) | [![downloads](https://img.shields.io/pub/dm/local_auth)](https://pub.dev/packages/local_auth/score) | [![GitHub issues by-label](https://img.shields.io/github/issues/flutter/flutter/p%3A%20local_auth?label=)](https://github.com/flutter/flutter/labels/p%3A%20local_auth) | [![GitHub pull requests by-label](https://img.shields.io/github/issues-pr/flutter/packages/p%3A%20local_auth?label=)](https://github.com/flutter/packages/labels/p%3A%20local_auth) | +| [material\_ui](./packages/material_ui/) | [![pub package](https://img.shields.io/pub/v/material_ui.svg)](https://pub.dev/packages/material_ui) | [![pub points](https://img.shields.io/pub/points/material_ui)](https://pub.dev/packages/material_ui/score) | [![downloads](https://img.shields.io/pub/dm/material_ui)](https://pub.dev/packages/material_ui/score) | [![GitHub issues by-label](https://img.shields.io/github/issues/flutter/flutter/p%3A%20material_ui?label=)](https://github.com/flutter/flutter/labels/p%3A%20material_ui) | [![GitHub pull requests by-label](https://img.shields.io/github/issues-pr/flutter/packages/p%3A%20material_ui?label=)](https://github.com/flutter/packages/labels/p%3A%20material_ui) | | [metrics\_center](./packages/metrics_center/) | [![pub package](https://img.shields.io/pub/v/metrics_center.svg)](https://pub.dev/packages/metrics_center) | [![pub points](https://img.shields.io/pub/points/metrics_center)](https://pub.dev/packages/metrics_center/score) | [![downloads](https://img.shields.io/pub/dm/metrics_center)](https://pub.dev/packages/metrics_center/score) | [![GitHub issues by-label](https://img.shields.io/github/issues/flutter/flutter/p%3A%20metrics_center?label=)](https://github.com/flutter/flutter/labels/p%3A%20metrics_center) | [![GitHub pull requests by-label](https://img.shields.io/github/issues-pr/flutter/packages/p%3A%20metrics_center?label=)](https://github.com/flutter/packages/labels/p%3A%20metrics_center) | | [multicast\_dns](./packages/multicast_dns/) | [![pub package](https://img.shields.io/pub/v/multicast_dns.svg)](https://pub.dev/packages/multicast_dns) | [![pub points](https://img.shields.io/pub/points/multicast_dns)](https://pub.dev/packages/multicast_dns/score) | [![downloads](https://img.shields.io/pub/dm/multicast_dns)](https://pub.dev/packages/multicast_dns/score) | [![GitHub issues by-label](https://img.shields.io/github/issues/flutter/flutter/p%3A%20multicast_dns?label=)](https://github.com/flutter/flutter/labels/p%3A%20multicast_dns) | [![GitHub pull requests by-label](https://img.shields.io/github/issues-pr/flutter/packages/p%3A%20multicast_dns?label=)](https://github.com/flutter/packages/labels/p%3A%20multicast_dns) | | [path\_parsing](./third_party/packages/path_parsing/) | [![pub package](https://img.shields.io/pub/v/path_parsing.svg)](https://pub.dev/packages/path_parsing) | [![pub points](https://img.shields.io/pub/points/path_parsing)](https://pub.dev/packages/path_parsing/score) | [![downloads](https://img.shields.io/pub/dm/path_parsing)](https://pub.dev/packages/path_parsing/score) | [![GitHub issues by-label](https://img.shields.io/github/issues/flutter/flutter/p%3A%20path_parsing?label=)](https://github.com/flutter/flutter/labels/p%3A%20path_parsing) | [![GitHub pull requests by-label](https://img.shields.io/github/issues-pr/flutter/packages/p%3A%20path_parsing?label=)](https://github.com/flutter/packages/labels/p%3A%20path_parsing) | diff --git a/analysis_options.yaml b/analysis_options.yaml index a5de895abc41..5a160d9d8582 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -29,7 +29,7 @@ linter: - always_declare_return_types - always_put_control_body_on_new_line # - always_put_required_named_parameters_first # we prefer having parameters in the same order as fields https://github.com/flutter/flutter/issues/10219 - - always_specify_types + # - always_specify_types # conflicts with omit_obvious_local_variable_types # - always_use_package_imports # we do this commonly - annotate_overrides # - avoid_annotating_with_dynamic # conflicts with always_specify_types @@ -114,7 +114,7 @@ linter: # - matching_super_parameters # blocked on https://github.com/dart-lang/language/issues/2509 - missing_code_block_language_in_doc_comment - missing_whitespace_between_adjacent_strings - - no_adjacent_strings_in_list + # - no_adjacent_strings_in_list # conflicts with prefer_adjacent_string_concatenation - no_default_cases - no_duplicate_case_values - no_leading_underscores_for_library_prefixes @@ -128,7 +128,8 @@ linter: - noop_primitive_operations - null_check_on_nullable_type_parameter - null_closures - # - omit_local_variable_types # opposite of always_specify_types + # - omit_local_variable_types # conflicts with specify_nonobvious_local_variable_types + - omit_obvious_local_variable_types # - one_member_abstracts # too many false positives - only_throw_errors # this does get disabled in a few places where we have legacy code that uses strings et al - overridden_fields @@ -187,12 +188,15 @@ linter: - sort_constructors_first - sort_pub_dependencies # DIFFERENT FROM FLUTTER/FLUTTER: Flutter's use case for not sorting does not apply to this repository. - sort_unnamed_constructors_first + - specify_nonobvious_local_variable_types + - specify_nonobvious_property_types - test_types_in_equals - throw_in_finally - tighten_type_of_initializing_formals - # - type_annotate_public_apis # subset of always_specify_types + - type_annotate_public_apis - type_init_formals - type_literal_in_constant_pattern + - unintended_html_in_doc_comment # DIFFERENT FROM FLUTTER/FLUTTER: Disabled due to an issue that has been fixed, so just hasn't been adopted there yet. - unawaited_futures # DIFFERENT FROM FLUTTER/FLUTTER: It's disabled there for "too many false positives"; that's not an issue here, and missing awaits have caused production issues in plugins. - unnecessary_await_in_return - unnecessary_brace_in_string_interps diff --git a/packages/animations/CHANGELOG.md b/packages/animations/CHANGELOG.md index 4cb0aed121b4..6d7110f9b8ec 100644 --- a/packages/animations/CHANGELOG.md +++ b/packages/animations/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. + ## 2.1.1 * Updated the documentation for `OpenContainer.onClosed` to clarify that it is called at the start of the closing transition, not at the end. diff --git a/packages/animations/example/.metadata b/packages/animations/example/.metadata index 706ff779c7b7..9fb00192b70a 100644 --- a/packages/animations/example/.metadata +++ b/packages/animations/example/.metadata @@ -4,7 +4,7 @@ # This file should be version controlled and should not be manually edited. version: - revision: "603104015dd692ea3403755b55d07813d5cf8965" + revision: "582a0e7c5581dc0ca5f7bfd8662bb8db6f59d536" channel: "stable" project_type: app @@ -13,11 +13,11 @@ project_type: app migration: platforms: - platform: root - create_revision: 603104015dd692ea3403755b55d07813d5cf8965 - base_revision: 603104015dd692ea3403755b55d07813d5cf8965 + create_revision: 582a0e7c5581dc0ca5f7bfd8662bb8db6f59d536 + base_revision: 582a0e7c5581dc0ca5f7bfd8662bb8db6f59d536 - platform: android - create_revision: 603104015dd692ea3403755b55d07813d5cf8965 - base_revision: 603104015dd692ea3403755b55d07813d5cf8965 + create_revision: 582a0e7c5581dc0ca5f7bfd8662bb8db6f59d536 + base_revision: 582a0e7c5581dc0ca5f7bfd8662bb8db6f59d536 # User provided section diff --git a/packages/animations/example/android/.gitignore b/packages/animations/example/android/.gitignore index 55afd919c659..be3943c96d8e 100644 --- a/packages/animations/example/android/.gitignore +++ b/packages/animations/example/android/.gitignore @@ -5,6 +5,7 @@ gradle-wrapper.jar /gradlew.bat /local.properties GeneratedPluginRegistrant.java +.cxx/ # Remember to never publicly share your keystore. # See https://flutter.dev/to/reference-keystore diff --git a/packages/animations/example/android/app/build.gradle b/packages/animations/example/android/app/build.gradle deleted file mode 100644 index e9083f04998b..000000000000 --- a/packages/animations/example/android/app/build.gradle +++ /dev/null @@ -1,43 +0,0 @@ -plugins { - id "com.android.application" - id "kotlin-android" - // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. - id "dev.flutter.flutter-gradle-plugin" -} - -android { - namespace = "dev.flutter.packages.animations.example" - compileSdk = flutter.compileSdkVersion - ndkVersion = flutter.ndkVersion - - compileOptions { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 - } - - kotlinOptions { - jvmTarget = JavaVersion.VERSION_17.toString() - } - - sourceSets { - main.java.srcDirs += 'src/main/kotlin' - } - - defaultConfig { - applicationId = "dev.flutter.packages.animations.example" - minSdk = flutter.minSdkVersion - targetSdk = flutter.targetSdkVersion - versionCode = flutter.versionCode - versionName = flutter.versionName - } - - buildTypes { - release { - signingConfig = signingConfigs.debug - } - } -} - -flutter { - source = "../.." -} diff --git a/packages/animations/example/android/app/build.gradle.kts b/packages/animations/example/android/app/build.gradle.kts new file mode 100644 index 000000000000..ffa850c091c9 --- /dev/null +++ b/packages/animations/example/android/app/build.gradle.kts @@ -0,0 +1,39 @@ +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "dev.flutter.packages.animations.animations_example" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_17.toString() + } + + defaultConfig { + applicationId = "dev.flutter.packages.animations.animations_example" + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + signingConfig = signingConfigs.getByName("debug") + } + } +} + +flutter { + source = "../.." +} diff --git a/packages/animations/example/android/app/src/main/AndroidManifest.xml b/packages/animations/example/android/app/src/main/AndroidManifest.xml index 74a78b939e5e..c1af4eb74521 100644 --- a/packages/animations/example/android/app/src/main/AndroidManifest.xml +++ b/packages/animations/example/android/app/src/main/AndroidManifest.xml @@ -1,6 +1,6 @@ ("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/packages/animations/example/android/gradle.properties b/packages/animations/example/android/gradle.properties index 9b650e9517e0..fbee1d8cdafc 100644 --- a/packages/animations/example/android/gradle.properties +++ b/packages/animations/example/android/gradle.properties @@ -1,2 +1,2 @@ -org.gradle.jvmargs=-Xmx4G -XX:MaxMetaspaceSize=2G -XX:+HeapDumpOnOutOfMemoryError +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError android.useAndroidX=true diff --git a/packages/animations/example/android/gradle/wrapper/gradle-wrapper.properties b/packages/animations/example/android/gradle/wrapper/gradle-wrapper.properties index 6064aebd5424..e4ef43fb98df 100644 --- a/packages/animations/example/android/gradle/wrapper/gradle-wrapper.properties +++ b/packages/animations/example/android/gradle/wrapper/gradle-wrapper.properties @@ -2,5 +2,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-all.zip - +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip diff --git a/packages/animations/example/android/settings.gradle b/packages/animations/example/android/settings.gradle deleted file mode 100644 index 852d4892b9b6..000000000000 --- a/packages/animations/example/android/settings.gradle +++ /dev/null @@ -1,28 +0,0 @@ -pluginManagement { - def flutterSdkPath = { - def properties = new Properties() - file("local.properties").withInputStream { properties.load(it) } - def flutterSdkPath = properties.getProperty("flutter.sdk") - assert flutterSdkPath != null, "flutter.sdk not set in local.properties" - return flutterSdkPath - }() - - includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") - - repositories { - google() - mavenCentral() - gradlePluginPortal() - } -} - - -// 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.11.0" apply false - id "org.jetbrains.kotlin.android" version "2.2.0" apply false - id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1" -} - -include ":app" diff --git a/packages/animations/example/android/settings.gradle.kts b/packages/animations/example/android/settings.gradle.kts new file mode 100644 index 000000000000..a0118892641d --- /dev/null +++ b/packages/animations/example/android/settings.gradle.kts @@ -0,0 +1,28 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +// 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.11.1" apply false + id("org.jetbrains.kotlin.android") version "2.2.20" apply false + id("com.google.cloud.artifactregistry.gradle-plugin") version "2.2.1" +} + +include(":app") diff --git a/packages/animations/example/ios/Flutter/AppFrameworkInfo.plist b/packages/animations/example/ios/Flutter/AppFrameworkInfo.plist index 8c6e56146e23..ab8e063fe872 100644 --- a/packages/animations/example/ios/Flutter/AppFrameworkInfo.plist +++ b/packages/animations/example/ios/Flutter/AppFrameworkInfo.plist @@ -20,7 +20,5 @@ ???? CFBundleVersion 1.0 - MinimumOSVersion - 12.0 diff --git a/packages/animations/example/ios/Runner.xcodeproj/project.pbxproj b/packages/animations/example/ios/Runner.xcodeproj/project.pbxproj index ac54eb948cd3..647afcdca262 100644 --- a/packages/animations/example/ios/Runner.xcodeproj/project.pbxproj +++ b/packages/animations/example/ios/Runner.xcodeproj/project.pbxproj @@ -135,7 +135,7 @@ 97C146E61CF9000F007C117D /* Project object */ = { isa = PBXProject; attributes = { - LastUpgradeCheck = 1430; + LastUpgradeCheck = 1510; ORGANIZATIONNAME = "The Flutter Authors"; TargetAttributes = { 97C146ED1CF9000F007C117D = { @@ -283,7 +283,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -366,7 +366,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -415,7 +415,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; diff --git a/packages/animations/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/packages/animations/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index b52b2e698b7e..4f746537f280 100644 --- a/packages/animations/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/packages/animations/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -1,6 +1,6 @@ diff --git a/packages/animations/example/lib/container_transition.dart b/packages/animations/example/lib/container_transition.dart index 4f188eae2b23..26e91cccdc58 100644 --- a/packages/animations/example/lib/container_transition.dart +++ b/packages/animations/example/lib/container_transition.dart @@ -384,7 +384,7 @@ class _ExampleSingleTile extends StatelessWidget { @override Widget build(BuildContext context) { - const double height = 100.0; + const height = 100.0; return _InkWellOverlay( openContainer: openContainer, diff --git a/packages/animations/example/lib/shared_axis_transition.dart b/packages/animations/example/lib/shared_axis_transition.dart index 299f32cbaba2..4806644caf29 100644 --- a/packages/animations/example/lib/shared_axis_transition.dart +++ b/packages/animations/example/lib/shared_axis_transition.dart @@ -152,7 +152,7 @@ class _CourseSwitchState extends State<_CourseSwitch> { @override Widget build(BuildContext context) { - final String subtitle = _value ? 'Bundled' : 'Shown Individually'; + final subtitle = _value ? 'Bundled' : 'Shown Individually'; return SwitchListTile( title: Text(widget.course), subtitle: Text(subtitle), diff --git a/packages/animations/example/pubspec.yaml b/packages/animations/example/pubspec.yaml index f0511e4d6b8a..3a5b1b207c9b 100644 --- a/packages/animations/example/pubspec.yaml +++ b/packages/animations/example/pubspec.yaml @@ -6,8 +6,8 @@ publish_to: none version: 0.0.1 environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" dependencies: animations: diff --git a/packages/animations/lib/src/open_container.dart b/packages/animations/lib/src/open_container.dart index 56b3446e230c..10dd2b2f5e70 100644 --- a/packages/animations/lib/src/open_container.dart +++ b/packages/animations/lib/src/open_container.dart @@ -643,7 +643,7 @@ class _OpenContainerRoute extends ModalRoute { required BuildContext navigatorContext, bool delayForSourceRoute = false, }) { - final RenderBox navigator = + final navigator = Navigator.of( navigatorContext, rootNavigator: useRootNavigator, @@ -679,8 +679,7 @@ class _OpenContainerRoute extends ModalRoute { Rect _getRect(GlobalKey key, RenderBox ancestor) { assert(key.currentContext != null); assert(ancestor.hasSize); - final RenderBox render = - key.currentContext!.findRenderObject()! as RenderBox; + final render = key.currentContext!.findRenderObject()! as RenderBox; assert(render.hasSize); return MatrixUtils.transformRect( render.getTransformTo(ancestor), @@ -689,8 +688,8 @@ class _OpenContainerRoute extends ModalRoute { } bool get _transitionWasInterrupted { - bool wasInProgress = false; - bool isInProgress = false; + var wasInProgress = false; + var isInProgress = false; switch (_currentAnimationStatus) { case AnimationStatus.completed: @@ -884,8 +883,8 @@ class _FlippableTweenSequence extends TweenSequence { _FlippableTweenSequence? get flipped { if (_flipped == null) { - final List> newItems = >[]; - for (int i = 0; i < _items.length; i++) { + final newItems = >[]; + for (var i = 0; i < _items.length; i++) { newItems.add( TweenSequenceItem( tween: _items[i].tween, diff --git a/packages/animations/lib/src/page_transition_switcher.dart b/packages/animations/lib/src/page_transition_switcher.dart index 1b2e7365d9fa..53d4f7479a0e 100644 --- a/packages/animations/lib/src/page_transition_switcher.dart +++ b/packages/animations/lib/src/page_transition_switcher.dart @@ -293,8 +293,8 @@ class _PageTransitionSwitcherState extends State _activeEntries.forEach(_updateTransitionForEntry); } - final bool hasNewChild = widget.child != null; - final bool hasOldChild = _currentEntry != null; + final hasNewChild = widget.child != null; + final hasOldChild = _currentEntry != null; if (hasNewChild != hasOldChild || hasNewChild && !Widget.canUpdate(widget.child!, _currentEntry!.widgetChild)) { @@ -327,11 +327,11 @@ class _PageTransitionSwitcherState extends State if (widget.child == null) { return; } - final AnimationController primaryController = AnimationController( + final primaryController = AnimationController( duration: widget.duration, vsync: this, ); - final AnimationController secondaryController = AnimationController( + final secondaryController = AnimationController( duration: widget.duration, vsync: this, ); @@ -373,7 +373,7 @@ class _PageTransitionSwitcherState extends State primaryController, secondaryController, ); - final _ChildEntry entry = _ChildEntry( + final entry = _ChildEntry( widgetChild: child, transition: KeyedSubtree.wrap(transition, _childNumber), primaryController: primaryController, diff --git a/packages/animations/pubspec.yaml b/packages/animations/pubspec.yaml index 40509a2d7247..012218b3db2b 100644 --- a/packages/animations/pubspec.yaml +++ b/packages/animations/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.1.1 environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" dependencies: flutter: diff --git a/packages/animations/test/dual_transition_builder_test.dart b/packages/animations/test/dual_transition_builder_test.dart index c8fd4cea946a..7c7e25fc8b0e 100644 --- a/packages/animations/test/dual_transition_builder_test.dart +++ b/packages/animations/test/dual_transition_builder_test.dart @@ -7,7 +7,7 @@ import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('runs animations', (WidgetTester tester) async { - final AnimationController controller = AnimationController( + final controller = AnimationController( vsync: const TestVSync(), duration: const Duration(milliseconds: 300), ); @@ -75,7 +75,7 @@ void main() { }); testWidgets('keeps state', (WidgetTester tester) async { - final AnimationController controller = AnimationController( + final controller = AnimationController( vsync: const TestVSync(), duration: const Duration(milliseconds: 300), ); @@ -146,7 +146,7 @@ void main() { testWidgets('does not jump when interrupted - forward', ( WidgetTester tester, ) async { - final AnimationController controller = AnimationController( + final controller = AnimationController( vsync: const TestVSync(), duration: const Duration(milliseconds: 300), ); @@ -212,7 +212,7 @@ void main() { testWidgets('does not jump when interrupted - reverse', ( WidgetTester tester, ) async { - final AnimationController controller = AnimationController( + final controller = AnimationController( value: 1.0, vsync: const TestVSync(), duration: const Duration(milliseconds: 300), diff --git a/packages/animations/test/fade_scale_transition_test.dart b/packages/animations/test/fade_scale_transition_test.dart index b8a30e3f96c4..f5631c7695c0 100644 --- a/packages/animations/test/fade_scale_transition_test.dart +++ b/packages/animations/test/fade_scale_transition_test.dart @@ -361,7 +361,7 @@ void main() { }); testWidgets('should preserve state', (WidgetTester tester) async { - final AnimationController controller = AnimationController( + final controller = AnimationController( vsync: const TestVSync(), duration: const Duration(milliseconds: 300), ); @@ -416,7 +416,7 @@ double _getOpacity(GlobalKey key, WidgetTester tester) { matching: find.byType(FadeTransition), ); return tester.widgetList(finder).fold(1.0, (double a, Widget widget) { - final FadeTransition transition = widget as FadeTransition; + final transition = widget as FadeTransition; return a * transition.opacity.value; }); } @@ -427,7 +427,7 @@ double _getScale(GlobalKey key, WidgetTester tester) { matching: find.byType(ScaleTransition), ); return tester.widgetList(finder).fold(1.0, (double a, Widget widget) { - final ScaleTransition transition = widget as ScaleTransition; + final transition = widget as ScaleTransition; return a * transition.scale.value; }); } diff --git a/packages/animations/test/fade_through_transition_test.dart b/packages/animations/test/fade_through_transition_test.dart index 82d26b6e5520..10973d06e2eb 100644 --- a/packages/animations/test/fade_through_transition_test.dart +++ b/packages/animations/test/fade_through_transition_test.dart @@ -10,12 +10,8 @@ void main() { testWidgets( 'FadeThroughPageTransitionsBuilder builds a FadeThroughTransition', (WidgetTester tester) async { - final AnimationController animation = AnimationController( - vsync: const TestVSync(), - ); - final AnimationController secondaryAnimation = AnimationController( - vsync: const TestVSync(), - ); + final animation = AnimationController(vsync: const TestVSync()); + final secondaryAnimation = AnimationController(vsync: const TestVSync()); await tester.pumpWidget( const FadeThroughPageTransitionsBuilder().buildTransitions( @@ -34,9 +30,9 @@ void main() { testWidgets('FadeThroughTransition runs forward', ( WidgetTester tester, ) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; await tester.pumpWidget(_TestWidget(navigatorKey: navigator)); expect(find.text(bottomRoute), findsOneWidget); @@ -116,9 +112,9 @@ void main() { testWidgets('FadeThroughTransition runs backwards', ( WidgetTester tester, ) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; await tester.pumpWidget(_TestWidget(navigatorKey: navigator)); navigator.currentState!.pushNamed('/a'); @@ -206,9 +202,9 @@ void main() { testWidgets('FadeThroughTransition does not jump when interrupted', ( WidgetTester tester, ) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; await tester.pumpWidget(_TestWidget(navigatorKey: navigator)); expect(find.text(bottomRoute), findsOneWidget); @@ -271,9 +267,9 @@ void main() { testWidgets('State is not lost when transitioning', ( WidgetTester tester, ) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; await tester.pumpWidget( _TestWidget( @@ -358,11 +354,11 @@ void main() { }); testWidgets('should keep state', (WidgetTester tester) async { - final AnimationController animation = AnimationController( + final animation = AnimationController( vsync: const TestVSync(), duration: const Duration(milliseconds: 300), ); - final AnimationController secondaryAnimation = AnimationController( + final secondaryAnimation = AnimationController( vsync: const TestVSync(), duration: const Duration(milliseconds: 300), ); @@ -431,7 +427,7 @@ double _getOpacity(String key, WidgetTester tester) { matching: find.byType(FadeTransition), ); return tester.widgetList(finder).fold(1.0, (double a, Widget widget) { - final FadeTransition transition = widget as FadeTransition; + final transition = widget as FadeTransition; return a * transition.opacity.value; }); } @@ -442,7 +438,7 @@ double _getScale(String key, WidgetTester tester) { matching: find.byType(ScaleTransition), ); return tester.widgetList(finder).fold(1.0, (double a, Widget widget) { - final ScaleTransition transition = widget as ScaleTransition; + final transition = widget as ScaleTransition; return a * transition.scale.value; }); } diff --git a/packages/animations/test/modal_test.dart b/packages/animations/test/modal_test.dart index 2f3bbe901820..eb2963176e87 100644 --- a/packages/animations/test/modal_test.dart +++ b/packages/animations/test/modal_test.dart @@ -430,7 +430,7 @@ void main() { testWidgets('showModal builds a new route with specified route settings', ( WidgetTester tester, ) async { - const RouteSettings routeSettings = RouteSettings( + const routeSettings = RouteSettings( name: 'route-name', arguments: 'arguments', ); @@ -473,7 +473,7 @@ void main() { testWidgets('showModal builds a new route with specified image filter', ( WidgetTester tester, ) async { - final ui.ImageFilter filter = ui.ImageFilter.blur(sigmaX: 1, sigmaY: 1); + final filter = ui.ImageFilter.blur(sigmaX: 1, sigmaY: 1); final Widget button = Builder( builder: (BuildContext context) { @@ -518,7 +518,7 @@ double _getOpacity(GlobalKey key, WidgetTester tester) { matching: find.byType(FadeTransition), ); return tester.widgetList(finder).fold(1.0, (double a, Widget widget) { - final FadeTransition transition = widget as FadeTransition; + final transition = widget as FadeTransition; return a * transition.opacity.value; }); } @@ -529,7 +529,7 @@ double _getScale(GlobalKey key, WidgetTester tester) { matching: find.byType(ScaleTransition), ); return tester.widgetList(finder).fold(1.0, (double a, Widget widget) { - final ScaleTransition transition = widget as ScaleTransition; + final transition = widget as ScaleTransition; return a * transition.scale.value; }); } diff --git a/packages/animations/test/open_container_test.dart b/packages/animations/test/open_container_test.dart index 916f5ed3f123..673547039992 100644 --- a/packages/animations/test/open_container_test.dart +++ b/packages/animations/test/open_container_test.dart @@ -8,8 +8,7 @@ import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Can be opened via GlobalKey', (WidgetTester tester) async { - final GlobalKey openContainerKey = - GlobalKey(); + final openContainerKey = GlobalKey(); await tester.pumpWidget( _boilerplate( @@ -43,8 +42,8 @@ void main() { const ShapeBorder shape = RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(8.0)), ); - bool closedBuilderCalled = false; - bool openBuilderCalled = false; + var closedBuilderCalled = false; + var openBuilderCalled = false; await tester.pumpWidget( _boilerplate( @@ -72,7 +71,7 @@ void main() { final Element srcMaterialElement = tester.firstElement( find.ancestor(of: find.text('Closed'), matching: find.byType(Material)), ); - final Material srcMaterial = srcMaterialElement.widget as Material; + final srcMaterial = srcMaterialElement.widget as Material; expect(srcMaterial.color, Colors.green); expect(srcMaterial.elevation, 4.0); expect(srcMaterial.shape, shape); @@ -94,7 +93,7 @@ void main() { final Element destMaterialElement = tester.firstElement( find.ancestor(of: find.text('Closed'), matching: find.byType(Material)), ); - final Material closedMaterial = destMaterialElement.widget as Material; + final closedMaterial = destMaterialElement.widget as Material; expect(closedMaterial.color, Colors.green); expect(closedMaterial.elevation, 4.0); expect(closedMaterial.shape, shape); @@ -107,14 +106,11 @@ void main() { expect(_getOpacity(tester, 'Open'), 0.0); expect(_getOpacity(tester, 'Closed'), 1.0); - final _TrackedData dataClosed = _TrackedData( - closedMaterial, - closedMaterialRect, - ); + final dataClosed = _TrackedData(closedMaterial, closedMaterialRect); // Jump to the start of the fade in. await tester.pump(const Duration(milliseconds: 60)); // 300ms * 1/5 = 60ms - final _TrackedData dataPreFade = _TrackedData( + final dataPreFade = _TrackedData( destMaterialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == destMaterialElement), @@ -130,7 +126,7 @@ void main() { // Jump to the middle of the fade in. await tester.pump(const Duration(milliseconds: 30)); // 300ms * 3/10 = 90ms - final _TrackedData dataMidFadeIn = _TrackedData( + final dataMidFadeIn = _TrackedData( destMaterialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == destMaterialElement), @@ -149,7 +145,7 @@ void main() { // Jump to the end of the fade in at 2/5 of 300ms. await tester.pump(const Duration(milliseconds: 30)); // 300ms * 2/5 = 120ms - final _TrackedData dataPostFadeIn = _TrackedData( + final dataPostFadeIn = _TrackedData( destMaterialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == destMaterialElement), @@ -165,7 +161,7 @@ void main() { // Jump almost to the end of the transition. await tester.pump(const Duration(milliseconds: 180)); - final _TrackedData dataTransitionDone = _TrackedData( + final dataTransitionDone = _TrackedData( destMaterialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == destMaterialElement), @@ -188,7 +184,7 @@ void main() { final Element finalMaterialElement = tester.firstElement( find.ancestor(of: find.text('Open'), matching: find.byType(Material)), ); - final _TrackedData dataOpen = _TrackedData( + final dataOpen = _TrackedData( finalMaterialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == finalMaterialElement), @@ -236,7 +232,7 @@ void main() { final Element initialMaterialElement = tester.firstElement( find.ancestor(of: find.text('Open'), matching: find.byType(Material)), ); - final _TrackedData dataOpen = _TrackedData( + final dataOpen = _TrackedData( initialMaterialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == initialMaterialElement), @@ -257,7 +253,7 @@ void main() { final Element materialElement = tester.firstElement( find.ancestor(of: find.text('Open'), matching: find.byType(Material)), ); - final _TrackedData dataTransitionStart = _TrackedData( + final dataTransitionStart = _TrackedData( materialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == materialElement), @@ -271,7 +267,7 @@ void main() { // Jump to start of fade out: 1/5 of 300. await tester.pump(const Duration(milliseconds: 60)); // 300 * 1/5 = 60 - final _TrackedData dataPreFadeOut = _TrackedData( + final dataPreFadeOut = _TrackedData( materialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == materialElement), @@ -287,7 +283,7 @@ void main() { // Jump to the middle of the fade out. await tester.pump(const Duration(milliseconds: 30)); // 300 * 3/10 = 90 - final _TrackedData dataMidpoint = _TrackedData( + final dataMidpoint = _TrackedData( materialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == materialElement), @@ -305,7 +301,7 @@ void main() { // Jump to the end of the fade out. await tester.pump(const Duration(milliseconds: 30)); // 300 * 2/5 = 120 - final _TrackedData dataPostFadeOut = _TrackedData( + final dataPostFadeOut = _TrackedData( materialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == materialElement), @@ -321,7 +317,7 @@ void main() { // Jump almost to the end of the transition. await tester.pump(const Duration(milliseconds: 180)); - final _TrackedData dataTransitionDone = _TrackedData( + final dataTransitionDone = _TrackedData( materialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == materialElement), @@ -344,7 +340,7 @@ void main() { final Element finalMaterialElement = tester.firstElement( find.ancestor(of: find.text('Closed'), matching: find.byType(Material)), ); - final _TrackedData dataClosed = _TrackedData( + final dataClosed = _TrackedData( finalMaterialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == finalMaterialElement), @@ -363,8 +359,8 @@ void main() { const ShapeBorder shape = RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(8.0)), ); - bool closedBuilderCalled = false; - bool openBuilderCalled = false; + var closedBuilderCalled = false; + var openBuilderCalled = false; await tester.pumpWidget( _boilerplate( @@ -394,7 +390,7 @@ void main() { final Element srcMaterialElement = tester.firstElement( find.ancestor(of: find.text('Closed'), matching: find.byType(Material)), ); - final Material srcMaterial = srcMaterialElement.widget as Material; + final srcMaterial = srcMaterialElement.widget as Material; expect(srcMaterial.color, Colors.green); expect(srcMaterial.elevation, 4.0); expect(srcMaterial.shape, shape); @@ -416,7 +412,7 @@ void main() { final Element destMaterialElement = tester.firstElement( find.ancestor(of: find.text('Closed'), matching: find.byType(Material)), ); - final Material closedMaterial = destMaterialElement.widget as Material; + final closedMaterial = destMaterialElement.widget as Material; expect(closedMaterial.color, Colors.green); expect(closedMaterial.elevation, 4.0); expect(closedMaterial.shape, shape); @@ -429,14 +425,11 @@ void main() { expect(_getOpacity(tester, 'Open'), 0.0); expect(_getOpacity(tester, 'Closed'), 1.0); - final _TrackedData dataClosed = _TrackedData( - closedMaterial, - closedMaterialRect, - ); + final dataClosed = _TrackedData(closedMaterial, closedMaterialRect); // The fade-out takes 1/5 of 300ms. Let's jump to the midpoint of that. await tester.pump(const Duration(milliseconds: 30)); // 300ms * 1/10 = 30ms - final _TrackedData dataMidFadeOut = _TrackedData( + final dataMidFadeOut = _TrackedData( destMaterialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == destMaterialElement), @@ -454,7 +447,7 @@ void main() { // Let's jump to the crossover point at 1/5 of 300ms. await tester.pump(const Duration(milliseconds: 30)); // 300ms * 1/5 = 60ms - final _TrackedData dataMidpoint = _TrackedData( + final dataMidpoint = _TrackedData( destMaterialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == destMaterialElement), @@ -471,7 +464,7 @@ void main() { // Let's jump to the middle of the fade-in at 3/5 of 300ms await tester.pump(const Duration(milliseconds: 120)); // 300ms * 3/5 = 180ms - final _TrackedData dataMidFadeIn = _TrackedData( + final dataMidFadeIn = _TrackedData( destMaterialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == destMaterialElement), @@ -489,7 +482,7 @@ void main() { // Let's jump almost to the end of the transition. await tester.pump(const Duration(milliseconds: 120)); - final _TrackedData dataTransitionDone = _TrackedData( + final dataTransitionDone = _TrackedData( destMaterialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == destMaterialElement), @@ -517,7 +510,7 @@ void main() { final Element finalMaterialElement = tester.firstElement( find.ancestor(of: find.text('Open'), matching: find.byType(Material)), ); - final _TrackedData dataOpen = _TrackedData( + final dataOpen = _TrackedData( finalMaterialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == finalMaterialElement), @@ -565,7 +558,7 @@ void main() { final Element initialMaterialElement = tester.firstElement( find.ancestor(of: find.text('Open'), matching: find.byType(Material)), ); - final _TrackedData dataOpen = _TrackedData( + final dataOpen = _TrackedData( initialMaterialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == initialMaterialElement), @@ -587,7 +580,7 @@ void main() { final Element materialElement = tester.firstElement( find.ancestor(of: find.text('Open'), matching: find.byType(Material)), ); - final _TrackedData dataTransitionStart = _TrackedData( + final dataTransitionStart = _TrackedData( materialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == materialElement), @@ -602,7 +595,7 @@ void main() { // Jump to mid-point of fade-out: 1/10 of 300ms. await tester.pump(const Duration(milliseconds: 30)); // 300ms * 1/10 = 30ms - final _TrackedData dataMidFadeOut = _TrackedData( + final dataMidFadeOut = _TrackedData( materialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == materialElement), @@ -623,7 +616,7 @@ void main() { // Let's jump to the crossover point at 1/5 of 300ms. await tester.pump(const Duration(milliseconds: 30)); // 300ms * 1/5 = 60ms - final _TrackedData dataMidpoint = _TrackedData( + final dataMidpoint = _TrackedData( materialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == materialElement), @@ -640,7 +633,7 @@ void main() { // Let's jump to the middle of the fade-in at 3/5 of 300ms await tester.pump(const Duration(milliseconds: 120)); // 300ms * 3/5 = 180ms - final _TrackedData dataMidFadeIn = _TrackedData( + final dataMidFadeIn = _TrackedData( materialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == materialElement), @@ -658,7 +651,7 @@ void main() { // Let's jump almost to the end of the transition. await tester.pump(const Duration(milliseconds: 120)); - final _TrackedData dataTransitionDone = _TrackedData( + final dataTransitionDone = _TrackedData( materialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == materialElement), @@ -685,7 +678,7 @@ void main() { final Element finalMaterialElement = tester.firstElement( find.ancestor(of: find.text('Closed'), matching: find.byType(Material)), ); - final _TrackedData dataClosed = _TrackedData( + final dataClosed = _TrackedData( finalMaterialElement.widget as Material, tester.getRect( find.byElementPredicate((Element e) => e == finalMaterialElement), @@ -1040,7 +1033,7 @@ void main() { ), ), ); - const Rect fullNavigator = Rect.fromLTWH(250, 100, 300, 400); + const fullNavigator = Rect.fromLTWH(250, 100, 300, 400); expect(tester.getRect(find.byType(Navigator)), fullNavigator); final Rect materialRectClosed = tester.getRect( @@ -1306,9 +1299,7 @@ void main() { testWidgets( 'Container partly offscreen can be opened without crash - vertical', (WidgetTester tester) async { - final ScrollController controller = ScrollController( - initialScrollOffset: 50, - ); + final controller = ScrollController(initialScrollOffset: 50); await tester.pumpWidget( Center( child: SizedBox( @@ -1382,9 +1373,7 @@ void main() { testWidgets( 'Container partly offscreen can be opened without crash - horizontal', (WidgetTester tester) async { - final ScrollController controller = ScrollController( - initialScrollOffset: 50, - ); + final controller = ScrollController(initialScrollOffset: 50); await tester.pumpWidget( Center( child: SizedBox( @@ -1494,7 +1483,7 @@ void main() { testWidgets('onClosed callback is called when container has closed', ( WidgetTester tester, ) async { - bool hasClosed = false; + var hasClosed = false; final Widget openContainer = OpenContainer( onClosed: (dynamic _) { hasClosed = true; @@ -1666,8 +1655,8 @@ void main() { testWidgets( 'Verify that "useRootNavigator: false" uses the correct navigator', (WidgetTester tester) async { - const Key appKey = Key('App'); - const Key nestedNavigatorKey = Key('Nested Navigator'); + const appKey = Key('App'); + const nestedNavigatorKey = Key('Nested Navigator'); await tester.pumpWidget( createRootNavigatorTest( @@ -1698,8 +1687,8 @@ void main() { testWidgets( 'Verify that "useRootNavigator: true" uses the correct navigator', (WidgetTester tester) async { - const Key appKey = Key('App'); - const Key nestedNavigatorKey = Key('Nested Navigator'); + const appKey = Key('App'); + const nestedNavigatorKey = Key('Nested Navigator'); await tester.pumpWidget( createRootNavigatorTest( @@ -1730,8 +1719,8 @@ void main() { testWidgets('Verify correct opened size when "useRootNavigator: false"', ( WidgetTester tester, ) async { - const Key appKey = Key('App'); - const Key nestedNavigatorKey = Key('Nested Navigator'); + const appKey = Key('App'); + const nestedNavigatorKey = Key('Nested Navigator'); await tester.pumpWidget( createRootNavigatorTest( @@ -1753,8 +1742,8 @@ void main() { testWidgets('Verify correct opened size when "useRootNavigator: true"', ( WidgetTester tester, ) async { - const Key appKey = Key('App'); - const Key nestedNavigatorKey = Key('Nested Navigator'); + const appKey = Key('App'); + const nestedNavigatorKey = Key('Nested Navigator'); await tester.pumpWidget( createRootNavigatorTest( @@ -1776,7 +1765,7 @@ void main() { testWidgets('Verify routeSettings passed to Navigator', ( WidgetTester tester, ) async { - const RouteSettings routeSettings = RouteSettings( + const routeSettings = RouteSettings( name: 'route-name', arguments: 'arguments', ); @@ -1852,12 +1841,11 @@ class _TrackedData { } double _getRadius(Material material) { - final RoundedRectangleBorder? shape = - material.shape as RoundedRectangleBorder?; + final shape = material.shape as RoundedRectangleBorder?; if (shape == null) { return 0.0; } - final BorderRadius radius = shape.borderRadius as BorderRadius; + final radius = shape.borderRadius as BorderRadius; return radius.topRight.x; } diff --git a/packages/animations/test/page_transition_switcher_test.dart b/packages/animations/test/page_transition_switcher_test.dart index 930729893c7b..56f4c774b818 100644 --- a/packages/animations/test/page_transition_switcher_test.dart +++ b/packages/animations/test/page_transition_switcher_test.dart @@ -8,9 +8,9 @@ import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('transitions in a new child.', (WidgetTester tester) async { - final UniqueKey containerOne = UniqueKey(); - final UniqueKey containerTwo = UniqueKey(); - final UniqueKey containerThree = UniqueKey(); + final containerOne = UniqueKey(); + final containerTwo = UniqueKey(); + final containerThree = UniqueKey(); await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), @@ -87,9 +87,9 @@ void main() { testWidgets('transitions in a new child in reverse.', ( WidgetTester tester, ) async { - final UniqueKey containerOne = UniqueKey(); - final UniqueKey containerTwo = UniqueKey(); - final UniqueKey containerThree = UniqueKey(); + final containerOne = UniqueKey(); + final containerTwo = UniqueKey(); + final containerThree = UniqueKey(); await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), @@ -167,9 +167,9 @@ void main() { }); testWidgets('switch from forward to reverse', (WidgetTester tester) async { - final UniqueKey containerOne = UniqueKey(); - final UniqueKey containerTwo = UniqueKey(); - final UniqueKey containerThree = UniqueKey(); + final containerOne = UniqueKey(); + final containerTwo = UniqueKey(); + final containerThree = UniqueKey(); await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), @@ -239,9 +239,9 @@ void main() { }); testWidgets('switch from reverse to forward.', (WidgetTester tester) async { - final UniqueKey containerOne = UniqueKey(); - final UniqueKey containerTwo = UniqueKey(); - final UniqueKey containerThree = UniqueKey(); + final containerOne = UniqueKey(); + final containerTwo = UniqueKey(); + final containerThree = UniqueKey(); await tester.pumpWidget( PageTransitionSwitcher( duration: const Duration(milliseconds: 100), @@ -458,9 +458,9 @@ void main() { testWidgets("doesn't reset state of the children in transitions.", ( WidgetTester tester, ) async { - final UniqueKey statefulOne = UniqueKey(); - final UniqueKey statefulTwo = UniqueKey(); - final UniqueKey statefulThree = UniqueKey(); + final statefulOne = UniqueKey(); + final statefulTwo = UniqueKey(); + final statefulThree = UniqueKey(); StatefulTestWidgetState.generation = 0; @@ -555,9 +555,9 @@ void main() { testWidgets( 'updates previous child transitions if the transitionBuilder changes.', (WidgetTester tester) async { - final UniqueKey containerOne = UniqueKey(); - final UniqueKey containerTwo = UniqueKey(); - final UniqueKey containerThree = UniqueKey(); + final containerOne = UniqueKey(); + final containerTwo = UniqueKey(); + final containerThree = UniqueKey(); // Insert three unique children so that we have some previous children. await tester.pumpWidget( @@ -687,8 +687,8 @@ Widget _transitionBuilder( Map _getSecondaryAnimation(List keys, WidgetTester tester) { expect(find.byType(FadeTransition), findsNWidgets(keys.length)); - final Map result = {}; - for (final Key key in keys) { + final result = {}; + for (final key in keys) { final FadeTransition transition = tester.firstWidget( find.ancestor(of: find.byKey(key), matching: find.byType(FadeTransition)), ); @@ -699,8 +699,8 @@ Map _getSecondaryAnimation(List keys, WidgetTester tester) { Map _getPrimaryAnimation(List keys, WidgetTester tester) { expect(find.byType(ScaleTransition), findsNWidgets(keys.length)); - final Map result = {}; - for (final Key key in keys) { + final result = {}; + for (final key in keys) { final ScaleTransition transition = tester.firstWidget( find.ancestor( of: find.byKey(key), diff --git a/packages/animations/test/shared_axis_transition_test.dart b/packages/animations/test/shared_axis_transition_test.dart index db861390a6f0..d422071df183 100644 --- a/packages/animations/test/shared_axis_transition_test.dart +++ b/packages/animations/test/shared_axis_transition_test.dart @@ -12,10 +12,8 @@ void main() { testWidgets( 'SharedAxisPageTransitionsBuilder builds a SharedAxisTransition', (WidgetTester tester) async { - final AnimationController animation = AnimationController( - vsync: const TestVSync(), - ); - final AnimationController secondaryAnimation = AnimationController( + final animation = AnimationController(vsync: const TestVSync()); + final secondaryAnimation = AnimationController( vsync: const TestVSync(), ); @@ -38,9 +36,9 @@ void main() { testWidgets('SharedAxisTransition runs forward', ( WidgetTester tester, ) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; await tester.pumpWidget( _TestWidget( @@ -160,9 +158,9 @@ void main() { testWidgets('SharedAxisTransition runs in reverse', ( WidgetTester tester, ) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; await tester.pumpWidget( _TestWidget( @@ -285,9 +283,9 @@ void main() { testWidgets('SharedAxisTransition does not jump when interrupted', ( WidgetTester tester, ) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; await tester.pumpWidget( _TestWidget( @@ -414,9 +412,9 @@ void main() { testWidgets('State is not lost when transitioning', ( WidgetTester tester, ) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; await tester.pumpWidget( _TestWidget( @@ -502,9 +500,9 @@ void main() { }); testWidgets('default fill color', (WidgetTester tester) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; // The default fill color should be derived from ThemeData.canvasColor. final Color defaultFillColor = ThemeData().canvasColor; @@ -547,9 +545,9 @@ void main() { }); testWidgets('custom fill color', (WidgetTester tester) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; await tester.pumpWidget( _TestWidget( @@ -590,11 +588,11 @@ void main() { }); testWidgets('should keep state', (WidgetTester tester) async { - final AnimationController animation = AnimationController( + final animation = AnimationController( vsync: const TestVSync(), duration: const Duration(milliseconds: 300), ); - final AnimationController secondaryAnimation = AnimationController( + final secondaryAnimation = AnimationController( vsync: const TestVSync(), duration: const Duration(milliseconds: 300), ); @@ -662,10 +660,8 @@ void main() { testWidgets( 'SharedAxisPageTransitionsBuilder builds a SharedAxisTransition', (WidgetTester tester) async { - final AnimationController animation = AnimationController( - vsync: const TestVSync(), - ); - final AnimationController secondaryAnimation = AnimationController( + final animation = AnimationController(vsync: const TestVSync()); + final secondaryAnimation = AnimationController( vsync: const TestVSync(), ); @@ -688,9 +684,9 @@ void main() { testWidgets('SharedAxisTransition runs forward', ( WidgetTester tester, ) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; await tester.pumpWidget( _TestWidget( @@ -810,9 +806,9 @@ void main() { testWidgets('SharedAxisTransition runs in reverse', ( WidgetTester tester, ) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; await tester.pumpWidget( _TestWidget( @@ -935,9 +931,9 @@ void main() { testWidgets('SharedAxisTransition does not jump when interrupted', ( WidgetTester tester, ) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; await tester.pumpWidget( _TestWidget( @@ -1064,9 +1060,9 @@ void main() { testWidgets('State is not lost when transitioning', ( WidgetTester tester, ) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; await tester.pumpWidget( _TestWidget( @@ -1152,9 +1148,9 @@ void main() { }); testWidgets('default fill color', (WidgetTester tester) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; // The default fill color should be derived from ThemeData.canvasColor. final Color defaultFillColor = ThemeData().canvasColor; @@ -1197,9 +1193,9 @@ void main() { }); testWidgets('custom fill color', (WidgetTester tester) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; await tester.pumpWidget( _TestWidget( @@ -1240,11 +1236,11 @@ void main() { }); testWidgets('should keep state', (WidgetTester tester) async { - final AnimationController animation = AnimationController( + final animation = AnimationController( vsync: const TestVSync(), duration: const Duration(milliseconds: 300), ); - final AnimationController secondaryAnimation = AnimationController( + final secondaryAnimation = AnimationController( vsync: const TestVSync(), duration: const Duration(milliseconds: 300), ); @@ -1312,10 +1308,8 @@ void main() { testWidgets( 'SharedAxisPageTransitionsBuilder builds a SharedAxisTransition', (WidgetTester tester) async { - final AnimationController animation = AnimationController( - vsync: const TestVSync(), - ); - final AnimationController secondaryAnimation = AnimationController( + final animation = AnimationController(vsync: const TestVSync()); + final secondaryAnimation = AnimationController( vsync: const TestVSync(), ); @@ -1338,9 +1332,9 @@ void main() { testWidgets('SharedAxisTransition runs forward', ( WidgetTester tester, ) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; await tester.pumpWidget( _TestWidget( @@ -1415,9 +1409,9 @@ void main() { testWidgets('SharedAxisTransition runs in reverse', ( WidgetTester tester, ) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; await tester.pumpWidget( _TestWidget( @@ -1497,9 +1491,9 @@ void main() { testWidgets('SharedAxisTransition does not jump when interrupted', ( WidgetTester tester, ) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; await tester.pumpWidget( _TestWidget( @@ -1569,9 +1563,9 @@ void main() { testWidgets('SharedAxisTransition properly disposes animation', ( WidgetTester tester, ) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; await tester.pumpWidget( _TestWidget( @@ -1604,9 +1598,9 @@ void main() { testWidgets('State is not lost when transitioning', ( WidgetTester tester, ) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; await tester.pumpWidget( _TestWidget( @@ -1692,9 +1686,9 @@ void main() { }); testWidgets('default fill color', (WidgetTester tester) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; // The default fill color should be derived from ThemeData.canvasColor. final Color defaultFillColor = ThemeData().canvasColor; @@ -1737,9 +1731,9 @@ void main() { }); testWidgets('custom fill color', (WidgetTester tester) async { - final GlobalKey navigator = GlobalKey(); - const String bottomRoute = '/'; - const String topRoute = '/a'; + final navigator = GlobalKey(); + const bottomRoute = '/'; + const topRoute = '/a'; await tester.pumpWidget( _TestWidget( @@ -1780,11 +1774,11 @@ void main() { }); testWidgets('should keep state', (WidgetTester tester) async { - final AnimationController animation = AnimationController( + final animation = AnimationController( vsync: const TestVSync(), duration: const Duration(milliseconds: 300), ); - final AnimationController secondaryAnimation = AnimationController( + final secondaryAnimation = AnimationController( vsync: const TestVSync(), duration: const Duration(milliseconds: 300), ); @@ -1855,7 +1849,7 @@ double _getOpacity(String key, WidgetTester tester) { matching: find.byType(FadeTransition), ); return tester.widgetList(finder).fold(1.0, (double a, Widget widget) { - final FadeTransition transition = widget as FadeTransition; + final transition = widget as FadeTransition; return a * transition.opacity.value; }); } @@ -1876,7 +1870,7 @@ double _getTranslationOffset( double a, Widget widget, ) { - final Transform transition = widget as Transform; + final transition = widget as Transform; final Vector3 translation = transition.transform.getTranslation(); return a + translation.x; }); @@ -1885,7 +1879,7 @@ double _getTranslationOffset( double a, Widget widget, ) { - final Transform transition = widget as Transform; + final transition = widget as Transform; final Vector3 translation = transition.transform.getTranslation(); return a + translation.y; }); @@ -1904,7 +1898,7 @@ double _getScale(String key, WidgetTester tester) { matching: find.byType(ScaleTransition), ); return tester.widgetList(finder).fold(1.0, (double a, Widget widget) { - final ScaleTransition transition = widget as ScaleTransition; + final transition = widget as ScaleTransition; return a * transition.scale.value; }); } diff --git a/packages/camera/camera/AUTHORS b/packages/camera/camera/AUTHORS index 493a0b4ef9c2..605414ab7dcf 100644 --- a/packages/camera/camera/AUTHORS +++ b/packages/camera/camera/AUTHORS @@ -64,3 +64,4 @@ Aleksandr Yurkovskiy Anton Borries Alex Li Rahul Raj <64.rahulraj@gmail.com> +Rui Craveiro diff --git a/packages/camera/camera/CHANGELOG.md b/packages/camera/camera/CHANGELOG.md index cbb5031f6da0..557e16ea59e4 100644 --- a/packages/camera/camera/CHANGELOG.md +++ b/packages/camera/camera/CHANGELOG.md @@ -1,6 +1,24 @@ -## NEXT +## 0.12.0+1 -* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. +* Makes `Optional.of` constructor `const`. + +## 0.12.0 + +* Adds support for video stabilization. + +## 0.11.4 + +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. +* Fixes a bug where exceptions thrown during return within try blocks in an async function were not correctly caught, aligning behavior with expected Dart semantics (see [dart-lang/sdk#44395](https://github.com/dart-lang/sdk/issues/44395)). +* Updates example to demonstrate correct exception handling for async return within try blocks, ensuring exceptions thrown during return are properly caught as per [dart-lang/sdk#44395](https://github.com/dart-lang/sdk/issues/44395). + +## 0.11.3+1 + +* Fixes delivering errors from onCameraError. +* Updates README to reflect currently supported OS versions for the latest + versions of the endorsed platform implementations. + * Applications built with older versions of Flutter will continue to + use compatible versions of the platform implementations. ## 0.11.3 diff --git a/packages/camera/camera/README.md b/packages/camera/camera/README.md index cb016d68c96e..f3fbdc35a738 100644 --- a/packages/camera/camera/README.md +++ b/packages/camera/camera/README.md @@ -8,7 +8,7 @@ A Flutter plugin for iOS, Android and Web allowing access to the device cameras. | | Android | iOS | Web | |----------------|---------|-----------|------------------------| -| **Support** | SDK 24+ | iOS 12.0+ | [See `camera_web `][1] | +| **Support** | SDK 24+ | iOS 13.0+ | [See `camera_web `][1] | ## Features diff --git a/packages/camera/camera/example/android/app/gradle/wrapper/gradle-wrapper.properties b/packages/camera/camera/example/android/app/gradle/wrapper/gradle-wrapper.properties index 0c68fbc1dadd..4a647536b632 100644 --- a/packages/camera/camera/example/android/app/gradle/wrapper/gradle-wrapper.properties +++ b/packages/camera/camera/example/android/app/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.0-all.zip +networkTimeout=10000 zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists - diff --git a/packages/camera/camera/example/android/settings.gradle b/packages/camera/camera/example/android/settings.gradle index d00a6cf2438a..d7ba8d54ffbc 100644 --- a/packages/camera/camera/example/android/settings.gradle +++ b/packages/camera/camera/example/android/settings.gradle @@ -19,8 +19,8 @@ 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.11.0" apply false - id "org.jetbrains.kotlin.android" version "2.2.0" apply false + id "com.android.application" version "8.11.1" apply false + id "org.jetbrains.kotlin.android" version "2.2.20" apply false id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1" } diff --git a/packages/camera/camera/example/integration_test/camera_test.dart b/packages/camera/camera/example/integration_test/camera_test.dart index c12e5880bd5d..258110e41a1b 100644 --- a/packages/camera/camera/example/integration_test/camera_test.dart +++ b/packages/camera/camera/example/integration_test/camera_test.dart @@ -31,19 +31,18 @@ void main() { await testDir.delete(recursive: true); }); - final Map presetExpectedSizes = - { - ResolutionPreset.low: Platform.isAndroid - ? const Size(240, 320) - : const Size(288, 352), - ResolutionPreset.medium: Platform.isAndroid - ? const Size(480, 720) - : const Size(480, 640), - ResolutionPreset.high: const Size(720, 1280), - ResolutionPreset.veryHigh: const Size(1080, 1920), - ResolutionPreset.ultraHigh: const Size(2160, 3840), - // Don't bother checking for max here since it could be anything. - }; + final presetExpectedSizes = { + ResolutionPreset.low: Platform.isAndroid + ? const Size(240, 320) + : const Size(288, 352), + ResolutionPreset.medium: Platform.isAndroid + ? const Size(480, 720) + : const Size(480, 640), + ResolutionPreset.high: const Size(720, 1280), + ResolutionPreset.veryHigh: const Size(1080, 1920), + ResolutionPreset.ultraHigh: const Size(2160, 3840), + // Don't bother checking for max here since it could be anything. + }; /// Verify that [actual] has dimensions that are at least as large as /// [expectedSize]. Allows for a mismatch in portrait vs landscape. Returns @@ -70,10 +69,8 @@ void main() { final XFile file = await controller.stopVideoRecording(); // Load video metadata - final File videoFile = File(file.path); - final VideoPlayerController videoController = VideoPlayerController.file( - videoFile, - ); + final videoFile = File(file.path); + final videoController = VideoPlayerController.file(videoFile); await videoController.initialize(); final Size video = videoController.value.size; @@ -92,14 +89,11 @@ void main() { if (cameras.isEmpty) { return; } - for (final CameraDescription cameraDescription in cameras) { - bool previousPresetExactlySupported = true; + for (final cameraDescription in cameras) { + var previousPresetExactlySupported = true; for (final MapEntry preset in presetExpectedSizes.entries) { - final CameraController controller = CameraController( - cameraDescription, - preset.key, - ); + final controller = CameraController(cameraDescription, preset.key); await controller.initialize(); await controller.prepareForVideoRecording(); final bool presetExactlySupported = await testCaptureVideoResolution( @@ -125,7 +119,7 @@ void main() { return; } - final CameraController controller = CameraController( + final controller = CameraController( cameras[0], ResolutionPreset.low, enableAudio: false, @@ -142,10 +136,8 @@ void main() { final int recordingTime = DateTime.now().millisecondsSinceEpoch - recordingStart; - final File videoFile = File(file.path); - final VideoPlayerController videoController = VideoPlayerController.file( - videoFile, - ); + final videoFile = File(file.path); + final videoController = VideoPlayerController.file(videoFile); await videoController.initialize(); final int duration = videoController.value.duration.inMilliseconds; await videoController.dispose(); @@ -159,7 +151,7 @@ void main() { return; } - final CameraController controller = CameraController( + final controller = CameraController( cameras[0], ResolutionPreset.low, enableAudio: false, @@ -169,14 +161,14 @@ void main() { await controller.prepareForVideoRecording(); int startPause; - int timePaused = 0; - const int pauseIterations = 2; + var timePaused = 0; + const pauseIterations = 2; await controller.startVideoRecording(); final int recordingStart = DateTime.now().millisecondsSinceEpoch; sleep(const Duration(milliseconds: 500)); - for (int i = 0; i < pauseIterations; i++) { + for (var i = 0; i < pauseIterations; i++) { await controller.pauseVideoRecording(); startPause = DateTime.now().millisecondsSinceEpoch; sleep(const Duration(milliseconds: 500)); @@ -190,10 +182,8 @@ void main() { final int recordingTime = DateTime.now().millisecondsSinceEpoch - recordingStart; - final File videoFile = File(file.path); - final VideoPlayerController videoController = VideoPlayerController.file( - videoFile, - ); + final videoFile = File(file.path); + final videoController = VideoPlayerController.file(videoFile); await videoController.initialize(); final int duration = videoController.value.duration.inMilliseconds; await videoController.dispose(); @@ -207,14 +197,14 @@ void main() { return; } - final CameraController controller = CameraController( + final controller = CameraController( cameras[0], ResolutionPreset.low, enableAudio: false, ); await controller.initialize(); - bool isDetecting = false; + var isDetecting = false; await controller.startImageStream((CameraImage image) { if (isDetecting) { @@ -239,7 +229,7 @@ void main() { List cameras, ImageFormatGroup? imageFormatGroup, ) async { - final CameraController controller = CameraController( + final controller = CameraController( cameras.first, ResolutionPreset.low, enableAudio: false, @@ -247,7 +237,7 @@ void main() { ); await controller.initialize(); - final Completer completer = Completer(); + final completer = Completer(); await controller.startImageStream((CameraImage image) { if (!completer.isCompleted) { @@ -270,10 +260,7 @@ void main() { return; } - final CameraController controller = CameraController( - cameras[0], - ResolutionPreset.low, - ); + final controller = CameraController(cameras[0], ResolutionPreset.low); await controller.initialize(); await controller.prepareForVideoRecording(); @@ -289,10 +276,8 @@ void main() { final XFile file = await controller.stopVideoRecording(); - final File videoFile = File(file.path); - final VideoPlayerController videoController = VideoPlayerController.file( - videoFile, - ); + final videoFile = File(file.path); + final videoController = VideoPlayerController.file(videoFile); await videoController.initialize(); final int duration = videoController.value.duration.inMilliseconds; await videoController.dispose(); @@ -310,7 +295,7 @@ void main() { return; } - final CameraController controller = CameraController( + final controller = CameraController( cameras[0], ResolutionPreset.low, enableAudio: false, diff --git a/packages/camera/camera/example/ios/Flutter/AppFrameworkInfo.plist b/packages/camera/camera/example/ios/Flutter/AppFrameworkInfo.plist index 7c5696400627..391a902b2beb 100644 --- a/packages/camera/camera/example/ios/Flutter/AppFrameworkInfo.plist +++ b/packages/camera/camera/example/ios/Flutter/AppFrameworkInfo.plist @@ -20,7 +20,5 @@ ???? CFBundleVersion 1.0 - MinimumOSVersion - 12.0 diff --git a/packages/camera/camera/example/ios/Flutter/Debug.xcconfig b/packages/camera/camera/example/ios/Flutter/Debug.xcconfig index ec97fc6f3021..592ceee85b89 100644 --- a/packages/camera/camera/example/ios/Flutter/Debug.xcconfig +++ b/packages/camera/camera/example/ios/Flutter/Debug.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" diff --git a/packages/camera/camera/example/ios/Flutter/Release.xcconfig b/packages/camera/camera/example/ios/Flutter/Release.xcconfig index c4855bfe2000..592ceee85b89 100644 --- a/packages/camera/camera/example/ios/Flutter/Release.xcconfig +++ b/packages/camera/camera/example/ios/Flutter/Release.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" diff --git a/packages/camera/camera/example/ios/Podfile b/packages/camera/camera/example/ios/Podfile deleted file mode 100644 index 01d4aa611bb9..000000000000 --- a/packages/camera/camera/example/ios/Podfile +++ /dev/null @@ -1,40 +0,0 @@ -# Uncomment this line to define a global platform for your project -# platform :ios, '12.0' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_ios_podfile_setup - -target 'Runner' do - use_frameworks! - - flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_ios_build_settings(target) - end -end diff --git a/packages/camera/camera/example/ios/Runner.xcodeproj/project.pbxproj b/packages/camera/camera/example/ios/Runner.xcodeproj/project.pbxproj index 92de69f31b7a..ee233668159d 100644 --- a/packages/camera/camera/example/ios/Runner.xcodeproj/project.pbxproj +++ b/packages/camera/camera/example/ios/Runner.xcodeproj/project.pbxproj @@ -14,7 +14,6 @@ 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; - EB6758FFC1A59E7774509E39 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6CA17D06B2B6044C6A951FD9 /* Pods_Runner.framework */; }; /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -31,15 +30,12 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 0010728987EF6ACD54767767 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; - 18740A70956D02B893DD99B5 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; - 1B2BDE3874E413D6318A95CE /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; - 6CA17D06B2B6044C6A951FD9 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; @@ -56,35 +52,16 @@ buildActionMask = 2147483647; files = ( 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, - EB6758FFC1A59E7774509E39 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 329964CB20AC702500CCE47E /* Pods */ = { - isa = PBXGroup; - children = ( - 0010728987EF6ACD54767767 /* Pods-Runner.debug.xcconfig */, - 18740A70956D02B893DD99B5 /* Pods-Runner.release.xcconfig */, - 1B2BDE3874E413D6318A95CE /* Pods-Runner.profile.xcconfig */, - ); - name = Pods; - path = Pods; - sourceTree = ""; - }; - 511227E4C822303A7548D1DE /* Frameworks */ = { - isa = PBXGroup; - children = ( - 6CA17D06B2B6044C6A951FD9 /* Pods_Runner.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, 9740EEB21CF90195004384FC /* Debug.xcconfig */, 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, @@ -99,8 +76,6 @@ 9740EEB11CF90186004384FC /* Flutter */, 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, - 329964CB20AC702500CCE47E /* Pods */, - 511227E4C822303A7548D1DE /* Frameworks */, ); sourceTree = ""; }; @@ -134,7 +109,6 @@ isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - C277C3093C2BC2BEC825E592 /* [CP] Check Pods Manifest.lock */, 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, @@ -237,28 +211,6 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; }; - C277C3093C2BC2BEC825E592 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -336,7 +288,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -415,7 +367,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -466,7 +418,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; diff --git a/packages/camera/camera/example/lib/main.dart b/packages/camera/camera/example/lib/main.dart index f8d4c8c44dc7..cca528c04fda 100644 --- a/packages/camera/camera/example/lib/main.dart +++ b/packages/camera/camera/example/lib/main.dart @@ -558,7 +558,7 @@ class _CameraExampleHomeState extends State /// Display a row of toggle to select the camera (or a message if no camera is available). Widget _cameraTogglesRowWidget() { - final List toggles = []; + final toggles = []; void onChanged(CameraDescription? description) { if (description == null) { @@ -614,7 +614,7 @@ class _CameraExampleHomeState extends State final CameraController cameraController = controller!; - final Offset offset = Offset( + final offset = Offset( details.localPosition.dx / constraints.maxWidth, details.localPosition.dy / constraints.maxHeight, ); @@ -633,7 +633,7 @@ class _CameraExampleHomeState extends State Future _initializeCameraController( CameraDescription cameraDescription, ) async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( cameraDescription, kIsWeb ? ResolutionPreset.max : ResolutionPreset.medium, enableAudio: enableAudio, @@ -888,7 +888,7 @@ class _CameraExampleHomeState extends State } try { - return cameraController.stopVideoRecording(); + return await cameraController.stopVideoRecording(); } on CameraException catch (e) { _showCameraException(e); return null; @@ -985,7 +985,7 @@ class _CameraExampleHomeState extends State return; } - final VideoPlayerController vController = kIsWeb + final vController = kIsWeb ? VideoPlayerController.networkUrl(Uri.parse(videoFile!.path)) : VideoPlayerController.file(File(videoFile!.path)); diff --git a/packages/camera/camera/example/pubspec.yaml b/packages/camera/camera/example/pubspec.yaml index 34003f4bea6e..b5d9dff6e913 100644 --- a/packages/camera/camera/example/pubspec.yaml +++ b/packages/camera/camera/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the camera plugin. publish_to: none environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" dependencies: camera: diff --git a/packages/camera/camera/example/test/main_test.dart b/packages/camera/camera/example/test/main_test.dart index fe969d9a3c6a..9563df089fac 100644 --- a/packages/camera/camera/example/test/main_test.dart +++ b/packages/camera/camera/example/test/main_test.dart @@ -20,7 +20,7 @@ void main() { ) async { WidgetsFlutterBinding.ensureInitialized(); // Adds 10 fake camera descriptions. - for (int i = 0; i < 10; i++) { + for (var i = 0; i < 10; i++) { cameras.add( CameraDescription( name: 'camera_$i', diff --git a/packages/camera/camera/example/test_driver/integration_test.dart b/packages/camera/camera/example/test_driver/integration_test.dart index d512473309e9..ef65f091ca07 100644 --- a/packages/camera/camera/example/test_driver/integration_test.dart +++ b/packages/camera/camera/example/test_driver/integration_test.dart @@ -17,8 +17,7 @@ Future main() async { print('This test must be run on a POSIX host. Skipping...'); exit(0); } - final bool adbExists = - Process.runSync('which', ['adb']).exitCode == 0; + final adbExists = Process.runSync('which', ['adb']).exitCode == 0; if (!adbExists) { print(r'This test needs ADB to exist on the $PATH. Skipping...'); exit(0); @@ -61,6 +60,6 @@ Future main() async { 'android.permission.RECORD_AUDIO', ]); - final Map result = jsonDecode(data) as Map; + final result = jsonDecode(data) as Map; exit(result['result'] == 'true' ? 0 : 1); } diff --git a/packages/camera/camera/lib/camera.dart b/packages/camera/camera/lib/camera.dart index 2557b3c58cdb..1558dbf687d0 100644 --- a/packages/camera/camera/lib/camera.dart +++ b/packages/camera/camera/lib/camera.dart @@ -13,6 +13,7 @@ export 'package:camera_platform_interface/camera_platform_interface.dart' FocusMode, ImageFormatGroup, ResolutionPreset, + VideoStabilizationMode, XFile; export 'src/camera_controller.dart'; diff --git a/packages/camera/camera/lib/src/camera_controller.dart b/packages/camera/camera/lib/src/camera_controller.dart index 23494b4b27ff..d941c2e85f66 100644 --- a/packages/camera/camera/lib/src/camera_controller.dart +++ b/packages/camera/camera/lib/src/camera_controller.dart @@ -28,10 +28,6 @@ Future> availableCameras() async { return CameraPlatform.instance.availableCameras(); } -// TODO(stuartmorgan): Remove this once the package requires 2.10, where the -// dart:async `unawaited` accepts a nullable future. -void _unawaited(Future? future) {} - /// The state of a [CameraController]. class CameraValue { /// Creates a new camera controller state. @@ -54,6 +50,7 @@ class CameraValue { this.recordingOrientation, this.isPreviewPaused = false, this.previewPauseOrientation, + this.videoStabilizationMode = VideoStabilizationMode.off, }) : _isRecordingPaused = isRecordingPaused; /// Creates a new camera controller state for an uninitialized controller. @@ -72,6 +69,7 @@ class CameraValue { deviceOrientation: DeviceOrientation.portraitUp, isPreviewPaused: false, description: description, + videoStabilizationMode: VideoStabilizationMode.off, ); /// True after [CameraController.initialize] has completed successfully. @@ -148,6 +146,9 @@ class CameraValue { /// The properties of the camera device controlled by this controller. final CameraDescription description; + /// The current video stabilization mode. + final VideoStabilizationMode videoStabilizationMode; + /// Creates a modified copy of the object. /// /// Explicitly specified fields get the specified value, all other fields get @@ -171,10 +172,11 @@ class CameraValue { bool? isPreviewPaused, CameraDescription? description, Optional? previewPauseOrientation, + VideoStabilizationMode? videoStabilizationMode, }) { return CameraValue( isInitialized: isInitialized ?? this.isInitialized, - errorDescription: errorDescription, + errorDescription: errorDescription ?? this.errorDescription, previewSize: previewSize ?? this.previewSize, isRecordingVideo: isRecordingVideo ?? this.isRecordingVideo, isTakingPicture: isTakingPicture ?? this.isTakingPicture, @@ -198,6 +200,8 @@ class CameraValue { previewPauseOrientation: previewPauseOrientation == null ? this.previewPauseOrientation : previewPauseOrientation.orNull, + videoStabilizationMode: + videoStabilizationMode ?? this.videoStabilizationMode, ); } @@ -219,6 +223,7 @@ class CameraValue { 'recordingOrientation: $recordingOrientation, ' 'isPreviewPaused: $isPreviewPaused, ' 'previewPausedOrientation: $previewPauseOrientation, ' + 'videoStabilizationMode: $videoStabilizationMode, ' 'description: $description)'; } } @@ -327,12 +332,11 @@ class CameraController extends ValueNotifier { ); } - final Completer initializeCompleter = Completer(); + final initializeCompleter = Completer(); _initializeFuture = initializeCompleter.future; try { - final Completer initializeCompleter = - Completer(); + final initializeCompleter = Completer(); _deviceOrientationSubscription ??= CameraPlatform.instance .onDeviceOrientationChanged() @@ -345,7 +349,7 @@ class CameraController extends ValueNotifier { mediaSettings, ); - _unawaited( + unawaited( CameraPlatform.instance.onCameraInitialized(_cameraId).first.then(( CameraInitializedEvent event, ) { @@ -353,6 +357,14 @@ class CameraController extends ValueNotifier { }), ); + unawaited( + CameraPlatform.instance.onCameraError(_cameraId).first.then(( + CameraErrorEvent event, + ) { + value = value.copyWith(errorDescription: event.description); + }), + ); + await CameraPlatform.instance.initializeCamera( _cameraId, imageFormatGroup: imageFormatGroup ?? ImageFormatGroup.unknown, @@ -713,6 +725,94 @@ class CameraController extends ValueNotifier { } } + /// Set the video stabilization mode for the selected camera. + /// + /// When [allowFallback] is true (default) the camera will be set to the best + /// video stabilization mode up to, and including, [mode]. + /// + /// When [allowFallback] is false and if [mode] is not one of the supported + /// modes (see [getSupportedVideoStabilizationModes]), then it throws an + /// [ArgumentError]. + /// + /// This feature is only available if [getSupportedVideoStabilizationModes] + /// returns at least one value other than [VideoStabilizationMode.off]. + Future setVideoStabilizationMode( + VideoStabilizationMode mode, { + bool allowFallback = true, + }) async { + _throwIfNotInitialized('setVideoStabilizationMode'); + try { + final VideoStabilizationMode? modeToSet = + await _getVideoStabilizationModeToSet(mode, allowFallback); + + // When _getVideoStabilizationModeToSet returns null + // it means that the device doesn't support any + // video stabilization mode and that doing nothing + // is valid because allowFallback is true or [mode] + // is [VideoStabilizationMode.off], so this results + // in a no-op. + if (modeToSet == null) { + return; + } + await CameraPlatform.instance.setVideoStabilizationMode( + _cameraId, + modeToSet, + ); + value = value.copyWith(videoStabilizationMode: modeToSet); + } on PlatformException catch (e) { + throw CameraException(e.code, e.message); + } + } + + Future _getVideoStabilizationModeToSet( + VideoStabilizationMode requestedMode, + bool allowFallback, + ) async { + final Iterable supportedModes = await CameraPlatform + .instance + .getSupportedVideoStabilizationModes(_cameraId); + + // If it can't fallback and the specific + // requested mode isn't available, then... + if (!allowFallback && !supportedModes.contains(requestedMode)) { + // if the request is off, it is a no-op + if (requestedMode == VideoStabilizationMode.off) { + return null; + } + // otherwise, it throws. + throw ArgumentError('Unavailable video stabilization mode.', 'mode'); + } + + VideoStabilizationMode? fallbackMode = requestedMode; + while (fallbackMode != null && !supportedModes.contains(fallbackMode)) { + fallbackMode = CameraPlatform.getFallbackVideoStabilizationMode( + fallbackMode, + ); + } + + return fallbackMode; + } + + /// Gets a list of video stabilization modes that are supported + /// for the selected camera. + /// + /// [VideoStabilizationMode.off] will always be listed. + Future> + getSupportedVideoStabilizationModes() async { + _throwIfNotInitialized('getSupportedVideoStabilizationModes'); + try { + final modes = { + VideoStabilizationMode.off, + ...await CameraPlatform.instance.getSupportedVideoStabilizationModes( + _cameraId, + ), + }; + return modes; + } on PlatformException catch (e) { + throw CameraException(e.code, e.message); + } + } + /// Sets the flash mode for taking pictures. Future setFlashMode(FlashMode mode) async { try { @@ -759,7 +859,7 @@ class CameraController extends ValueNotifier { Future getMinExposureOffset() async { _throwIfNotInitialized('getMinExposureOffset'); try { - return CameraPlatform.instance.getMinExposureOffset(_cameraId); + return await CameraPlatform.instance.getMinExposureOffset(_cameraId); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } @@ -769,7 +869,7 @@ class CameraController extends ValueNotifier { Future getMaxExposureOffset() async { _throwIfNotInitialized('getMaxExposureOffset'); try { - return CameraPlatform.instance.getMaxExposureOffset(_cameraId); + return await CameraPlatform.instance.getMaxExposureOffset(_cameraId); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } @@ -781,7 +881,7 @@ class CameraController extends ValueNotifier { Future getExposureOffsetStepSize() async { _throwIfNotInitialized('getExposureOffsetStepSize'); try { - return CameraPlatform.instance.getExposureOffsetStepSize(_cameraId); + return await CameraPlatform.instance.getExposureOffsetStepSize(_cameraId); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } @@ -826,7 +926,7 @@ class CameraController extends ValueNotifier { } try { - return CameraPlatform.instance.setExposureOffset(_cameraId, offset); + return await CameraPlatform.instance.setExposureOffset(_cameraId, offset); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } @@ -904,7 +1004,7 @@ class CameraController extends ValueNotifier { if (_isDisposed) { return; } - _unawaited(_deviceOrientationSubscription?.cancel()); + unawaited(_deviceOrientationSubscription?.cancel()); _isDisposed = true; super.dispose(); if (_initializeFuture != null) { @@ -949,13 +1049,7 @@ class Optional extends IterableBase { const Optional.absent() : _value = null; /// Constructs an Optional of the given [value]. - /// - /// Throws [ArgumentError] if [value] is null. - Optional.of(T value) : _value = value { - // TODO(cbracken): Delete and make this ctor const once mixed-mode - // execution is no longer around. - ArgumentError.checkNotNull(value); - } + const Optional.of(T value) : _value = value; /// Constructs an Optional of the given [value]. /// diff --git a/packages/camera/camera/lib/src/camera_preview.dart b/packages/camera/camera/lib/src/camera_preview.dart index ea0b601ac73a..c4af103bb00f 100644 --- a/packages/camera/camera/lib/src/camera_preview.dart +++ b/packages/camera/camera/lib/src/camera_preview.dart @@ -59,7 +59,7 @@ class CameraPreview extends StatelessWidget { } int _getQuarterTurns() { - final Map turns = { + final turns = { DeviceOrientation.portraitUp: 0, DeviceOrientation.landscapeRight: 1, DeviceOrientation.portraitDown: 2, diff --git a/packages/camera/camera/pubspec.yaml b/packages/camera/camera/pubspec.yaml index 95b55be083db..2d5967181c32 100644 --- a/packages/camera/camera/pubspec.yaml +++ b/packages/camera/camera/pubspec.yaml @@ -4,7 +4,7 @@ description: A Flutter plugin for controlling the camera. Supports previewing Dart. repository: https://github.com/flutter/packages/tree/main/packages/camera/camera issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+camera%22 -version: 0.11.3 +version: 0.12.0+1 environment: sdk: ^3.9.0 @@ -21,9 +21,9 @@ flutter: default_package: camera_web dependencies: - camera_android_camerax: ^0.6.22 - camera_avfoundation: ^0.9.18 - camera_platform_interface: ^2.11.0 + camera_android_camerax: ^0.7.0 + camera_avfoundation: ^0.10.0 + camera_platform_interface: ^2.12.0 camera_web: ^0.3.3 flutter: sdk: flutter diff --git a/packages/camera/camera/test/camera_image_stream_test.dart b/packages/camera/camera/test/camera_image_stream_test.dart index a78536b4b008..0a9644fcd8df 100644 --- a/packages/camera/camera/test/camera_image_stream_test.dart +++ b/packages/camera/camera/test/camera_image_stream_test.dart @@ -20,7 +20,7 @@ void main() { }); test('startImageStream() throws $CameraException when uninitialized', () { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -50,7 +50,7 @@ void main() { test( 'startImageStream() throws $CameraException when recording videos', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -80,7 +80,7 @@ void main() { test( 'startImageStream() throws $CameraException when already streaming images', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -107,7 +107,7 @@ void main() { ); test('startImageStream() calls CameraPlatform', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -127,7 +127,7 @@ void main() { }); test('stopImageStream() throws $CameraException when uninitialized', () { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -157,7 +157,7 @@ void main() { test( 'stopImageStream() throws $CameraException when not streaming images', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -181,7 +181,7 @@ void main() { ); test('stopImageStream() intended behaviour', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -203,7 +203,7 @@ void main() { }); test('startVideoRecording() can stream images', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -225,7 +225,7 @@ void main() { }); test('startVideoRecording() by default does not stream', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, diff --git a/packages/camera/camera/test/camera_image_test.dart b/packages/camera/camera/test/camera_image_test.dart index a9ea9d9c663b..6eb594497e39 100644 --- a/packages/camera/camera/test/camera_image_test.dart +++ b/packages/camera/camera/test/camera_image_test.dart @@ -9,7 +9,7 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('translates correctly from platform interface classes', () { - final CameraImageData originalImage = CameraImageData( + final originalImage = CameraImageData( format: const CameraImageFormat(ImageFormatGroup.jpeg, raw: 1234), planes: [ CameraImagePlane( @@ -34,7 +34,7 @@ void main() { sensorSensitivity: 1.3, ); - final CameraImage image = CameraImage.fromPlatformInterface(originalImage); + final image = CameraImage.fromPlatformInterface(originalImage); // Simple values. expect(image.width, 640); expect(image.height, 480); @@ -46,12 +46,12 @@ void main() { expect(image.format.raw, 1234); // Planes. expect(image.planes.length, originalImage.planes.length); - for (int i = 0; i < image.planes.length; i++) { + for (var i = 0; i < image.planes.length; i++) { expect( image.planes[i].bytes.length, originalImage.planes[i].bytes.length, ); - for (int j = 0; j < image.planes[i].bytes.length; j++) { + for (var j = 0; j < image.planes[i].bytes.length; j++) { expect(image.planes[i].bytes[j], originalImage.planes[i].bytes[j]); } expect( @@ -67,25 +67,23 @@ void main() { group('legacy constructors', () { test('$CameraImage can be created', () { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final CameraImage cameraImage = CameraImage.fromPlatformData( - { - 'format': 35, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4, - }, - ], - }, - ); + final cameraImage = CameraImage.fromPlatformData({ + 'format': 35, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }); expect(cameraImage.height, 1); expect(cameraImage.width, 4); expect(cameraImage.format.group, ImageFormatGroup.yuv420); @@ -95,123 +93,113 @@ void main() { test('$CameraImage has ImageFormatGroup.yuv420 for iOS', () { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; - final CameraImage cameraImage = CameraImage.fromPlatformData( - { - 'format': 875704438, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4, - }, - ], - }, - ); + final cameraImage = CameraImage.fromPlatformData({ + 'format': 875704438, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }); expect(cameraImage.format.group, ImageFormatGroup.yuv420); }); test('$CameraImage has ImageFormatGroup.yuv420 for Android', () { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final CameraImage cameraImage = CameraImage.fromPlatformData( - { - 'format': 35, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4, - }, - ], - }, - ); + final cameraImage = CameraImage.fromPlatformData({ + 'format': 35, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }); expect(cameraImage.format.group, ImageFormatGroup.yuv420); }); test('$CameraImage has ImageFormatGroup.nv21 for android', () { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final CameraImage cameraImage = CameraImage.fromPlatformData( - { - 'format': 17, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4, - }, - ], - }, - ); + final cameraImage = CameraImage.fromPlatformData({ + 'format': 17, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }); expect(cameraImage.format.group, ImageFormatGroup.nv21); }); test('$CameraImage has ImageFormatGroup.bgra8888 for iOS', () { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; - final CameraImage cameraImage = CameraImage.fromPlatformData( - { - 'format': 1111970369, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4, - }, - ], - }, - ); + final cameraImage = CameraImage.fromPlatformData({ + 'format': 1111970369, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }); expect(cameraImage.format.group, ImageFormatGroup.bgra8888); }); test('$CameraImage has ImageFormatGroup.unknown', () { - final CameraImage cameraImage = CameraImage.fromPlatformData( - { - 'format': null, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4, - }, - ], - }, - ); + final cameraImage = CameraImage.fromPlatformData({ + 'format': null, + 'height': 1, + 'width': 4, + 'lensAperture': 1.8, + 'sensorExposureTime': 9991324, + 'sensorSensitivity': 92.0, + 'planes': [ + { + 'bytes': Uint8List.fromList([1, 2, 3, 4]), + 'bytesPerPixel': 1, + 'bytesPerRow': 4, + 'height': 1, + 'width': 4, + }, + ], + }); expect(cameraImage.format.group, ImageFormatGroup.unknown); }); }); diff --git a/packages/camera/camera/test/camera_preview_test.dart b/packages/camera/camera/test/camera_preview_test.dart index bafc77831dcb..912a583e9255 100644 --- a/packages/camera/camera/test/camera_preview_test.dart +++ b/packages/camera/camera/test/camera_preview_test.dart @@ -139,6 +139,16 @@ class FakeController extends ValueNotifier @override CameraDescription get description => value.description; + @override + Future setVideoStabilizationMode( + VideoStabilizationMode mode, { + bool allowFallback = true, + }) async {} + + @override + Future> + getSupportedVideoStabilizationModes() async => []; + @override bool supportsImageStreaming() => true; } @@ -150,7 +160,7 @@ void main() { (WidgetTester tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); + final controller = FakeController(); addTearDown(controller.dispose); controller.value = controller.value.copyWith( @@ -189,7 +199,7 @@ void main() { (WidgetTester tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); + final controller = FakeController(); addTearDown(controller.dispose); controller.value = controller.value.copyWith( @@ -228,7 +238,7 @@ void main() { (WidgetTester tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); + final controller = FakeController(); addTearDown(controller.dispose); controller.value = controller.value.copyWith( @@ -267,7 +277,7 @@ void main() { (WidgetTester tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); + final controller = FakeController(); addTearDown(controller.dispose); controller.value = controller.value.copyWith( @@ -306,7 +316,7 @@ void main() { (WidgetTester tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); + final controller = FakeController(); addTearDown(controller.dispose); controller.value = controller.value.copyWith( @@ -344,7 +354,7 @@ void main() { (WidgetTester tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); + final controller = FakeController(); addTearDown(controller.dispose); controller.value = controller.value.copyWith( @@ -382,7 +392,7 @@ void main() { (WidgetTester tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); + final controller = FakeController(); addTearDown(controller.dispose); controller.value = controller.value.copyWith( @@ -420,7 +430,7 @@ void main() { (WidgetTester tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); + final controller = FakeController(); addTearDown(controller.dispose); controller.value = controller.value.copyWith( @@ -458,7 +468,7 @@ void main() { (WidgetTester tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); + final controller = FakeController(); addTearDown(controller.dispose); controller.value = controller.value.copyWith( @@ -492,7 +502,7 @@ void main() { (WidgetTester tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); + final controller = FakeController(); addTearDown(controller.dispose); controller.value = controller.value.copyWith( @@ -526,7 +536,7 @@ void main() { (WidgetTester tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); + final controller = FakeController(); addTearDown(controller.dispose); controller.value = controller.value.copyWith( @@ -560,7 +570,7 @@ void main() { (WidgetTester tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final FakeController controller = FakeController(); + final controller = FakeController(); addTearDown(controller.dispose); controller.value = controller.value.copyWith( @@ -594,7 +604,7 @@ void main() { WidgetTester tester, ) async { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; - final FakeController controller = FakeController(); + final controller = FakeController(); addTearDown(controller.dispose); controller.value = controller.value.copyWith( isInitialized: true, diff --git a/packages/camera/camera/test/camera_test.dart b/packages/camera/camera/test/camera_test.dart index c3af92bb7579..913d3391cd9e 100644 --- a/packages/camera/camera/test/camera_test.dart +++ b/packages/camera/camera/test/camera_test.dart @@ -61,11 +61,8 @@ void main() { test( 'debugCheckIsDisposed should not throw assertion error when disposed', () { - const MockCameraDescription description = MockCameraDescription(); - final CameraController controller = CameraController( - description, - ResolutionPreset.low, - ); + const description = MockCameraDescription(); + final controller = CameraController(description, ResolutionPreset.low); controller.dispose(); @@ -76,11 +73,8 @@ void main() { test( 'debugCheckIsDisposed should throw assertion error when not disposed', () { - const MockCameraDescription description = MockCameraDescription(); - final CameraController controller = CameraController( - description, - ResolutionPreset.low, - ); + const description = MockCameraDescription(); + final controller = CameraController(description, ResolutionPreset.low); expect(() => controller.debugCheckIsDisposed(), throwsAssertionError); }, @@ -101,7 +95,7 @@ void main() { }); test('Can be initialized', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -117,7 +111,7 @@ void main() { }); test('can be initialized with media settings', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -142,7 +136,7 @@ void main() { }); test('default constructor initializes media settings', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -160,7 +154,7 @@ void main() { }); test('can be disposed', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -180,7 +174,7 @@ void main() { }); test('initialize() throws CameraException when disposed', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -213,7 +207,7 @@ void main() { test( 'initialize() throws $CameraException on $PlatformException ', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -240,7 +234,7 @@ void main() { test('initialize() sets imageFormat', () async { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -261,7 +255,7 @@ void main() { test( 'setDescription waits for initialize before calling dispose', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -271,7 +265,7 @@ void main() { imageFormatGroup: ImageFormatGroup.bgra8888, ); - final Completer initializeCompleter = Completer(); + final initializeCompleter = Completer(); when( CameraPlatform.instance.initializeCamera( mockInitializeCamera, @@ -299,7 +293,7 @@ void main() { ); test('prepareForVideoRecording() calls $CameraPlatform ', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -315,7 +309,7 @@ void main() { }); test('takePicture() throws $CameraException when uninitialized ', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -344,7 +338,7 @@ void main() { test( 'takePicture() throws $CameraException when takePicture is true', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -371,7 +365,7 @@ void main() { ); test('takePicture() returns $XFile', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -388,7 +382,7 @@ void main() { test( 'takePicture() throws $CameraException on $PlatformException', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -416,7 +410,7 @@ void main() { test( 'startVideoRecording() throws $CameraException when uninitialized', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -446,7 +440,7 @@ void main() { test( 'startVideoRecording() throws $CameraException when recording videos', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -477,7 +471,7 @@ void main() { test( 'getMaxZoomLevel() throws $CameraException when uninitialized', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -506,7 +500,7 @@ void main() { ); test('getMaxZoomLevel() throws $CameraException when disposed', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -539,7 +533,7 @@ void main() { test( 'getMaxZoomLevel() throws $CameraException when a platform exception occured.', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -575,7 +569,7 @@ void main() { ); test('getMaxZoomLevel() returns max zoom level.', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -596,7 +590,7 @@ void main() { test( 'getMinZoomLevel() throws $CameraException when uninitialized', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -625,7 +619,7 @@ void main() { ); test('getMinZoomLevel() throws $CameraException when disposed', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -658,7 +652,7 @@ void main() { test( 'getMinZoomLevel() throws $CameraException when a platform exception occured.', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -694,7 +688,7 @@ void main() { ); test('getMinZoomLevel() returns max zoom level.', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -713,7 +707,7 @@ void main() { }); test('setZoomLevel() throws $CameraException when uninitialized', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -741,7 +735,7 @@ void main() { }); test('setZoomLevel() throws $CameraException when disposed', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -774,7 +768,7 @@ void main() { test( 'setZoomLevel() throws $CameraException when a platform exception occured.', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -814,7 +808,7 @@ void main() { test( 'setZoomLevel() completes and calls method channel with correct value.', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -833,7 +827,7 @@ void main() { ); test('setFlashMode() calls $CameraPlatform', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -856,7 +850,7 @@ void main() { test( 'setFlashMode() throws $CameraException on $PlatformException', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -892,7 +886,7 @@ void main() { ); test('setExposureMode() calls $CameraPlatform', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -915,7 +909,7 @@ void main() { test( 'setExposureMode() throws $CameraException on $PlatformException', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -951,7 +945,7 @@ void main() { ); test('setExposurePoint() calls $CameraPlatform', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -974,7 +968,7 @@ void main() { test( 'setExposurePoint() throws $CameraException on $PlatformException', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -1010,7 +1004,7 @@ void main() { ); test('getMinExposureOffset() calls $CameraPlatform', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -1034,7 +1028,7 @@ void main() { test( 'getMinExposureOffset() throws $CameraException on $PlatformException', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -1066,7 +1060,7 @@ void main() { ); test('getMaxExposureOffset() calls $CameraPlatform', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -1090,7 +1084,7 @@ void main() { test( 'getMaxExposureOffset() throws $CameraException on $PlatformException', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -1122,7 +1116,7 @@ void main() { ); test('getExposureOffsetStepSize() calls $CameraPlatform', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -1150,7 +1144,7 @@ void main() { test( 'getExposureOffsetStepSize() throws $CameraException on $PlatformException', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -1182,7 +1176,7 @@ void main() { ); test('setExposureOffset() calls $CameraPlatform', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -1222,7 +1216,7 @@ void main() { test( 'setExposureOffset() throws $CameraException on $PlatformException', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -1271,7 +1265,7 @@ void main() { test( 'setExposureOffset() throws $CameraException when offset is out of bounds', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -1361,7 +1355,7 @@ void main() { ); test('setExposureOffset() rounds offset to nearest step', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -1474,36 +1468,40 @@ void main() { ).called(4); }); - test('pausePreview() calls $CameraPlatform', () async { - final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - await cameraController.initialize(); - cameraController.value = cameraController.value.copyWith( - deviceOrientation: DeviceOrientation.portraitUp, - ); + test( + 'getSupportedVideoStabilizationModes() returns off when device supports no mode', + () async { + // arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); - await cameraController.pausePreview(); + await cameraController.initialize(); + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer((_) async => []); - verify( - CameraPlatform.instance.pausePreview(cameraController.cameraId), - ).called(1); - expect(cameraController.value.isPreviewPaused, equals(true)); - expect( - cameraController.value.previewPauseOrientation, - DeviceOrientation.portraitUp, - ); - }); + // act + final Iterable modes = await cameraController + .getSupportedVideoStabilizationModes(); + + // assert + expect(modes, [VideoStabilizationMode.off]); + }, + ); test( - 'pausePreview() does not call $CameraPlatform when already paused', + 'getSupportedVideoStabilizationModes() returns off when device supports only off', () async { - final CameraController cameraController = CameraController( + // arrange + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -1511,24 +1509,30 @@ void main() { ), ResolutionPreset.max, ); + await cameraController.initialize(); - cameraController.value = cameraController.value.copyWith( - isPreviewPaused: true, + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [VideoStabilizationMode.off], ); - await cameraController.pausePreview(); + // act + final Iterable modes = await cameraController + .getSupportedVideoStabilizationModes(); - verifyNever( - CameraPlatform.instance.pausePreview(cameraController.cameraId), - ); - expect(cameraController.value.isPreviewPaused, equals(true)); + // assert + expect(modes, [VideoStabilizationMode.off]); }, ); test( - 'pausePreview() sets previewPauseOrientation according to locked orientation', + 'getSupportedVideoStabilizationModes() returns off and level1', () async { - final CameraController cameraController = CameraController( + // arrange + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -1536,32 +1540,36 @@ void main() { ), ResolutionPreset.max, ); + await cameraController.initialize(); - cameraController.value = cameraController.value.copyWith( - isPreviewPaused: false, - deviceOrientation: DeviceOrientation.portraitUp, - lockedCaptureOrientation: Optional.of( - DeviceOrientation.landscapeRight, + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, ), + ).thenAnswer( + (_) async => [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + ], ); - await cameraController.pausePreview(); + // act + final Iterable modes = await cameraController + .getSupportedVideoStabilizationModes(); - expect( - cameraController.value.deviceOrientation, - equals(DeviceOrientation.portraitUp), - ); - expect( - cameraController.value.previewPauseOrientation, - equals(DeviceOrientation.landscapeRight), - ); + // assert + expect(modes, [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + ]); }, ); test( - 'pausePreview() throws $CameraException on $PlatformException', + 'getSupportedVideoStabilizationModes() returns off, level1 and level2', () async { - final CameraController cameraController = CameraController( + // arrange + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -1569,31 +1577,36 @@ void main() { ), ResolutionPreset.max, ); + await cameraController.initialize(); when( - CameraPlatform.instance.pausePreview(cameraController.cameraId), - ).thenThrow( - PlatformException( - code: 'TEST_ERROR', - message: 'This is a test error message', + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, ), + ).thenAnswer( + (_) async => [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + VideoStabilizationMode.level2, + ], ); - expect( - cameraController.pausePreview(), - throwsA( - isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ), - ), - ); + // act + final Iterable modes = await cameraController + .getSupportedVideoStabilizationModes(); + + // assert + expect(modes, [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + VideoStabilizationMode.level2, + ]); }, ); - test('resumePreview() calls $CameraPlatform', () async { - final CameraController cameraController = CameraController( + test('getSupportedVideoStabilizationModes() returns all modes', () async { + // arrange + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -1601,23 +1614,38 @@ void main() { ), ResolutionPreset.max, ); + await cameraController.initialize(); - cameraController.value = cameraController.value.copyWith( - isPreviewPaused: true, + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + VideoStabilizationMode.level2, + VideoStabilizationMode.level3, + ], ); - await cameraController.resumePreview(); - - verify( - CameraPlatform.instance.resumePreview(cameraController.cameraId), - ).called(1); - expect(cameraController.value.isPreviewPaused, equals(false)); + // act + final Iterable modes = await cameraController + .getSupportedVideoStabilizationModes(); + + // assert + expect(modes, [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + VideoStabilizationMode.level2, + VideoStabilizationMode.level3, + ]); }); test( - 'resumePreview() does not call $CameraPlatform when not paused', + 'setVideoStabilizationMode() throws $CameraException on $PlatformException', () async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -1626,36 +1654,23 @@ void main() { ResolutionPreset.max, ); await cameraController.initialize(); - cameraController.value = cameraController.value.copyWith( - isPreviewPaused: false, - ); - - await cameraController.resumePreview(); - - verifyNever( - CameraPlatform.instance.resumePreview(cameraController.cameraId), - ); - expect(cameraController.value.isPreviewPaused, equals(false)); - }, - ); - test( - 'resumePreview() throws $CameraException on $PlatformException', - () async { - final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, ), - ResolutionPreset.max, - ); - await cameraController.initialize(); - cameraController.value = cameraController.value.copyWith( - isPreviewPaused: true, + ).thenAnswer( + (_) async => [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + ], ); + when( - CameraPlatform.instance.resumePreview(cameraController.cameraId), + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), ).thenThrow( PlatformException( code: 'TEST_ERROR', @@ -1664,7 +1679,9 @@ void main() { ); expect( - cameraController.resumePreview(), + cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level1, + ), throwsA( isA().having( (CameraException error) => error.description, @@ -1676,48 +1693,15 @@ void main() { }, ); - test('lockCaptureOrientation() calls $CameraPlatform', () async { - final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - await cameraController.initialize(); - - await cameraController.lockCaptureOrientation(); - expect( - cameraController.value.lockedCaptureOrientation, - equals(DeviceOrientation.portraitUp), - ); - await cameraController.lockCaptureOrientation( - DeviceOrientation.landscapeRight, - ); - expect( - cameraController.value.lockedCaptureOrientation, - equals(DeviceOrientation.landscapeRight), - ); - - verify( - CameraPlatform.instance.lockCaptureOrientation( - cameraController.cameraId, - DeviceOrientation.portraitUp, - ), - ).called(1); - verify( - CameraPlatform.instance.lockCaptureOrientation( - cameraController.cameraId, - DeviceOrientation.landscapeRight, - ), - ).called(1); - }); - test( - 'lockCaptureOrientation() throws $CameraException on $PlatformException', + 'setVideoStabilizationMode() with fallback never calls CameraPlatform.instance.setVideoStabilizationMode when no supported mode is available', () async { - final CameraController cameraController = CameraController( + //// The purpose of this test is to ensure that when no video stabilization mode is supported, + //// then all calls to setVideoStabilizationMode with fallback will not result in any + //// call to CameraPlatform.instance.setVideoStabilizationMode. + + //arrange + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -1726,56 +1710,62 @@ void main() { ResolutionPreset.max, ); await cameraController.initialize(); + when( - CameraPlatform.instance.lockCaptureOrientation( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer((_) async => []); + + clearInteractions(CameraPlatform.instance); + + // act + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.off, + ); + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level1, + ); + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level2, + ); + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level3, + ); + + // assert + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( cameraController.cameraId, - DeviceOrientation.portraitUp, + VideoStabilizationMode.off, ), - ).thenThrow( - PlatformException( - code: 'TEST_ERROR', - message: 'This is a test error message', + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, ), ); - - expect( - cameraController.lockCaptureOrientation(DeviceOrientation.portraitUp), - throwsA( - isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ), + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, ), ); }, ); - test('unlockCaptureOrientation() calls $CameraPlatform', () async { - final CameraController cameraController = CameraController( - const CameraDescription( - name: 'cam', - lensDirection: CameraLensDirection.back, - sensorOrientation: 90, - ), - ResolutionPreset.max, - ); - await cameraController.initialize(); - - await cameraController.unlockCaptureOrientation(); - expect(cameraController.value.lockedCaptureOrientation, equals(null)); - - verify( - CameraPlatform.instance.unlockCaptureOrientation( - cameraController.cameraId, - ), - ).called(1); - }); - test( - 'unlockCaptureOrientation() throws $CameraException on $PlatformException', + 'setVideoStabilizationMode() with fallback calls CameraPlatform.instance.setVideoStabilizationMode with VideoStabilizationMode.off when off is requested and only off is available', () async { - final CameraController cameraController = CameraController( + //arrange + final cameraController = CameraController( const CameraDescription( name: 'cam', lensDirection: CameraLensDirection.back, @@ -1784,38 +1774,2190 @@ void main() { ResolutionPreset.max, ); await cameraController.initialize(); + when( - CameraPlatform.instance.unlockCaptureOrientation( + CameraPlatform.instance.setVideoStabilizationMode( cameraController.cameraId, + VideoStabilizationMode.off, ), - ).thenThrow( - PlatformException( - code: 'TEST_ERROR', - message: 'This is a test error message', + ).thenAnswer((_) => Future(() {})); + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, ), + ).thenAnswer( + (_) async => [VideoStabilizationMode.off], ); - expect( - cameraController.unlockCaptureOrientation(), - throwsA( - isA().having( - (CameraException error) => error.description, - 'TEST_ERROR', - 'This is a test error message', - ), - ), + clearInteractions(CameraPlatform.instance); + + // act + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.off, ); - }, - ); - }); -} -class MockCameraPlatform extends Mock - with MockPlatformInterfaceMixin - implements CameraPlatform { - @override - Future initializeCamera( - int? cameraId, { + // assert + verify( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ).called(1); + + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() with fallback calls CameraPlatform.instance.setVideoStabilizationMode with VideoStabilizationMode.off when level1 is requested and only off is available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ).thenAnswer((_) => Future(() {})); + + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [VideoStabilizationMode.off], + ); + + clearInteractions(CameraPlatform.instance); + + // act + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level1, + ); + + // assert + verify( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ).called(1); + + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() with fallback calls CameraPlatform.instance.setVideoStabilizationMode with VideoStabilizationMode.off when level2 is requested and only off is available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ).thenAnswer((_) => Future(() {})); + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [VideoStabilizationMode.off], + ); + + clearInteractions(CameraPlatform.instance); + + // act + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level2, + ); + + // assert + verify( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ).called(1); + + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() with fallback calls CameraPlatform.instance.setVideoStabilizationMode with VideoStabilizationMode.off when level3 is requested and only off is available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ).thenAnswer((_) => Future(() {})); + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [VideoStabilizationMode.off], + ); + + clearInteractions(CameraPlatform.instance); + + // act + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level3, + ); + + // assert + verify( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ).called(1); + + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() with fallback calls CameraPlatform.instance.setVideoStabilizationMode with VideoStabilizationMode.off when off is requested and only off and level1 are available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ).thenAnswer((_) => Future(() {})); + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + ], + ); + + clearInteractions(CameraPlatform.instance); + + // act + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.off, + ); + + // assert + verify( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ).called(1); + + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() with fallback calls CameraPlatform.instance.setVideoStabilizationMode with VideoStabilizationMode.level1 when level1 is requested and only off and level1 are available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ).thenAnswer((_) => Future(() {})); + + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + ], + ); + clearInteractions(CameraPlatform.instance); + + // act + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level1, + ); + + // assert + verify( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ).called(1); + + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() with fallback calls CameraPlatform.instance.setVideoStabilizationMode with VideoStabilizationMode.level1 when level2 is requested and only off and level1 are available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ).thenAnswer((_) => Future(() {})); + + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + ], + ); + + clearInteractions(CameraPlatform.instance); + + // act + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level2, + ); + + // assert + verify( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ).called(1); + + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() with fallback calls CameraPlatform.instance.setVideoStabilizationMode with VideoStabilizationMode.level1 when level3 is requested and only off and level1 are available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ).thenAnswer((_) => Future(() {})); + + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + ], + ); + + clearInteractions(CameraPlatform.instance); + + // act + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level3, + ); + + // assert + verify( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ).called(1); + + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() with fallback calls CameraPlatform.instance.setVideoStabilizationMode with VideoStabilizationMode.off when off is requested and all levels are available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ).thenAnswer((_) => Future(() {})); + + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + VideoStabilizationMode.level2, + VideoStabilizationMode.level3, + ], + ); + + clearInteractions(CameraPlatform.instance); + + // act + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.off, + ); + + // assert + verify( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ).called(1); + + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() with fallback calls CameraPlatform.instance.setVideoStabilizationMode with VideoStabilizationMode.level1 when level1 is requested and all levels are available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ).thenAnswer((_) => Future(() {})); + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + VideoStabilizationMode.level2, + VideoStabilizationMode.level3, + ], + ); + + clearInteractions(CameraPlatform.instance); + + // act + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level1, + ); + + // assert + verify( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ).called(1); + + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() with fallback calls CameraPlatform.instance.setVideoStabilizationMode with VideoStabilizationMode.level2 when level2 is requested and all levels are available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ).thenAnswer((_) => Future(() {})); + + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + VideoStabilizationMode.level2, + VideoStabilizationMode.level3, + ], + ); + + clearInteractions(CameraPlatform.instance); + + // act + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level2, + ); + + // assert + verify( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ).called(1); + + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() with fallback calls CameraPlatform.instance.setVideoStabilizationMode with VideoStabilizationMode.level3 when level3 is requested and all levels available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ).thenAnswer((_) => Future(() {})); + + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + VideoStabilizationMode.level2, + VideoStabilizationMode.level3, + ], + ); + + clearInteractions(CameraPlatform.instance); + + // act + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level3, + ); + + // assert + verify( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ).called(1); + + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() without fallback calls never calls CameraPlatform.instance.setVideoStabilizationMode when off is requested no supported mode is available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer((_) async => []); + + clearInteractions(CameraPlatform.instance); + + // act + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.off, + allowFallback: false, + ); + + // assert + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() without fallback throws $ArgumentError when level1 is requested and no supported mode is available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer((_) async => []); + + clearInteractions(CameraPlatform.instance); + + // assert + expect( + // act + cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level1, + allowFallback: false, + ), + throwsA( + isA().having( + (ArgumentError error) => error.name, + 'name', + 'mode', + ), + ), + ); + + // assert + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() without fallback throws $ArgumentError when level2 is requested and no supported mode is available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer((_) async => []); + + clearInteractions(CameraPlatform.instance); + + // assert + expect( + // act + cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level2, + allowFallback: false, + ), + throwsA( + isA().having( + (ArgumentError error) => error.name, + 'name', + 'mode', + ), + ), + ); + + // assert + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() without fallback throws $ArgumentError when level3 is requested and no supported mode is available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer((_) async => []); + + clearInteractions(CameraPlatform.instance); + + // assert + expect( + // act + cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level3, + allowFallback: false, + ), + throwsA( + isA().having( + (ArgumentError error) => error.name, + 'name', + 'mode', + ), + ), + ); + + // assert + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() without fallback calls CameraPlatform.instance.setVideoStabilizationMode with VideoStabilizationMode.off when off is requested and only off is available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ).thenAnswer((_) => Future(() {})); + + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [VideoStabilizationMode.off], + ); + + clearInteractions(CameraPlatform.instance); + + // act + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.off, + allowFallback: false, + ); + + // assert + verify( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ).called(1); + + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() without fallback throws $ArgumentError when level1 is requested and only off is available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [VideoStabilizationMode.off], + ); + + clearInteractions(CameraPlatform.instance); + + // assert + expect( + // act + cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level1, + allowFallback: false, + ), + throwsA( + isA().having( + (ArgumentError error) => error.name, + 'name', + 'mode', + ), + ), + ); + + // assert + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() without fallback throws $ArgumentError when level2 is requested and only off is available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [VideoStabilizationMode.off], + ); + + clearInteractions(CameraPlatform.instance); + + // assert + expect( + // act + cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level2, + allowFallback: false, + ), + throwsA( + isA().having( + (ArgumentError error) => error.name, + 'name', + 'mode', + ), + ), + ); + + // assert + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() without fallback throws $ArgumentError when level3 is requested and only off is available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [VideoStabilizationMode.off], + ); + + clearInteractions(CameraPlatform.instance); + + // assert + expect( + // act + cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level3, + allowFallback: false, + ), + throwsA( + isA().having( + (ArgumentError error) => error.name, + 'name', + 'mode', + ), + ), + ); + + // assert + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() without fallback calls CameraPlatform.instance.setVideoStabilizationMode with VideoStabilizationMode.off when off is requested and all level1 is available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ).thenAnswer((_) => Future(() {})); + + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + ], + ); + + clearInteractions(CameraPlatform.instance); + + // act + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.off, + allowFallback: false, + ); + + // assert + verify( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ).called(1); + + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() without fallback calls CameraPlatform.instance.setVideoStabilizationMode with VideoStabilizationMode.level1 when level1 is requested and level1 is available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ).thenAnswer((_) => Future(() {})); + + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + ], + ); + + clearInteractions(CameraPlatform.instance); + + // act + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level1, + allowFallback: false, + ); + + // assert + verify( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ).called(1); + + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() without fallback throws $ArgumentError when level2 is requested and only off and level1 are available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ).thenAnswer((_) => Future(() {})); + + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + ], + ); + + clearInteractions(CameraPlatform.instance); + + // assert + expect( + // act + cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level2, + allowFallback: false, + ), + throwsA( + isA().having( + (ArgumentError error) => error.name, + 'name', + 'mode', + ), + ), + ); + + // assert + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() without fallback calls CameraPlatform.instance.setVideoStabilizationMode with VideoStabilizationMode.off when off is requested and all levels are available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ).thenAnswer((_) => Future(() {})); + + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + VideoStabilizationMode.level2, + VideoStabilizationMode.level3, + ], + ); + + clearInteractions(CameraPlatform.instance); + + // act + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.off, + allowFallback: false, + ); + + // assert + verify( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ).called(1); + + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() without fallback calls CameraPlatform.instance.setVideoStabilizationMode with VideoStabilizationMode.level1 when level1 is requested and all levels are available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ).thenAnswer((_) => Future(() {})); + + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + VideoStabilizationMode.level2, + VideoStabilizationMode.level3, + ], + ); + + clearInteractions(CameraPlatform.instance); + + // act + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level1, + allowFallback: false, + ); + + // assert + verify( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ).called(1); + + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() without fallback calls CameraPlatform.instance.setVideoStabilizationMode with VideoStabilizationMode.level2 when level2 is requested and all levels are available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ).thenAnswer((_) => Future(() {})); + + when( + CameraPlatform.instance.setVideoStabilizationMode( + mockInitializeCamera, + VideoStabilizationMode.level2, + ), + ).thenAnswer((_) => Future(() {})); + + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + VideoStabilizationMode.level2, + VideoStabilizationMode.level3, + ], + ); + + clearInteractions(CameraPlatform.instance); + + // act + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level2, + allowFallback: false, + ); + + // assert + verify( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ).called(1); + + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode() without fallback calls CameraPlatform.instance.setVideoStabilizationMode with VideoStabilizationMode.level3 when level3 is requested and all levels are available', + () async { + //arrange + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + when( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ).thenAnswer((_) => Future(() {})); + + when( + CameraPlatform.instance.getSupportedVideoStabilizationModes( + mockInitializeCamera, + ), + ).thenAnswer( + (_) async => [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + VideoStabilizationMode.level2, + VideoStabilizationMode.level3, + ], + ); + + clearInteractions(CameraPlatform.instance); + + // act + await cameraController.setVideoStabilizationMode( + VideoStabilizationMode.level3, + allowFallback: false, + ); + + // assert + verify( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level3, + ), + ).called(1); + + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.off, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level1, + ), + ); + verifyNever( + CameraPlatform.instance.setVideoStabilizationMode( + cameraController.cameraId, + VideoStabilizationMode.level2, + ), + ); + }, + ); + + test('pausePreview() calls $CameraPlatform', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + cameraController.value = cameraController.value.copyWith( + deviceOrientation: DeviceOrientation.portraitUp, + ); + + await cameraController.pausePreview(); + + verify( + CameraPlatform.instance.pausePreview(cameraController.cameraId), + ).called(1); + expect(cameraController.value.isPreviewPaused, equals(true)); + expect( + cameraController.value.previewPauseOrientation, + DeviceOrientation.portraitUp, + ); + }); + + test( + 'pausePreview() does not call $CameraPlatform when already paused', + () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + cameraController.value = cameraController.value.copyWith( + isPreviewPaused: true, + ); + + await cameraController.pausePreview(); + + verifyNever( + CameraPlatform.instance.pausePreview(cameraController.cameraId), + ); + expect(cameraController.value.isPreviewPaused, equals(true)); + }, + ); + + test( + 'pausePreview() sets previewPauseOrientation according to locked orientation', + () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + cameraController.value = cameraController.value.copyWith( + isPreviewPaused: false, + deviceOrientation: DeviceOrientation.portraitUp, + lockedCaptureOrientation: const Optional.of( + DeviceOrientation.landscapeRight, + ), + ); + + await cameraController.pausePreview(); + + expect( + cameraController.value.deviceOrientation, + equals(DeviceOrientation.portraitUp), + ); + expect( + cameraController.value.previewPauseOrientation, + equals(DeviceOrientation.landscapeRight), + ); + }, + ); + + test( + 'pausePreview() throws $CameraException on $PlatformException', + () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + when( + CameraPlatform.instance.pausePreview(cameraController.cameraId), + ).thenThrow( + PlatformException( + code: 'TEST_ERROR', + message: 'This is a test error message', + ), + ); + + expect( + cameraController.pausePreview(), + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', + ), + ), + ); + }, + ); + + test('resumePreview() calls $CameraPlatform', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + cameraController.value = cameraController.value.copyWith( + isPreviewPaused: true, + ); + + await cameraController.resumePreview(); + + verify( + CameraPlatform.instance.resumePreview(cameraController.cameraId), + ).called(1); + expect(cameraController.value.isPreviewPaused, equals(false)); + }); + + test( + 'resumePreview() does not call $CameraPlatform when not paused', + () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + cameraController.value = cameraController.value.copyWith( + isPreviewPaused: false, + ); + + await cameraController.resumePreview(); + + verifyNever( + CameraPlatform.instance.resumePreview(cameraController.cameraId), + ); + expect(cameraController.value.isPreviewPaused, equals(false)); + }, + ); + + test( + 'resumePreview() throws $CameraException on $PlatformException', + () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + cameraController.value = cameraController.value.copyWith( + isPreviewPaused: true, + ); + when( + CameraPlatform.instance.resumePreview(cameraController.cameraId), + ).thenThrow( + PlatformException( + code: 'TEST_ERROR', + message: 'This is a test error message', + ), + ); + + expect( + cameraController.resumePreview(), + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', + ), + ), + ); + }, + ); + + test('lockCaptureOrientation() calls $CameraPlatform', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + await cameraController.lockCaptureOrientation(); + expect( + cameraController.value.lockedCaptureOrientation, + equals(DeviceOrientation.portraitUp), + ); + await cameraController.lockCaptureOrientation( + DeviceOrientation.landscapeRight, + ); + expect( + cameraController.value.lockedCaptureOrientation, + equals(DeviceOrientation.landscapeRight), + ); + + verify( + CameraPlatform.instance.lockCaptureOrientation( + cameraController.cameraId, + DeviceOrientation.portraitUp, + ), + ).called(1); + verify( + CameraPlatform.instance.lockCaptureOrientation( + cameraController.cameraId, + DeviceOrientation.landscapeRight, + ), + ).called(1); + }); + + test( + 'lockCaptureOrientation() throws $CameraException on $PlatformException', + () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + when( + CameraPlatform.instance.lockCaptureOrientation( + cameraController.cameraId, + DeviceOrientation.portraitUp, + ), + ).thenThrow( + PlatformException( + code: 'TEST_ERROR', + message: 'This is a test error message', + ), + ); + + expect( + cameraController.lockCaptureOrientation(DeviceOrientation.portraitUp), + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', + ), + ), + ); + }, + ); + + test('unlockCaptureOrientation() calls $CameraPlatform', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + await cameraController.unlockCaptureOrientation(); + expect(cameraController.value.lockedCaptureOrientation, equals(null)); + + verify( + CameraPlatform.instance.unlockCaptureOrientation( + cameraController.cameraId, + ), + ).called(1); + }); + + test( + 'unlockCaptureOrientation() throws $CameraException on $PlatformException', + () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + when( + CameraPlatform.instance.unlockCaptureOrientation( + cameraController.cameraId, + ), + ).thenThrow( + PlatformException( + code: 'TEST_ERROR', + message: 'This is a test error message', + ), + ); + + expect( + cameraController.unlockCaptureOrientation(), + throwsA( + isA().having( + (CameraException error) => error.description, + 'TEST_ERROR', + 'This is a test error message', + ), + ), + ); + }, + ); + + test('error from onCameraError is received', () async { + final cameraController = CameraController( + const CameraDescription( + name: 'cam', + lensDirection: CameraLensDirection.back, + sensorOrientation: 90, + ), + ResolutionPreset.max, + ); + await cameraController.initialize(); + + expect(cameraController.value.hasError, isTrue); + expect( + cameraController.value.errorDescription, + mockOnCameraErrorEvent.description, + ); + }); + }); +} + +class MockCameraPlatform extends Mock + with MockPlatformInterfaceMixin + implements CameraPlatform { + @override + Future initializeCamera( + int? cameraId, { ImageFormatGroup? imageFormatGroup = ImageFormatGroup.unknown, }) async => super.noSuchMethod( Invocation.method( @@ -1987,6 +4129,29 @@ class MockCameraPlatform extends Mock returnValue: Future.value(1.0), ) as Future; + + @override + Future> getSupportedVideoStabilizationModes( + int cameraId, + ) { + return super.noSuchMethod( + Invocation.method(#getSupportedVideoStabilizationModes, [ + cameraId, + ]), + returnValue: Future>.value( + [], + ), + ) + as Future>; + } + + @override + Future setVideoStabilizationMode( + int cameraId, + VideoStabilizationMode mode, + ) async => super.noSuchMethod( + Invocation.method(#setVideoStabilizationMode, [cameraId, mode]), + ); } class MockCameraDescription extends CameraDescription { diff --git a/packages/camera/camera/test/camera_value_test.dart b/packages/camera/camera/test/camera_value_test.dart index 205ed6ce884c..3d52cf809583 100644 --- a/packages/camera/camera/test/camera_value_test.dart +++ b/packages/camera/camera/test/camera_value_test.dart @@ -11,7 +11,7 @@ import 'camera_preview_test.dart'; void main() { group('camera_value', () { test('Can be created', () { - const CameraValue cameraValue = CameraValue( + const cameraValue = CameraValue( isInitialized: false, previewSize: Size(10, 10), isRecordingPaused: false, @@ -28,6 +28,7 @@ void main() { focusPointSupported: true, previewPauseOrientation: DeviceOrientation.portraitUp, description: FakeController.fakeDescription, + videoStabilizationMode: VideoStabilizationMode.level2, ); expect(cameraValue, isA()); @@ -49,10 +50,11 @@ void main() { expect(cameraValue.recordingOrientation, DeviceOrientation.portraitUp); expect(cameraValue.isPreviewPaused, false); expect(cameraValue.previewPauseOrientation, DeviceOrientation.portraitUp); + expect(cameraValue.videoStabilizationMode, VideoStabilizationMode.level2); }); test('Can be created as uninitialized', () { - const CameraValue cameraValue = CameraValue.uninitialized( + const cameraValue = CameraValue.uninitialized( FakeController.fakeDescription, ); @@ -73,12 +75,11 @@ void main() { expect(cameraValue.recordingOrientation, null); expect(cameraValue.isPreviewPaused, isFalse); expect(cameraValue.previewPauseOrientation, null); + expect(cameraValue.videoStabilizationMode, VideoStabilizationMode.off); }); test('Can be copied with isInitialized', () { - const CameraValue cv = CameraValue.uninitialized( - FakeController.fakeDescription, - ); + const cv = CameraValue.uninitialized(FakeController.fakeDescription); final CameraValue cameraValue = cv.copyWith(isInitialized: true); expect(cameraValue, isA()); @@ -98,12 +99,11 @@ void main() { expect(cameraValue.recordingOrientation, null); expect(cameraValue.isPreviewPaused, isFalse); expect(cameraValue.previewPauseOrientation, null); + expect(cameraValue.videoStabilizationMode, VideoStabilizationMode.off); }); test('Has aspectRatio after setting size', () { - const CameraValue cv = CameraValue.uninitialized( - FakeController.fakeDescription, - ); + const cv = CameraValue.uninitialized(FakeController.fakeDescription); final CameraValue cameraValue = cv.copyWith( isInitialized: true, previewSize: const Size(20, 10), @@ -113,9 +113,7 @@ void main() { }); test('hasError is true after setting errorDescription', () { - const CameraValue cv = CameraValue.uninitialized( - FakeController.fakeDescription, - ); + const cv = CameraValue.uninitialized(FakeController.fakeDescription); final CameraValue cameraValue = cv.copyWith(errorDescription: 'error'); expect(cameraValue.hasError, isTrue); @@ -123,9 +121,7 @@ void main() { }); test('Recording paused is false when not recording', () { - const CameraValue cv = CameraValue.uninitialized( - FakeController.fakeDescription, - ); + const cv = CameraValue.uninitialized(FakeController.fakeDescription); final CameraValue cameraValue = cv.copyWith( isInitialized: true, isRecordingVideo: false, @@ -136,7 +132,7 @@ void main() { }); test('toString() works as expected', () { - const CameraValue cameraValue = CameraValue( + const cameraValue = CameraValue( isInitialized: false, previewSize: Size(10, 10), isRecordingPaused: false, @@ -154,6 +150,7 @@ void main() { isPreviewPaused: true, previewPauseOrientation: DeviceOrientation.portraitUp, description: FakeController.fakeDescription, + videoStabilizationMode: VideoStabilizationMode.level3, ); expect( @@ -168,6 +165,7 @@ void main() { 'recordingOrientation: DeviceOrientation.portraitUp, ' 'isPreviewPaused: true, ' 'previewPausedOrientation: DeviceOrientation.portraitUp, ' + 'videoStabilizationMode: VideoStabilizationMode.level3, ' // CameraDescription.toString is defined in the platform interface // package, so don't assert a specific value for it, only that // whatever it returns is inserted as expected. diff --git a/packages/camera/camera_android/CHANGELOG.md b/packages/camera/camera_android/CHANGELOG.md index 6ebd56630b06..0bf9721e6ab9 100644 --- a/packages/camera/camera_android/CHANGELOG.md +++ b/packages/camera/camera_android/CHANGELOG.md @@ -1,3 +1,11 @@ +## 0.10.10+16 + +* Updates build files from Groovy to Kotlin. + +## 0.10.10+15 + +* Updates example to demonstrate correct exception handling for async return statements, ensuring exceptions thrown during return within try blocks are properly caught as per [dart-lang/sdk#44395](https://github.com/dart-lang/sdk/issues/44395). + ## 0.10.10+14 * Bumps com.android.tools.build:gradle from 8.12.1 to 8.13.1. diff --git a/packages/camera/camera_android/android/build.gradle b/packages/camera/camera_android/android/build.gradle deleted file mode 100644 index ec6b93c24ed2..000000000000 --- a/packages/camera/camera_android/android/build.gradle +++ /dev/null @@ -1,74 +0,0 @@ -group = 'io.flutter.plugins.camera' -version = '1.0-SNAPSHOT' -def args = ["-Xlint:deprecation","-Xlint:unchecked"] - -buildscript { - repositories { - google() - mavenCentral() - } - - dependencies { - classpath 'com.android.tools.build:gradle:8.13.1' - } -} - -rootProject.allprojects { - repositories { - google() - mavenCentral() - } -} - -project.getTasks().withType(JavaCompile){ - options.compilerArgs.addAll(args) -} - -apply plugin: 'com.android.library' - -android { -buildFeatures { - buildConfig = true - } - namespace = "io.flutter.plugins.camera" - compileSdk = flutter.compileSdkVersion - - defaultConfig { - minSdkVersion 24 - testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - } - lintOptions { - checkAllWarnings = true - warningsAsErrors = true - disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency', 'NewerVersionAvailable' - } - compileOptions { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 - } - - testOptions { - unitTests.includeAndroidResources = true - unitTests.returnDefaultValues = true - unitTests.all { - // The org.gradle.jvmargs property that may be set in gradle.properties does not impact - // the Java heap size when running the Android unit tests. The following property here - // sets the heap size to a size large enough to run the robolectric tests across - // multiple SDK levels. - jvmArgs "-Xmx4G" - testLogging { - events "passed", "skipped", "failed", "standardOut", "standardError" - outputs.upToDateWhen {false} - showStandardStreams = true - } - } - } -} - -dependencies { - implementation("androidx.annotation:annotation:1.9.1") - testImplementation("junit:junit:4.13.2") - testImplementation("org.mockito:mockito-core:5.20.0") - testImplementation("androidx.test:core:1.7.0") - testImplementation("org.robolectric:robolectric:4.16") -} diff --git a/packages/camera/camera_android/android/build.gradle.kts b/packages/camera/camera_android/android/build.gradle.kts new file mode 100644 index 000000000000..22a4dfb62033 --- /dev/null +++ b/packages/camera/camera_android/android/build.gradle.kts @@ -0,0 +1,80 @@ +group = "io.flutter.plugins.camera" +version = "1.0-SNAPSHOT" + +buildscript { + repositories { + google() + mavenCentral() + } + + dependencies { + classpath("com.android.tools.build:gradle:8.13.1") + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +tasks.withType().configureEach { + options.compilerArgs.add("-Xlint:deprecation") + options.compilerArgs.add("-Xlint:unchecked") +} + +plugins { + id("com.android.library") +} + +android { + buildFeatures { + buildConfig = true + } + namespace = "io.flutter.plugins.camera" + compileSdk = flutter.compileSdkVersion + + defaultConfig { + minSdk = 24 + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + lint { + checkAllWarnings = true + warningsAsErrors = true + disable.addAll(setOf("AndroidGradlePluginVersion", "InvalidPackage", "GradleDependency", "NewerVersionAvailable")) + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + testOptions { + unitTests { + isIncludeAndroidResources = true + isReturnDefaultValues = true + all { + it.outputs.upToDateWhen { false } + it.testLogging { + events("passed", "skipped", "failed", "standardOut", "standardError") + showStandardStreams = true + } + // The org.gradle.jvmargs property that may be set in gradle.properties does not impact + // the Java heap size when running the Android unit tests. The following property here + // sets the heap size to a size large enough to run the robolectric tests across + // multiple SDK levels. + it.jvmArgs("-Xmx4G") + } + } + } +} + +dependencies { + implementation("androidx.annotation:annotation:1.9.1") + testImplementation("junit:junit:4.13.2") + testImplementation("org.mockito:mockito-core:5.23.0") + testImplementation("androidx.test:core:1.7.0") + testImplementation("org.robolectric:robolectric:4.16") +} diff --git a/packages/camera/camera_android/android/settings.gradle b/packages/camera/camera_android/android/settings.gradle deleted file mode 100644 index 94a1bae9d6cd..000000000000 --- a/packages/camera/camera_android/android/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'camera_android' diff --git a/packages/camera/camera_android/android/settings.gradle.kts b/packages/camera/camera_android/android/settings.gradle.kts new file mode 100644 index 000000000000..0006625daf4e --- /dev/null +++ b/packages/camera/camera_android/android/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "camera_android" diff --git a/packages/camera/camera_android/example/android/app/gradle/wrapper/gradle-wrapper.properties b/packages/camera/camera_android/example/android/app/gradle/wrapper/gradle-wrapper.properties index 0c68fbc1dadd..4a647536b632 100644 --- a/packages/camera/camera_android/example/android/app/gradle/wrapper/gradle-wrapper.properties +++ b/packages/camera/camera_android/example/android/app/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.0-all.zip +networkTimeout=10000 zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists - diff --git a/packages/camera/camera_android/example/android/settings.gradle b/packages/camera/camera_android/example/android/settings.gradle index 96fce46479f8..b542cca3f52e 100644 --- a/packages/camera/camera_android/example/android/settings.gradle +++ b/packages/camera/camera_android/example/android/settings.gradle @@ -19,8 +19,8 @@ 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.11.0" apply false - id "org.jetbrains.kotlin.android" version "2.2.0" apply false + id "com.android.application" version "8.11.1" apply false + id "org.jetbrains.kotlin.android" version "2.2.20" apply false id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1" } diff --git a/packages/camera/camera_android/example/integration_test/camera_test.dart b/packages/camera/camera_android/example/integration_test/camera_test.dart index 53fad65a878f..01621c32682d 100644 --- a/packages/camera/camera_android/example/integration_test/camera_test.dart +++ b/packages/camera/camera_android/example/integration_test/camera_test.dart @@ -28,15 +28,14 @@ void main() { await testDir.delete(recursive: true); }); - final Map presetExpectedSizes = - { - ResolutionPreset.low: const Size(240, 320), - ResolutionPreset.medium: const Size(480, 720), - ResolutionPreset.high: const Size(720, 1280), - ResolutionPreset.veryHigh: const Size(1080, 1920), - ResolutionPreset.ultraHigh: const Size(2160, 3840), - // Don't bother checking for max here since it could be anything. - }; + final presetExpectedSizes = { + ResolutionPreset.low: const Size(240, 320), + ResolutionPreset.medium: const Size(480, 720), + ResolutionPreset.high: const Size(720, 1280), + ResolutionPreset.veryHigh: const Size(1080, 1920), + ResolutionPreset.ultraHigh: const Size(2160, 3840), + // Don't bother checking for max here since it could be anything. + }; /// Verify that [actual] has dimensions that are at least as large as /// [expectedSize]. Allows for a mismatch in portrait vs landscape. Returns @@ -63,10 +62,8 @@ void main() { final XFile file = await controller.stopVideoRecording(); // Load video metadata - final File videoFile = File(file.path); - final VideoPlayerController videoController = VideoPlayerController.file( - videoFile, - ); + final videoFile = File(file.path); + final videoController = VideoPlayerController.file(videoFile); await videoController.initialize(); final Size video = videoController.value.size; @@ -86,11 +83,11 @@ void main() { if (cameras.isEmpty) { return; } - for (final CameraDescription cameraDescription in cameras) { - bool previousPresetExactlySupported = true; + for (final cameraDescription in cameras) { + var previousPresetExactlySupported = true; for (final MapEntry preset in presetExpectedSizes.entries) { - final CameraController controller = CameraController( + final controller = CameraController( cameraDescription, mediaSettings: MediaSettings(resolutionPreset: preset.key), ); @@ -120,13 +117,13 @@ void main() { return; } - final CameraController controller = CameraController(cameras[0]); + final controller = CameraController(cameras[0]); await controller.initialize(); await controller.prepareForVideoRecording(); int startPause; - int timePaused = 0; + var timePaused = 0; await controller.startVideoRecording(); final int recordingStart = DateTime.now().millisecondsSinceEpoch; @@ -152,10 +149,8 @@ void main() { final int recordingTime = DateTime.now().millisecondsSinceEpoch - recordingStart; - final File videoFile = File(file.path); - final VideoPlayerController videoController = VideoPlayerController.file( - videoFile, - ); + final videoFile = File(file.path); + final videoController = VideoPlayerController.file(videoFile); await videoController.initialize(); final int duration = videoController.value.duration.inMilliseconds; await videoController.dispose(); @@ -170,7 +165,7 @@ void main() { return; } - final CameraController controller = CameraController(cameras[0]); + final controller = CameraController(cameras[0]); await controller.initialize(); await controller.prepareForVideoRecording(); @@ -179,7 +174,7 @@ void main() { // SDK < 26 will throw a platform error when trying to switch and keep the same camera // we accept either outcome here, while the native unit tests check the outcome based on the current Android SDK - bool failed = false; + var failed = false; try { await controller.setDescription(cameras[1]); } catch (err) { @@ -207,7 +202,7 @@ void main() { return; } - final CameraController controller = CameraController(cameras[0]); + final controller = CameraController(cameras[0]); await controller.initialize(); await controller.setDescription(cameras[1]); @@ -222,10 +217,10 @@ void main() { return; } - final CameraController controller = CameraController(cameras[0]); + final controller = CameraController(cameras[0]); await controller.initialize(); - bool isDetecting = false; + var isDetecting = false; await controller.startImageStream((CameraImageData image) { if (isDetecting) { @@ -252,10 +247,10 @@ void main() { return; } - final CameraController controller = CameraController(cameras[0]); + final controller = CameraController(cameras[0]); await controller.initialize(); - bool isDetecting = false; + var isDetecting = false; await controller.startVideoRecording( streamCallback: (CameraImageData image) { @@ -315,10 +310,10 @@ void main() { testWidgets('Control FPS', (WidgetTester tester) async { final CameraDescription cameraDescription = await getCamera(); - final List lengths = []; + final lengths = []; - for (final int fps in [10, 30]) { - final CameraController controller = CameraController( + for (final fps in [10, 30]) { + final controller = CameraController( cameraDescription, mediaSettings: MediaSettings( resolutionPreset: ResolutionPreset.medium, @@ -333,14 +328,14 @@ void main() { final XFile file = await controller.stopVideoRecording(); // Load video size - final File videoFile = File(file.path); + final videoFile = File(file.path); lengths.add(await videoFile.length()); await controller.dispose(); } - for (int n = 0; n < lengths.length - 1; n++) { + for (var n = 0; n < lengths.length - 1; n++) { expect(lengths[n], greaterThan(0)); } }); @@ -348,10 +343,10 @@ void main() { testWidgets('Control video bitrate', (WidgetTester tester) async { final CameraDescription cameraDescription = await getCamera(); - const int kiloBits = 1000; - final List lengths = []; - for (final int videoBitrate in [200 * kiloBits, 2000 * kiloBits]) { - final CameraController controller = CameraController( + const kiloBits = 1000; + final lengths = []; + for (final videoBitrate in [200 * kiloBits, 2000 * kiloBits]) { + final controller = CameraController( cameraDescription, mediaSettings: MediaSettings( resolutionPreset: ResolutionPreset.medium, @@ -366,27 +361,27 @@ void main() { final XFile file = await controller.stopVideoRecording(); // Load video size - final File videoFile = File(file.path); + final videoFile = File(file.path); lengths.add(await videoFile.length()); await controller.dispose(); } - for (int n = 0; n < lengths.length - 1; n++) { + for (var n = 0; n < lengths.length - 1; n++) { expect(lengths[n], greaterThan(0)); } }); testWidgets('Control audio bitrate', (WidgetTester tester) async { - final List lengths = []; + final lengths = []; final CameraDescription cameraDescription = await getCamera(); - const int kiloBits = 1000; + const kiloBits = 1000; - for (final int audioBitrate in [32 * kiloBits, 256 * kiloBits]) { - final CameraController controller = CameraController( + for (final audioBitrate in [32 * kiloBits, 256 * kiloBits]) { + final controller = CameraController( cameraDescription, mediaSettings: MediaSettings( //region Use lowest video settings for minimize video impact on bitrate @@ -406,7 +401,7 @@ void main() { final XFile file = await controller.stopVideoRecording(); // Load video metadata - final File videoFile = File(file.path); + final videoFile = File(file.path); final int length = await videoFile.length(); @@ -415,7 +410,7 @@ void main() { await controller.dispose(); } - for (int n = 0; n < lengths.length - 1; n++) { + for (var n = 0; n < lengths.length - 1; n++) { expect(lengths[n], greaterThan(0)); } }); diff --git a/packages/camera/camera_android/example/lib/camera_controller.dart b/packages/camera/camera_android/example/lib/camera_controller.dart index 2ca1a1f00a8f..33cafe13e447 100644 --- a/packages/camera/camera_android/example/lib/camera_controller.dart +++ b/packages/camera/camera_android/example/lib/camera_controller.dart @@ -206,8 +206,7 @@ class CameraController extends ValueNotifier { Future initialize() => _initializeWithDescription(description); Future _initializeWithDescription(CameraDescription description) async { - final Completer initializeCompleter = - Completer(); + final initializeCompleter = Completer(); _deviceOrientationSubscription = CameraPlatform.instance .onDeviceOrientationChanged() @@ -479,13 +478,7 @@ class Optional extends IterableBase { const Optional.absent() : _value = null; /// Constructs an Optional of the given [value]. - /// - /// Throws [ArgumentError] if [value] is null. - Optional.of(T value) : _value = value { - // TODO(cbracken): Delete and make this ctor const once mixed-mode - // execution is no longer around. - ArgumentError.checkNotNull(value); - } + const Optional.of(T value) : _value = value; /// Constructs an Optional of the given [value]. /// diff --git a/packages/camera/camera_android/example/lib/camera_preview.dart b/packages/camera/camera_android/example/lib/camera_preview.dart index 22fb2cc4d77f..0a768b340639 100644 --- a/packages/camera/camera_android/example/lib/camera_preview.dart +++ b/packages/camera/camera_android/example/lib/camera_preview.dart @@ -62,7 +62,7 @@ class CameraPreview extends StatelessWidget { } int _getQuarterTurns() { - final Map turns = { + final turns = { DeviceOrientation.portraitUp: 0, DeviceOrientation.landscapeRight: 1, DeviceOrientation.portraitDown: 2, diff --git a/packages/camera/camera_android/example/lib/main.dart b/packages/camera/camera_android/example/lib/main.dart index 10b0b9c4e928..b669f6ac6831 100644 --- a/packages/camera/camera_android/example/lib/main.dart +++ b/packages/camera/camera_android/example/lib/main.dart @@ -577,7 +577,7 @@ class _CameraExampleHomeState extends State /// Display a row of toggle to select the camera (or a message if no camera is available). Widget _cameraTogglesRowWidget() { - final List toggles = []; + final toggles = []; void onChanged(CameraDescription? description) { if (description == null) { @@ -628,7 +628,7 @@ class _CameraExampleHomeState extends State final CameraController cameraController = controller!; - final Point point = Point( + final point = Point( details.localPosition.dx / constraints.maxWidth, details.localPosition.dy / constraints.maxHeight, ); @@ -647,7 +647,7 @@ class _CameraExampleHomeState extends State Future _initializeCameraController( CameraDescription cameraDescription, ) async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( cameraDescription, mediaSettings: MediaSettings( resolutionPreset: kIsWeb @@ -908,7 +908,7 @@ class _CameraExampleHomeState extends State } try { - return cameraController.stopVideoRecording(); + return await cameraController.stopVideoRecording(); } on CameraException catch (e) { _showCameraException(e); return null; @@ -1005,7 +1005,7 @@ class _CameraExampleHomeState extends State return; } - final VideoPlayerController vController = kIsWeb + final vController = kIsWeb ? VideoPlayerController.networkUrl(Uri.parse(videoFile!.path)) : VideoPlayerController.file(File(videoFile!.path)); diff --git a/packages/camera/camera_android/example/test_driver/integration_test.dart b/packages/camera/camera_android/example/test_driver/integration_test.dart index d512473309e9..ef65f091ca07 100644 --- a/packages/camera/camera_android/example/test_driver/integration_test.dart +++ b/packages/camera/camera_android/example/test_driver/integration_test.dart @@ -17,8 +17,7 @@ Future main() async { print('This test must be run on a POSIX host. Skipping...'); exit(0); } - final bool adbExists = - Process.runSync('which', ['adb']).exitCode == 0; + final adbExists = Process.runSync('which', ['adb']).exitCode == 0; if (!adbExists) { print(r'This test needs ADB to exist on the $PATH. Skipping...'); exit(0); @@ -61,6 +60,6 @@ Future main() async { 'android.permission.RECORD_AUDIO', ]); - final Map result = jsonDecode(data) as Map; + final result = jsonDecode(data) as Map; exit(result['result'] == 'true' ? 0 : 1); } diff --git a/packages/camera/camera_android/lib/src/android_camera.dart b/packages/camera/camera_android/lib/src/android_camera.dart index 8d6da994cac6..9f7d580f2364 100644 --- a/packages/camera/camera_android/lib/src/android_camera.dart +++ b/packages/camera/camera_android/lib/src/android_camera.dart @@ -120,7 +120,7 @@ class AndroidCamera extends CameraPlatform { () => HostCameraMessageHandler(cameraId, cameraEventStreamController), ); - final Completer completer = Completer(); + final completer = Completer(); unawaited( onCameraInitialized(cameraId).first.then((CameraInitializedEvent value) { @@ -270,7 +270,7 @@ class AndroidCamera extends CameraPlatform { } void _startStreamListener() { - const EventChannel cameraEventChannel = EventChannel( + const cameraEventChannel = EventChannel( 'plugins.flutter.io/camera_android/imageStream', ); _platformImageStreamSubscription = cameraEventChannel diff --git a/packages/camera/camera_android/pubspec.yaml b/packages/camera/camera_android/pubspec.yaml index f5dbe700d346..34ffc900e502 100644 --- a/packages/camera/camera_android/pubspec.yaml +++ b/packages/camera/camera_android/pubspec.yaml @@ -3,7 +3,7 @@ description: Android implementation of the camera plugin. repository: https://github.com/flutter/packages/tree/main/packages/camera/camera_android issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+camera%22 -version: 0.10.10+14 +version: 0.10.10+16 environment: sdk: ^3.9.0 diff --git a/packages/camera/camera_android/test/android_camera_test.dart b/packages/camera/camera_android/test/android_camera_test.dart index 78b2744be347..8321001ed954 100644 --- a/packages/camera/camera_android/test/android_camera_test.dart +++ b/packages/camera/camera_android/test/android_camera_test.dart @@ -57,7 +57,7 @@ void main() { test('Should send creation data and receive back a camera id', () async { // Arrange - final AndroidCamera camera = AndroidCamera(hostApi: mockCameraApi); + final camera = AndroidCamera(hostApi: mockCameraApi); when( mockCameraApi.create( 'Test', @@ -89,7 +89,7 @@ void main() { 'Should send creation data and receive back a camera id using createCameraWithSettings', () async { // Arrange - final AndroidCamera camera = AndroidCamera(hostApi: mockCameraApi); + final camera = AndroidCamera(hostApi: mockCameraApi); when( mockCameraApi.create( 'Test', @@ -130,7 +130,7 @@ void main() { 'Should throw CameraException when create throws a PlatformException', () { // Arrange - final AndroidCamera camera = AndroidCamera(hostApi: mockCameraApi); + final camera = AndroidCamera(hostApi: mockCameraApi); when( mockCameraApi.create( 'Test', @@ -181,7 +181,7 @@ void main() { 'Should throw CameraException when initialize throws a PlatformException', () { // Arrange - final AndroidCamera camera = AndroidCamera(hostApi: mockCameraApi); + final camera = AndroidCamera(hostApi: mockCameraApi); when( mockCameraApi.initialize(PlatformImageFormatGroup.yuv420), ).thenThrow( @@ -213,7 +213,7 @@ void main() { test('Should send initialization data', () async { // Arrange - final AndroidCamera camera = AndroidCamera(hostApi: mockCameraApi); + final camera = AndroidCamera(hostApi: mockCameraApi); when( mockCameraApi.create( 'Test', @@ -260,7 +260,7 @@ void main() { test('Should send a disposal call on dispose', () async { // Arrange - final AndroidCamera camera = AndroidCamera(hostApi: mockCameraApi); + final camera = AndroidCamera(hostApi: mockCameraApi); when( mockCameraApi.create( 'Test', @@ -338,12 +338,11 @@ void main() { // Act final Stream eventStream = camera .onCameraInitialized(cameraId); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); // Emit test events - final PlatformSize previewSize = PlatformSize(width: 3840, height: 2160); - final CameraInitializedEvent event = CameraInitializedEvent( + final previewSize = PlatformSize(width: 3840, height: 2160); + final event = CameraInitializedEvent( cameraId, previewSize.width, previewSize.height, @@ -374,12 +373,11 @@ void main() { final Stream eventStream = camera.onCameraClosing( cameraId, ); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); // Emit test events - final CameraClosingEvent event = CameraClosingEvent(cameraId); - for (int i = 0; i < 3; i++) { + final event = CameraClosingEvent(cameraId); + for (var i = 0; i < 3; i++) { camera.hostCameraHandlers[cameraId]!.closed(); } @@ -397,15 +395,11 @@ void main() { final Stream errorStream = camera.onCameraError( cameraId, ); - final StreamQueue streamQueue = - StreamQueue(errorStream); + final streamQueue = StreamQueue(errorStream); // Emit test events - final CameraErrorEvent event = CameraErrorEvent( - cameraId, - 'Error Description', - ); - for (int i = 0; i < 3; i++) { + final event = CameraErrorEvent(cameraId, 'Error Description'); + for (var i = 0; i < 3; i++) { camera.hostCameraHandlers[cameraId]!.error('Error Description'); } @@ -422,14 +416,13 @@ void main() { // Act final Stream eventStream = camera .onDeviceOrientationChanged(); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue( + eventStream, + ); // Emit test events - const DeviceOrientationChangedEvent event = DeviceOrientationChangedEvent( - DeviceOrientation.portraitUp, - ); - for (int i = 0; i < 3; i++) { + const event = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); + for (var i = 0; i < 3; i++) { camera.hostHandler.deviceOrientationChanged( PlatformDeviceOrientation.portraitUp, ); @@ -480,19 +473,18 @@ void main() { 'Should fetch CameraDescription instances for available cameras', () async { // Arrange - final List returnData = - [ - PlatformCameraDescription( - name: 'Test 1', - lensDirection: PlatformCameraLensDirection.front, - sensorOrientation: 1, - ), - PlatformCameraDescription( - name: 'Test 2', - lensDirection: PlatformCameraLensDirection.back, - sensorOrientation: 2, - ), - ]; + final returnData = [ + PlatformCameraDescription( + name: 'Test 1', + lensDirection: PlatformCameraLensDirection.front, + sensorOrientation: 1, + ), + PlatformCameraDescription( + name: 'Test 2', + lensDirection: PlatformCameraLensDirection.back, + sensorOrientation: 2, + ), + ]; when( mockCameraApi.getAvailableCameras(), ).thenAnswer((_) async => returnData); @@ -502,10 +494,10 @@ void main() { // Assert expect(cameras.length, returnData.length); - for (int i = 0; i < returnData.length; i++) { + for (var i = 0; i < returnData.length; i++) { final PlatformCameraDescription platformCameraDescription = returnData[i]; - final CameraDescription cameraDescription = CameraDescription( + final cameraDescription = CameraDescription( name: platformCameraDescription.name, lensDirection: cameraLensDirectionFromPlatform( platformCameraDescription.lensDirection, @@ -620,7 +612,7 @@ void main() { test('Should set the description while recording', () async { // Arrange - const CameraDescription camera2Description = CameraDescription( + const camera2Description = CameraDescription( name: 'Test2', lensDirection: CameraLensDirection.front, sensorOrientation: 0, diff --git a/packages/camera/camera_android_camerax/AUTHORS b/packages/camera/camera_android_camerax/AUTHORS index 557dff97933b..af2ff4eb39f6 100644 --- a/packages/camera/camera_android_camerax/AUTHORS +++ b/packages/camera/camera_android_camerax/AUTHORS @@ -4,3 +4,4 @@ # Name/Organization Google Inc. +Rui Craveiro diff --git a/packages/camera/camera_android_camerax/CHANGELOG.md b/packages/camera/camera_android_camerax/CHANGELOG.md index 99bad7103eab..c6a099c854d7 100644 --- a/packages/camera/camera_android_camerax/CHANGELOG.md +++ b/packages/camera/camera_android_camerax/CHANGELOG.md @@ -1,3 +1,67 @@ +## 0.7.1+2 + +* Fixes dartdoc comments that accidentally used HTML. + +## 0.7.1+1 + +* Updates build files from Groovy to Kotlin. + +## 0.7.1 + +* Removes outdated restrictions against concurrent camera use cases. + +## 0.7.0+1 + +* Updates example to demonstrate correct exception handling for async return statements, ensuring exceptions thrown during return within try blocks are properly caught as per [dart-lang/sdk#44395](https://github.com/dart-lang/sdk/issues/44395). + +## 0.7.0 + +* Adds video stabilization. + +## 0.6.30 + +* Bump camerax_version from 1.5.2 to 1.5.3. + +## 0.6.29 + +* Modifies lens direction logic to request the value from CameraX directly versus manual detection. + +## 0.6.28 + +* Adds more descriptive error to camera error stream when image capture fails. + +## 0.6.27 + +* Changes `availableCameras` to get the camera name from `Camera2CameraInfo.getCameraId`. + +## 0.6.26+3 + +* Bumps kotlin_version to 2.3.0. + +## 0.6.26+2 + +* Updates pigeon generation to prevent crash when objects call to Dart after a hot restart. + +## 0.6.26+1 + +* Bumps camerax_version from 1.5.1 to 1.5.2. + +## 0.6.26 + +* Removes internal native library Dart proxy. + +## 0.6.25+1 + +* Bumps kotlin_version to 2.2.21. + +## 0.6.25 + +* Adds support for `MediaSettings.fps` for camera preview, image streaming, and video recording. + +## 0.6.24+4 + +* Allows for video recording without audio when permission RECORD_AUDIO is denied. + ## 0.6.24+3 * Bumps com.android.tools.build:gradle from 8.12.1 to 8.13.1. diff --git a/packages/camera/camera_android_camerax/README.md b/packages/camera/camera_android_camerax/README.md index 5cf163e19a35..b3abec3cd6de 100644 --- a/packages/camera/camera_android_camerax/README.md +++ b/packages/camera/camera_android_camerax/README.md @@ -18,22 +18,6 @@ should add it to your `pubspec.yaml` as usual. ## Limitations -### Concurrent preview display, video recording, image capture, and image streaming - -The CameraX plugin only supports the concurrent camera use cases supported by Camerax; see -[their documentation][6] for more information. To avoid the usage of unsupported concurrent -use cases, the plugin behaves according to the following: - -* If the preview is paused (via `pausePreview`), concurrent video recording and image capture - and/or image streaming (via `startVideoCapturing(cameraId, VideoCaptureOptions(streamCallback:...))`) - is supported. -* If the preview is not paused - * **and** the camera device is at least supported hardware [`LIMITED`][8], then concurrent - image capture and video recording is supported. - * **and** the camera device is at least supported hardware [`LEVEL_3`][7], then concurrent - video recording and image streaming is supported, but concurrent video recording, image - streaming, and image capture is not supported. - ### 240p resolution configuration for video recording 240p resolution configuration for video recording is unsupported by CameraX, and thus, diff --git a/packages/camera/camera_android_camerax/android/build.gradle b/packages/camera/camera_android_camerax/android/build.gradle deleted file mode 100644 index ca0ad4ef162e..000000000000 --- a/packages/camera/camera_android_camerax/android/build.gradle +++ /dev/null @@ -1,86 +0,0 @@ -group = 'io.flutter.plugins.camerax' -version = '1.0' - -buildscript { - ext.kotlin_version = '2.2.10' - repositories { - google() - mavenCentral() - } - - dependencies { - classpath 'com.android.tools.build:gradle:8.13.1' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } -} - -rootProject.allprojects { - repositories { - google() - mavenCentral() - } -} - -apply plugin: 'com.android.library' -apply plugin: 'kotlin-android' - -android { - namespace = "io.flutter.plugins.camerax" - // CameraX dependencies require compilation against version 33 or later. - compileSdk = flutter.compileSdkVersion - - compileOptions { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 - } - - kotlinOptions { - // This must match the Java version provided in compileOptions. - jvmTarget = JavaVersion.VERSION_17.toString() - } - - defaultConfig { - // CameraX APIs require API 23 or later. - minSdk = 23 - testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - } - - testOptions { - unitTests.includeAndroidResources = true - unitTests.returnDefaultValues = true - unitTests.all { - // The org.gradle.jvmargs property that may be set in gradle.properties does not impact - // the Java heap size when running the Android unit tests. The following property here - // sets the heap size to a size large enough to run the robolectric tests across - // multiple SDK levels. - jvmArgs "-Xmx1G" - testLogging { - events "passed", "skipped", "failed", "standardOut", "standardError" - outputs.upToDateWhen {false} - showStandardStreams = true - } - } - } - - lint { - checkAllWarnings = true - warningsAsErrors = true - disable 'AndroidGradlePluginVersion', 'GradleDependency', 'InvalidPackage', 'NewerVersionAvailable' - baseline = file("lint-baseline.xml") - } -} - -dependencies { - // CameraX core library using the camera2 implementation must use same version number. - def camerax_version = "1.5.1" - implementation("androidx.camera:camera-core:${camerax_version}") - implementation("androidx.camera:camera-camera2:${camerax_version}") - implementation("androidx.camera:camera-lifecycle:${camerax_version}") - implementation("androidx.camera:camera-video:${camerax_version}") - implementation("com.google.guava:guava:33.5.0-android") - testImplementation("junit:junit:4.13.2") - testImplementation("org.mockito:mockito-core:5.20.0") - testImplementation("org.mockito:mockito-inline:5.2.0") - testImplementation("androidx.test:core:1.7.0") - testImplementation("org.robolectric:robolectric:4.16") -} diff --git a/packages/camera/camera_android_camerax/android/build.gradle.kts b/packages/camera/camera_android_camerax/android/build.gradle.kts new file mode 100644 index 000000000000..13da169a49e9 --- /dev/null +++ b/packages/camera/camera_android_camerax/android/build.gradle.kts @@ -0,0 +1,93 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + +group = "io.flutter.plugins.camerax" +version = "1.0" + +buildscript { + val kotlinVersion = "2.3.0" + repositories { + google() + mavenCentral() + } + + dependencies { + classpath("com.android.tools.build:gradle:8.13.1") + classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion") + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +plugins { + id("com.android.library") + id("kotlin-android") +} + +kotlin { + compilerOptions { + jvmTarget = JvmTarget.fromTarget(JavaVersion.VERSION_17.toString()) + } +} + +android { + namespace = "io.flutter.plugins.camerax" + // CameraX dependencies require compilation against version 33 or later. + compileSdk = flutter.compileSdkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + defaultConfig { + // CameraX APIs require API 23 or later. + minSdk = 23 + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + testOptions { + unitTests { + isIncludeAndroidResources = true + isReturnDefaultValues = true + all { + it.outputs.upToDateWhen { false } + it.testLogging { + events("passed", "skipped", "failed", "standardOut", "standardError") + showStandardStreams = true + } + // The org.gradle.jvmargs property that may be set in gradle.properties does not impact + // the Java heap size when running the Android unit tests. The following property here + // sets the heap size to a size large enough to run the robolectric tests across + // multiple SDK levels. + it.jvmArgs("-Xmx1G") + } + } + } + + lint { + checkAllWarnings = true + warningsAsErrors = true + disable.addAll(setOf("AndroidGradlePluginVersion", "GradleDependency", "InvalidPackage", "NewerVersionAvailable")) + baseline = file("lint-baseline.xml") + } +} + +dependencies { + // CameraX core library using the camera2 implementation must use same version number. + val cameraxVersion = "1.5.3" + implementation("androidx.camera:camera-core:${cameraxVersion}") + implementation("androidx.camera:camera-camera2:${cameraxVersion}") + implementation("androidx.camera:camera-lifecycle:${cameraxVersion}") + implementation("androidx.camera:camera-video:${cameraxVersion}") + implementation("com.google.guava:guava:33.5.0-android") + testImplementation("junit:junit:4.13.2") + testImplementation("org.mockito:mockito-core:5.23.0") + testImplementation("org.mockito:mockito-inline:5.2.0") + testImplementation("androidx.test:core:1.7.0") + testImplementation("org.robolectric:robolectric:4.16") +} diff --git a/packages/camera/camera_android_camerax/android/settings.gradle b/packages/camera/camera_android_camerax/android/settings.gradle deleted file mode 100644 index 613f994165a0..000000000000 --- a/packages/camera/camera_android_camerax/android/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'camera_android_camerax' diff --git a/packages/camera/camera_android_camerax/android/settings.gradle.kts b/packages/camera/camera_android_camerax/android/settings.gradle.kts new file mode 100644 index 000000000000..9d4ef5bade6a --- /dev/null +++ b/packages/camera/camera_android_camerax/android/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "camera_android_camerax" 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 index e3311862f3bb..d19d8bcf6bc9 100644 --- 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 @@ -28,4 +28,10 @@ public CameraCharacteristics.Key infoSupportedHardwareLevel() { public CameraCharacteristics.Key sensorOrientation() { return CameraCharacteristics.SENSOR_ORIENTATION; } + + @NonNull + @Override + public CameraCharacteristics.Key controlAvailableVideoStabilizationModes() { + return CameraCharacteristics.CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES; + } } 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 index 0e3e51b7756d..509cdc7ba357 100644 --- 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 @@ -5,7 +5,10 @@ package io.flutter.plugins.camerax; import androidx.annotation.NonNull; +import androidx.annotation.OptIn; import androidx.camera.core.CameraInfo; +import androidx.camera.core.CameraSelector; +import androidx.camera.core.ExperimentalLensFacing; import androidx.camera.core.ExposureState; /** @@ -23,6 +26,22 @@ public long sensorRotationDegrees(CameraInfo pigeonInstance) { return pigeonInstance.getSensorRotationDegrees(); } + @Override + @OptIn(markerClass = ExperimentalLensFacing.class) + public LensFacing lensFacing(CameraInfo pigeonInstance) { + int lensFacing = pigeonInstance.getLensFacing(); + switch (lensFacing) { + case CameraSelector.LENS_FACING_FRONT: + return LensFacing.FRONT; + case CameraSelector.LENS_FACING_BACK: + return LensFacing.BACK; + case CameraSelector.LENS_FACING_EXTERNAL: + return LensFacing.EXTERNAL; + default: + return LensFacing.UNKNOWN; + } + } + @NonNull @Override public ExposureState exposureState(CameraInfo pigeonInstance) { 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 index 22e63b54ce8e..2bdf4371dfed 100644 --- 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 @@ -1,7 +1,7 @@ // Copyright 2013 The Flutter Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// Autogenerated from Pigeon (v26.1.0), do not edit directly. +// Autogenerated from Pigeon (v26.1.7), do not edit directly. // See also: https://pub.dev/packages/pigeon @file:Suppress("UNCHECKED_CAST", "ArrayInDataClass") @@ -213,7 +213,7 @@ class CameraXLibraryPigeonInstanceManager( } /** Retrieves the instance associated with identifier, if present, otherwise `null`. */ - fun getInstance(identifier: Long): T? { + fun getInstance(identifier: Long): T? { logWarningIfFinalizationListenerHasStopped() val instance = weakInstances[identifier] as IdentityWeakReference? return instance?.get() @@ -2140,6 +2140,14 @@ abstract class PigeonApiObserver(open val pigeonRegistrar: CameraXLibraryPigeonP Result.failure( CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + CameraXError( + "missing-instance-error", + "Callback to `Observer.onChanged` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -2173,6 +2181,9 @@ abstract class PigeonApiCameraInfo( */ abstract fun sensorRotationDegrees(pigeon_instance: androidx.camera.core.CameraInfo): Long + /** Returns the lens direction of this camera. */ + abstract fun lensFacing(pigeon_instance: androidx.camera.core.CameraInfo): LensFacing + /** Returns a ExposureState. */ abstract fun exposureState( pigeon_instance: androidx.camera.core.CameraInfo @@ -2255,23 +2266,26 @@ abstract class PigeonApiCameraInfo( val pigeon_identifierArg = pigeonRegistrar.instanceManager.addHostCreatedInstance(pigeon_instanceArg) val sensorRotationDegreesArg = sensorRotationDegrees(pigeon_instanceArg) + val lensFacingArg = lensFacing(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)) + channel.send( + listOf(pigeon_identifierArg, sensorRotationDegreesArg, lensFacingArg, 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(CameraXLibraryPigeonUtils.createConnectionError(channelName))) + } } - } else { - callback(Result.failure(CameraXLibraryPigeonUtils.createConnectionError(channelName))) - } - } } } } @@ -2925,6 +2939,14 @@ abstract class PigeonApiSystemServicesManager( Result.failure( CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + CameraXError( + "missing-instance-error", + "Callback to `SystemServicesManager.onCameraError` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3165,6 +3187,14 @@ abstract class PigeonApiDeviceOrientationManager( Result.failure( CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + CameraXError( + "missing-instance-error", + "Callback to `DeviceOrientationManager.onDeviceOrientationChanged` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3193,7 +3223,8 @@ abstract class PigeonApiDeviceOrientationManager( abstract class PigeonApiPreview(open val pigeonRegistrar: CameraXLibraryPigeonProxyApiRegistrar) { abstract fun pigeon_defaultConstructor( resolutionSelector: androidx.camera.core.resolutionselector.ResolutionSelector?, - targetRotation: Long? + targetRotation: Long?, + targetFpsRange: android.util.Range<*>? ): androidx.camera.core.Preview abstract fun resolutionSelector( @@ -3249,10 +3280,12 @@ abstract class PigeonApiPreview(open val pigeonRegistrar: CameraXLibraryPigeonPr val resolutionSelectorArg = args[1] as androidx.camera.core.resolutionselector.ResolutionSelector? val targetRotationArg = args[2] as Long? + val targetFpsRangeArg = args[3] as android.util.Range<*>? val wrapped: List = try { api.pigeonRegistrar.instanceManager.addDartCreatedInstance( - api.pigeon_defaultConstructor(resolutionSelectorArg, targetRotationArg), + api.pigeon_defaultConstructor( + resolutionSelectorArg, targetRotationArg, targetFpsRangeArg), pigeon_identifierArg) listOf(null) } catch (exception: Throwable) { @@ -3433,7 +3466,8 @@ abstract class PigeonApiVideoCapture( ) { /** Create a `VideoCapture` associated with the given `VideoOutput`. */ abstract fun withOutput( - videoOutput: androidx.camera.video.VideoOutput + videoOutput: androidx.camera.video.VideoOutput, + targetFpsRange: android.util.Range<*>? ): androidx.camera.video.VideoCapture<*> /** Gets the VideoOutput associated with this VideoCapture. */ @@ -3462,10 +3496,11 @@ abstract class PigeonApiVideoCapture( val args = message as List val pigeon_identifierArg = args[0] as Long val videoOutputArg = args[1] as androidx.camera.video.VideoOutput + val targetFpsRangeArg = args[2] as android.util.Range<*>? val wrapped: List = try { api.pigeonRegistrar.instanceManager.addDartCreatedInstance( - api.withOutput(videoOutputArg), pigeon_identifierArg) + api.withOutput(videoOutputArg, targetFpsRangeArg), pigeon_identifierArg) listOf(null) } catch (exception: Throwable) { CameraXLibraryPigeonUtils.wrapError(exception) @@ -3877,6 +3912,14 @@ abstract class PigeonApiVideoRecordEventListener( Result.failure( CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + CameraXError( + "missing-instance-error", + "Callback to `VideoRecordEventListener.onEvent` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -4220,6 +4263,7 @@ abstract class PigeonApiImageCapture( /** Captures a new still image for in memory access. */ abstract fun takePicture( pigeon_instance: androidx.camera.core.ImageCapture, + systemServicesManager: SystemServicesManager, callback: (Result) -> Unit ) @@ -4294,7 +4338,9 @@ abstract class PigeonApiImageCapture( 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 systemServicesManagerArg = args[1] as SystemServicesManager + api.takePicture(pigeon_instanceArg, systemServicesManagerArg) { result: Result + -> val error = result.exceptionOrNull() if (error != null) { reply.reply(CameraXLibraryPigeonUtils.wrapError(error)) @@ -5058,6 +5104,7 @@ abstract class PigeonApiImageAnalysis( abstract fun pigeon_defaultConstructor( resolutionSelector: androidx.camera.core.resolutionselector.ResolutionSelector?, targetRotation: Long?, + targetFpsRange: android.util.Range<*>?, outputImageFormat: Long? ): androidx.camera.core.ImageAnalysis @@ -5097,12 +5144,16 @@ abstract class PigeonApiImageAnalysis( val resolutionSelectorArg = args[1] as androidx.camera.core.resolutionselector.ResolutionSelector? val targetRotationArg = args[2] as Long? - val outputImageFormatArg = args[3] as Long? + val targetFpsRangeArg = args[3] as android.util.Range<*>? + val outputImageFormatArg = args[4] as Long? val wrapped: List = try { api.pigeonRegistrar.instanceManager.addDartCreatedInstance( api.pigeon_defaultConstructor( - resolutionSelectorArg, targetRotationArg, outputImageFormatArg), + resolutionSelectorArg, + targetRotationArg, + targetFpsRangeArg, + outputImageFormatArg), pigeon_identifierArg) listOf(null) } catch (exception: Throwable) { @@ -5302,6 +5353,14 @@ abstract class PigeonApiAnalyzer(open val pigeonRegistrar: CameraXLibraryPigeonP Result.failure( CameraXError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + CameraXError( + "missing-instance-error", + "Callback to `Analyzer.analyze` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -6669,6 +6728,15 @@ abstract class PigeonApiCaptureRequest( */ abstract fun controlAELock(): android.hardware.camera2.CaptureRequest.Key<*> + /** + * Whether video stabilization is active. + * + * Value is int. + * + * This key is available on all devices. + */ + abstract fun controlVideoStabilizationMode(): android.hardware.camera2.CaptureRequest.Key<*> + companion object { @Suppress("LocalVariableName") fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, api: PigeonApiCaptureRequest?) { @@ -6697,6 +6765,30 @@ abstract class PigeonApiCaptureRequest( channel.setMessageHandler(null) } } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.CaptureRequest.controlVideoStabilizationMode", + 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.controlVideoStabilizationMode(), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + CameraXLibraryPigeonUtils.wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } } } @@ -7167,6 +7259,17 @@ abstract class PigeonApiCameraCharacteristics( */ abstract fun sensorOrientation(): android.hardware.camera2.CameraCharacteristics.Key<*> + /** + * List of video stabilization modes for android.control.videoStabilizationMode that are supported + * by this camera device. + * + * Value is `ControlAvailableVideoStabilizationMode`. + * + * This key is available on all devices. + */ + abstract fun controlAvailableVideoStabilizationModes(): + android.hardware.camera2.CameraCharacteristics.Key<*> + companion object { @Suppress("LocalVariableName") fun setUpMessageHandlers( @@ -7222,6 +7325,30 @@ abstract class PigeonApiCameraCharacteristics( channel.setMessageHandler(null) } } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.camera_android_camerax.CameraCharacteristics.controlAvailableVideoStabilizationModes", + 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.controlAvailableVideoStabilizationModes(), pigeon_identifierArg) + listOf(null) + } catch (exception: Throwable) { + CameraXLibraryPigeonUtils.wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } } } 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 index d8b814142b89..424dea8e91a1 100644 --- 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 @@ -42,8 +42,15 @@ public CaptureRequestOptions pigeon_defaultConstructor( continue; } - builder.setCaptureRequestOption( - (CaptureRequest.Key) option.getKey(), option.getValue()); + // Because Pigeon isn't down-casting from Dart num to Java Int, + // it needs to be done below. + var key = option.getKey(); + var value = option.getValue(); + if (CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE == key) { + value = ((Long) value).intValue(); + } + + builder.setCaptureRequestOption((CaptureRequest.Key) key, value); } return builder.build(); 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 index 5887e63f6f27..cf737815d017 100644 --- 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 @@ -22,4 +22,10 @@ class CaptureRequestProxyApi extends PigeonApiCaptureRequest { public CaptureRequest.Key controlAELock() { return CaptureRequest.CONTROL_AE_LOCK; } + + @NonNull + @Override + public CaptureRequest.Key controlVideoStabilizationMode() { + return CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE; + } } 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 index e914ad81e529..17ad7b001cd4 100644 --- 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 @@ -4,8 +4,13 @@ package io.flutter.plugins.camerax; +import android.hardware.camera2.CaptureRequest; +import android.util.Range; import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import androidx.annotation.OptIn; +import androidx.camera.camera2.interop.Camera2Interop; +import androidx.camera.camera2.interop.ExperimentalCamera2Interop; import androidx.camera.core.ImageAnalysis; import androidx.camera.core.resolutionselector.ResolutionSelector; import androidx.core.content.ContextCompat; @@ -18,11 +23,15 @@ class ImageAnalysisProxyApi extends PigeonApiImageAnalysis { static final long CLEAR_FINALIZED_WEAK_REFERENCES_INTERVAL_FOR_IMAGE_ANALYSIS = 1000; + // Range is defined as Range in pigeon. + @SuppressWarnings("unchecked") + @OptIn(markerClass = ExperimentalCamera2Interop.class) @NonNull @Override public ImageAnalysis pigeon_defaultConstructor( @Nullable ResolutionSelector resolutionSelector, @Nullable Long targetRotation, + @Nullable Range targetFpsRange, @Nullable Long outputImageFormat) { final ImageAnalysis.Builder builder = new ImageAnalysis.Builder(); if (resolutionSelector != null) { @@ -36,6 +45,12 @@ public ImageAnalysis pigeon_defaultConstructor( builder.setOutputImageFormat(outputImageFormat.intValue()); } + if (targetFpsRange != null) { + Camera2Interop.Extender extender = new Camera2Interop.Extender<>(builder); + extender.setCaptureRequestOption( + CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, (Range) targetFpsRange); + } + return builder.build(); } 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 index 1f7afd3e7140..7bf6bd508a25 100644 --- 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 @@ -85,6 +85,7 @@ public void setFlashMode( @Override public void takePicture( @NonNull ImageCapture pigeonInstance, + @NonNull SystemServicesManager systemServicesManager, @NonNull Function1, Unit> callback) { final File outputDir = getPigeonRegistrar().getContext().getCacheDir(); File temporaryCaptureFile; @@ -98,7 +99,7 @@ public void takePicture( final ImageCapture.OutputFileOptions outputFileOptions = createImageCaptureOutputFileOptions(temporaryCaptureFile); final ImageCapture.OnImageSavedCallback onImageSavedCallback = - createOnImageSavedCallback(temporaryCaptureFile, callback); + createOnImageSavedCallback(temporaryCaptureFile, systemServicesManager, callback); pigeonInstance.takePicture( outputFileOptions, Executors.newSingleThreadExecutor(), onImageSavedCallback); @@ -121,7 +122,9 @@ ImageCapture.OutputFileOptions createImageCaptureOutputFileOptions(@NonNull File @NonNull ImageCapture.OnImageSavedCallback createOnImageSavedCallback( - @NonNull File file, @NonNull Function1, Unit> callback) { + @NonNull File file, + @NonNull SystemServicesManager systemServicesManager, + @NonNull Function1, Unit> callback) { return new ImageCapture.OnImageSavedCallback() { @Override public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) { @@ -130,8 +133,32 @@ public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResul @Override public void onError(@NonNull ImageCaptureException exception) { + systemServicesManager.onCameraError( + getImageCaptureExceptionDescription(exception.getImageCaptureError())); ResultCompat.failure(exception, callback); } }; } + + /** + * Returns an error description for each {@link ImageCaptureException} error code. + * + *

See + * https://developer.android.com/reference/androidx/camera/core/ImageCaptureException#getImageCaptureError() + * for details on each error type. + */ + String getImageCaptureExceptionDescription(int imageCaptureErrorCode) { + switch (imageCaptureErrorCode) { + case ImageCapture.ERROR_FILE_IO: + return "An error occurred while attempting to save the captured image to a file."; + case ImageCapture.ERROR_CAPTURE_FAILED: + return "The camera framework failed to fulfill the image capture request."; + case ImageCapture.ERROR_CAMERA_CLOSED: + return "Image capture failed due to the camera being closed."; + case ImageCapture.ERROR_INVALID_CAMERA: + return "The ImageCapture use case was bound to an invalid camera by the Flutter camera plugin. If you see this error, please file an issue if you cannot find one that already exists: https://github.com/flutter/flutter/issues/."; + default: + return "An unknown error has occurred while attempting to take a picture. Check the logs for more details."; + } + } } 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 index 8cf28799b911..fcff73b59e3c 100644 --- 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 @@ -38,14 +38,17 @@ public PendingRecording asPersistentRecording(PendingRecording pigeonInstance) { @NonNull @Override public PendingRecording withAudioEnabled(PendingRecording pigeonInstance, boolean initialMuted) { - if (!initialMuted - && ContextCompat.checkSelfPermission( + boolean hasPermission = + ContextCompat.checkSelfPermission( getPigeonRegistrar().getContext(), Manifest.permission.RECORD_AUDIO) - == PackageManager.PERMISSION_GRANTED) { - return pigeonInstance.withAudioEnabled(false); + == PackageManager.PERMISSION_GRANTED; + + if (hasPermission) { + return pigeonInstance.withAudioEnabled(initialMuted); } - return pigeonInstance.withAudioEnabled(true); + // By default, the recording will not contain audio. + return pigeonInstance; } @NonNull 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 index 5269de95c077..56919b5a1567 100644 --- 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 @@ -4,9 +4,14 @@ package io.flutter.plugins.camerax; +import android.hardware.camera2.CaptureRequest; +import android.util.Range; import android.view.Surface; import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import androidx.annotation.OptIn; +import androidx.camera.camera2.interop.Camera2Interop; +import androidx.camera.camera2.interop.ExperimentalCamera2Interop; import androidx.camera.core.Preview; import androidx.camera.core.ResolutionInfo; import androidx.camera.core.SurfaceRequest; @@ -35,10 +40,15 @@ public ProxyApiRegistrar getPigeonRegistrar() { return (ProxyApiRegistrar) super.getPigeonRegistrar(); } + // Range is defined as Range in pigeon. + @SuppressWarnings("unchecked") + @OptIn(markerClass = ExperimentalCamera2Interop.class) @NonNull @Override public Preview pigeon_defaultConstructor( - @Nullable ResolutionSelector resolutionSelector, @Nullable Long targetRotation) { + @Nullable ResolutionSelector resolutionSelector, + @Nullable Long targetRotation, + @Nullable Range targetFpsRange) { final Preview.Builder builder = new Preview.Builder(); if (targetRotation != null) { builder.setTargetRotation(targetRotation.intValue()); @@ -46,6 +56,13 @@ public Preview pigeon_defaultConstructor( if (resolutionSelector != null) { builder.setResolutionSelector(resolutionSelector); } + + if (targetFpsRange != null) { + Camera2Interop.Extender extender = new Camera2Interop.Extender<>(builder); + extender.setCaptureRequestOption( + CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, (Range) targetFpsRange); + } + return builder.build(); } 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 index 3fb3a170b9c2..e0da224424cb 100644 --- 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 @@ -4,7 +4,13 @@ package io.flutter.plugins.camerax; +import android.hardware.camera2.CaptureRequest; +import android.util.Range; import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.annotation.OptIn; +import androidx.camera.camera2.interop.Camera2Interop; +import androidx.camera.camera2.interop.ExperimentalCamera2Interop; import androidx.camera.video.VideoCapture; import androidx.camera.video.VideoOutput; @@ -18,10 +24,23 @@ class VideoCaptureProxyApi extends PigeonApiVideoCapture { super(pigeonRegistrar); } + // Range is defined as Range in pigeon. + @SuppressWarnings("unchecked") + @OptIn(markerClass = ExperimentalCamera2Interop.class) @NonNull @Override - public VideoCapture withOutput(@NonNull VideoOutput videoOutput) { - return VideoCapture.withOutput(videoOutput); + public VideoCapture withOutput( + @NonNull VideoOutput videoOutput, @Nullable Range targetFpsRange) { + VideoCapture.Builder builder = new VideoCapture.Builder<>(videoOutput); + + if (targetFpsRange != null) { + Camera2Interop.Extender> extender = + new Camera2Interop.Extender<>(builder); + extender.setCaptureRequestOption( + CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, (Range) targetFpsRange); + } + + return builder.build(); } @NonNull 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 169d33b70a54..cb626ce45994 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 @@ -9,15 +9,18 @@ import static org.mockito.Mockito.when; import androidx.camera.core.CameraInfo; +import androidx.camera.core.CameraSelector; import androidx.camera.core.CameraState; import androidx.camera.core.ExposureState; import androidx.camera.core.ZoomState; import androidx.lifecycle.LiveData; +import java.util.Arrays; +import java.util.List; import org.junit.Test; public class CameraInfoTest { @Test - public void getSensorRotationDegrees_makesCallToRetrieveSensorRotationDegrees() { + public void sensorRotationDegrees_makesCallToRetrieveSensorRotationDegrees() { final PigeonApiCameraInfo api = new TestProxyApiRegistrar().getPigeonApiCameraInfo(); final CameraInfo instance = mock(CameraInfo.class); @@ -27,6 +30,41 @@ public void getSensorRotationDegrees_makesCallToRetrieveSensorRotationDegrees() assertEquals(value, api.sensorRotationDegrees(instance)); } + @Test + public void lensFacing_makesCallToRetrieveLensFacing() { + final PigeonApiCameraInfo api = new TestProxyApiRegistrar().getPigeonApiCameraInfo(); + + final CameraInfo instance = mock(CameraInfo.class); + List testedLensFacingValues = + Arrays.asList( + CameraSelector.LENS_FACING_BACK, + CameraSelector.LENS_FACING_FRONT, + CameraSelector.LENS_FACING_EXTERNAL, + CameraSelector.LENS_FACING_UNKNOWN); + + for (int testedLensFacingValue : testedLensFacingValues) { + when(instance.getLensFacing()).thenReturn(testedLensFacingValue); + + LensFacing expected; + switch (testedLensFacingValue) { + case CameraSelector.LENS_FACING_BACK: + expected = LensFacing.BACK; + break; + case CameraSelector.LENS_FACING_FRONT: + expected = LensFacing.FRONT; + break; + case CameraSelector.LENS_FACING_EXTERNAL: + expected = LensFacing.EXTERNAL; + break; + default: + expected = LensFacing.UNKNOWN; + break; + } + + assertEquals(expected, api.lensFacing(instance)); + } + } + @SuppressWarnings("unchecked") @Test public void getCameraState_makesCallToRetrieveLiveCameraState() { 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 463491d00b62..9a9ffdc47865 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 @@ -11,7 +11,10 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import android.hardware.camera2.CaptureRequest; +import android.util.Range; import android.view.Surface; +import androidx.camera.camera2.interop.Camera2Interop; import androidx.camera.core.ImageAnalysis; import androidx.camera.core.ImageAnalysis.Analyzer; import androidx.camera.core.resolutionselector.ResolutionSelector; @@ -19,6 +22,7 @@ import java.util.concurrent.Executor; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.MockedConstruction; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.stubbing.Answer; @@ -26,19 +30,36 @@ @RunWith(RobolectricTestRunner.class) public class ImageAnalysisTest { + // Due to Java's Type Erasure, we cannot get a class literal (e.g., Extender.class) for a + // parameterized type. We must use the raw type (Extender.class) which forces the 'unchecked' and + // 'rawtypes' warnings. The runtime logic handles the type safely. + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void pigeon_defaultConstructor_createsExpectedImageAnalysisInstance() { final PigeonApiImageAnalysis api = new TestProxyApiRegistrar().getPigeonApiImageAnalysis(); final ResolutionSelector mockResolutionSelector = new ResolutionSelector.Builder().build(); final long targetResolution = Surface.ROTATION_0; + final Range targetFpsRange = new Range<>(30, 30); final long outputImageFormat = ImageAnalysis.OUTPUT_IMAGE_FORMAT_NV21; - final ImageAnalysis imageAnalysis = - api.pigeon_defaultConstructor(mockResolutionSelector, targetResolution, outputImageFormat); - assertEquals(imageAnalysis.getResolutionSelector(), mockResolutionSelector); - assertEquals(imageAnalysis.getTargetRotation(), Surface.ROTATION_0); - assertEquals(imageAnalysis.getOutputImageFormat(), ImageAnalysis.OUTPUT_IMAGE_FORMAT_NV21); + try (MockedConstruction mockCamera2InteropExtender = + Mockito.mockConstruction( + Camera2Interop.Extender.class, + (mock, context) -> { + when(mock.setCaptureRequestOption( + CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, targetFpsRange)) + .thenReturn(mock); + })) { + final ImageAnalysis imageAnalysis = + api.pigeon_defaultConstructor( + mockResolutionSelector, targetResolution, targetFpsRange, outputImageFormat); + + assertEquals(mockResolutionSelector, imageAnalysis.getResolutionSelector()); + assertEquals(Surface.ROTATION_0, imageAnalysis.getTargetRotation()); + assertEquals(1, mockCamera2InteropExtender.constructed().size()); + assertEquals(ImageAnalysis.OUTPUT_IMAGE_FORMAT_NV21, imageAnalysis.getOutputImageFormat()); + } } @Test 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 56d800ad86b3..5c84dff947df 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 @@ -88,11 +88,13 @@ ImageCapture.OutputFileOptions createImageCaptureOutputFileOptions(@NonNull File @NonNull @Override ImageCapture.OnImageSavedCallback createOnImageSavedCallback( - @NonNull File file, @NonNull Function1, Unit> callback) { + @NonNull File file, + @NonNull SystemServicesManager systemServicesManager, + @NonNull Function1, Unit> callback) { final File mockFile = mock(File.class); when(mockFile.getAbsolutePath()).thenReturn(filename); final ImageCapture.OnImageSavedCallback imageSavedCallback = - super.createOnImageSavedCallback(mockFile, callback); + super.createOnImageSavedCallback(mockFile, systemServicesManager, callback); imageSavedCallback.onImageSaved(mock(ImageCapture.OutputFileResults.class)); return imageSavedCallback; } @@ -114,6 +116,7 @@ ImageCapture.OnImageSavedCallback createOnImageSavedCallback( final String[] result = {null}; api.takePicture( instance, + mock(SystemServicesManager.class), ResultCompat.asCompatCallback( reply -> { result[0] = reply.getOrNull(); @@ -155,6 +158,7 @@ public void takePicture_sendsErrorWhenTemporaryFileCannotBeCreated() { final Throwable[] result = {null}; api.takePicture( instance, + mock(SystemServicesManager.class), ResultCompat.asCompatCallback( reply -> { result[0] = reply.exceptionOrNull(); @@ -167,14 +171,16 @@ public void takePicture_sendsErrorWhenTemporaryFileCannotBeCreated() { } @Test - public void takePicture_onImageSavedCallbackCanSendsError() { + public void takePicture_onImageSavedCallbackSendsErrorAndReportsException() { final ProxyApiRegistrar mockApiRegistrar = mock(ProxyApiRegistrar.class); final Context mockContext = mock(Context.class); final File mockOutputDir = mock(File.class); + final SystemServicesManager mockSystemServicesManager = mock(SystemServicesManager.class); when(mockContext.getCacheDir()).thenReturn(mockOutputDir); when(mockApiRegistrar.getContext()).thenReturn(mockContext); final ImageCaptureException captureException = mock(ImageCaptureException.class); + when(captureException.getImageCaptureError()).thenReturn(ImageCapture.ERROR_CAPTURE_FAILED); final ImageCaptureProxyApi api = new ImageCaptureProxyApi(mockApiRegistrar) { @Override @@ -185,9 +191,11 @@ ImageCapture.OutputFileOptions createImageCaptureOutputFileOptions(@NonNull File @NonNull @Override ImageCapture.OnImageSavedCallback createOnImageSavedCallback( - @NonNull File file, @NonNull Function1, Unit> callback) { + @NonNull File file, + @NonNull SystemServicesManager systemServicesManager, + @NonNull Function1, Unit> callback) { final ImageCapture.OnImageSavedCallback imageSavedCallback = - super.createOnImageSavedCallback(mock(File.class), callback); + super.createOnImageSavedCallback(mock(File.class), systemServicesManager, callback); imageSavedCallback.onError(captureException); return imageSavedCallback; } @@ -209,6 +217,7 @@ ImageCapture.OnImageSavedCallback createOnImageSavedCallback( final Throwable[] result = {null}; api.takePicture( instance, + mockSystemServicesManager, ResultCompat.asCompatCallback( reply -> { result[0] = reply.exceptionOrNull(); @@ -220,6 +229,8 @@ ImageCapture.OnImageSavedCallback createOnImageSavedCallback( any(ImageCapture.OutputFileOptions.class), any(Executor.class), any(ImageCapture.OnImageSavedCallback.class)); + verify(mockSystemServicesManager) + .onCameraError("The camera framework failed to fulfill the image capture request."); assertEquals(result[0], captureException); } } 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 883cc8aefcfc..089d926bedef 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 @@ -8,6 +8,7 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -52,7 +53,6 @@ public void withAudioEnabled_doesNotEnableAudioWhenRequestedAndPermissionNotGran final PigeonApiPendingRecording api = new TestProxyApiRegistrar().getPigeonApiPendingRecording(); final PendingRecording instance = mock(PendingRecording.class); - final PendingRecording newInstance = mock(PendingRecording.class); try (MockedStatic mockedContextCompat = Mockito.mockStatic(ContextCompat.class)) { @@ -63,10 +63,32 @@ public void withAudioEnabled_doesNotEnableAudioWhenRequestedAndPermissionNotGran any(Context.class), eq(Manifest.permission.RECORD_AUDIO))) .thenAnswer((Answer) invocation -> PackageManager.PERMISSION_DENIED); - when(instance.withAudioEnabled(true)).thenReturn(newInstance); + when(instance.withAudioEnabled(false)).thenReturn(instance); - assertEquals(api.withAudioEnabled(instance, false), newInstance); - verify(instance).withAudioEnabled(true); + assertEquals(api.withAudioEnabled(instance, false), instance); + verify(instance, never()).withAudioEnabled(false); + } + } + + @Test + public void withAudioEnabled_doesNotEnableAudioWhenNotRequestedAndPermissionNotGranted() { + final PigeonApiPendingRecording api = + new TestProxyApiRegistrar().getPigeonApiPendingRecording(); + final PendingRecording instance = mock(PendingRecording.class); + + try (MockedStatic mockedContextCompat = + Mockito.mockStatic(ContextCompat.class)) { + mockedContextCompat + .when( + () -> + ContextCompat.checkSelfPermission( + any(Context.class), eq(Manifest.permission.RECORD_AUDIO))) + .thenAnswer((Answer) invocation -> PackageManager.PERMISSION_DENIED); + + when(instance.withAudioEnabled(true)).thenReturn(instance); + + assertEquals(api.withAudioEnabled(instance, true), instance); + verify(instance, never()).withAudioEnabled(true); } } 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 0e2cd2242888..eaa990338900 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 @@ -13,9 +13,12 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; +import android.hardware.camera2.CaptureRequest; +import android.util.Range; import android.util.Size; import android.view.Surface; import androidx.annotation.NonNull; +import androidx.camera.camera2.interop.Camera2Interop; import androidx.camera.core.Preview; import androidx.camera.core.ResolutionInfo; import androidx.camera.core.SurfaceRequest; @@ -26,21 +29,39 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; +import org.mockito.MockedConstruction; +import org.mockito.Mockito; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class PreviewTest { + // Due to Java's Type Erasure, we cannot get a class literal (e.g., Extender.class) for a + // parameterized type. We must use the raw type (Extender.class) which forces the 'unchecked' and + // 'rawtypes' warnings. The runtime logic handles the type safely. + @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void pigeon_defaultConstructor_createsPreviewWithCorrectConfiguration() { final PigeonApiPreview api = new TestProxyApiRegistrar().getPigeonApiPreview(); final ResolutionSelector mockResolutionSelector = new ResolutionSelector.Builder().build(); final long targetResolution = Surface.ROTATION_0; - final Preview instance = - api.pigeon_defaultConstructor(mockResolutionSelector, targetResolution); - - assertEquals(instance.getResolutionSelector(), mockResolutionSelector); - assertEquals(instance.getTargetRotation(), Surface.ROTATION_0); + final Range targetFpsRange = new Range<>(30, 30); + + try (MockedConstruction mockCamera2InteropExtender = + Mockito.mockConstruction( + Camera2Interop.Extender.class, + (mock, context) -> { + when(mock.setCaptureRequestOption( + CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, targetFpsRange)) + .thenReturn(mock); + })) { + final Preview instance = + api.pigeon_defaultConstructor(mockResolutionSelector, targetResolution, targetFpsRange); + + assertEquals(mockResolutionSelector, instance.getResolutionSelector()); + assertEquals(Surface.ROTATION_0, instance.getTargetRotation()); + assertEquals(1, mockCamera2InteropExtender.constructed().size()); + } } @Test 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 c59f4814b605..b81b853eee71 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 @@ -9,32 +9,42 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import android.hardware.camera2.CaptureRequest; +import android.util.Range; +import androidx.camera.camera2.interop.Camera2Interop; import androidx.camera.video.VideoCapture; import androidx.camera.video.VideoOutput; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.MockedStatic; +import org.mockito.MockedConstruction; import org.mockito.Mockito; -import org.mockito.stubbing.Answer; import org.robolectric.RobolectricTestRunner; @RunWith(RobolectricTestRunner.class) public class VideoCaptureTest { + // Due to Java's Type Erasure, we cannot get a class literal (e.g., Extender.class) for a + // parameterized type. We must use the raw type (Extender.class) which forces the 'unchecked' and + // 'rawtypes' warnings. The runtime logic handles the type safely. @SuppressWarnings({"unchecked", "rawtypes"}) @Test public void withOutput_createsVideoCaptureWithVideoOutput() { final PigeonApiVideoCapture api = new TestProxyApiRegistrar().getPigeonApiVideoCapture(); - final VideoCapture instance = mock(VideoCapture.class); final VideoOutput videoOutput = mock(VideoOutput.class); + final Range targetFpsRange = new Range<>(30, 30); - try (MockedStatic mockedCamera2CameraInfo = - Mockito.mockStatic(VideoCapture.class)) { - mockedCamera2CameraInfo - .when(() -> VideoCapture.withOutput(videoOutput)) - .thenAnswer((Answer) invocation -> instance); + try (MockedConstruction mockCamera2InteropExtender = + Mockito.mockConstruction( + Camera2Interop.Extender.class, + (mock, context) -> { + when(mock.setCaptureRequestOption( + CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, targetFpsRange)) + .thenReturn(mock); + })) { + final VideoCapture videoCapture = api.withOutput(videoOutput, targetFpsRange); - assertEquals(api.withOutput(videoOutput), instance); + assertEquals(1, mockCamera2InteropExtender.constructed().size()); + assertEquals(videoOutput, videoCapture.getOutput()); } } diff --git a/packages/camera/camera_android_camerax/example/android/settings.gradle b/packages/camera/camera_android_camerax/example/android/settings.gradle index 7be5709da0ca..b83203f03197 100644 --- a/packages/camera/camera_android_camerax/example/android/settings.gradle +++ b/packages/camera/camera_android_camerax/example/android/settings.gradle @@ -18,10 +18,10 @@ 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.11.0" apply false - id "org.jetbrains.kotlin.android" version "2.2.0" apply false - id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1" + id "dev.flutter.flutter-plugin-loader" version "1.0.0" + id "com.android.application" version "8.11.1" apply false + id "org.jetbrains.kotlin.android" version "2.2.20" apply false + id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1" } include ":app" diff --git a/packages/camera/camera_android_camerax/example/integration_test/integration_test.dart b/packages/camera/camera_android_camerax/example/integration_test/integration_test.dart index 93de4ea42f91..145186e6cd4a 100644 --- a/packages/camera/camera_android_camerax/example/integration_test/integration_test.dart +++ b/packages/camera/camera_android_camerax/example/integration_test/integration_test.dart @@ -14,10 +14,6 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:video_player/video_player.dart'; -// Skip due to video_player error. -// See https://github.com/flutter/flutter/issues/157181 -const bool skipFor157181 = true; - void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); @@ -25,15 +21,14 @@ void main() { CameraPlatform.instance = AndroidCameraCameraX(); }); - final Map presetExpectedSizes = - { - ResolutionPreset.low: const Size(240, 320), - ResolutionPreset.medium: const Size(480, 720), - ResolutionPreset.high: const Size(720, 1280), - ResolutionPreset.veryHigh: const Size(1080, 1920), - ResolutionPreset.ultraHigh: const Size(2160, 3840), - // Don't bother checking for max here since it could be anything. - }; + final presetExpectedSizes = { + ResolutionPreset.low: const Size(240, 320), + ResolutionPreset.medium: const Size(480, 720), + ResolutionPreset.high: const Size(720, 1280), + ResolutionPreset.veryHigh: const Size(1080, 1920), + ResolutionPreset.ultraHigh: const Size(2160, 3840), + // Don't bother checking for max here since it could be anything. + }; /// Verify that [actual] has dimensions that are at most as large as /// [expectedSize]. Allows for a mismatch in portrait vs landscape. Returns @@ -52,7 +47,7 @@ void main() { .instance .availableCameras(); - for (final CameraDescription cameraDescription in availableCameras) { + for (final cameraDescription in availableCameras) { expect( cameraDescription.lensDirection, isNot(CameraLensDirection.external), @@ -69,11 +64,11 @@ void main() { if (cameras.isEmpty) { return; } - for (final CameraDescription cameraDescription in cameras) { - bool previousPresetExactlySupported = true; + for (final cameraDescription in cameras) { + var previousPresetExactlySupported = true; for (final MapEntry preset in presetExpectedSizes.entries) { - final CameraController controller = CameraController( + final controller = CameraController( cameraDescription, mediaSettings: MediaSettings(resolutionPreset: preset.key), ); @@ -110,15 +105,15 @@ void main() { if (cameras.isEmpty) { return; } - for (final CameraDescription cameraDescription in cameras) { - bool previousPresetExactlySupported = true; + for (final cameraDescription in cameras) { + var previousPresetExactlySupported = true; for (final MapEntry preset in presetExpectedSizes.entries) { - final CameraController controller = CameraController( + final controller = CameraController( cameraDescription, mediaSettings: MediaSettings(resolutionPreset: preset.key), ); - final Completer imageCompleter = Completer(); + final imageCompleter = Completer(); await controller.initialize(); await controller.startImageStream((CameraImage image) { imageCompleter.complete(image); @@ -151,7 +146,7 @@ void main() { return; } - final CameraController controller = CameraController( + final controller = CameraController( cameras[0], mediaSettings: const MediaSettings( resolutionPreset: ResolutionPreset.low, @@ -163,22 +158,20 @@ void main() { await controller.startVideoRecording(); final int recordingStart = DateTime.now().millisecondsSinceEpoch; - sleep(const Duration(seconds: 2)); + await Future.delayed(const Duration(seconds: 2)); final XFile file = await controller.stopVideoRecording(); final int postStopTime = DateTime.now().millisecondsSinceEpoch - recordingStart; - final File videoFile = File(file.path); - final VideoPlayerController videoController = VideoPlayerController.file( - videoFile, - ); + final videoFile = File(file.path); + final videoController = VideoPlayerController.file(videoFile); await videoController.initialize(); final int duration = videoController.value.duration.inMilliseconds; await videoController.dispose(); expect(duration, lessThan(postStopTime)); - }, skip: skipFor157181); + }); testWidgets('Pause and resume video recording', (WidgetTester tester) async { final List cameras = await availableCameras(); @@ -186,7 +179,7 @@ void main() { return; } - final CameraController controller = CameraController( + final controller = CameraController( cameras[0], mediaSettings: const MediaSettings( resolutionPreset: ResolutionPreset.low, @@ -196,37 +189,36 @@ void main() { await controller.prepareForVideoRecording(); int startPause; - int timePaused = 0; - const int pauseIterations = 2; + var timePaused = 0; + const pauseIterations = 2; await controller.startVideoRecording(); final int recordingStart = DateTime.now().millisecondsSinceEpoch; - sleep(const Duration(milliseconds: 500)); + await Future.delayed(const Duration(milliseconds: 500)); - for (int i = 0; i < pauseIterations; i++) { + for (var i = 0; i < pauseIterations; i++) { await controller.pauseVideoRecording(); startPause = DateTime.now().millisecondsSinceEpoch; - sleep(const Duration(milliseconds: 500)); + await Future.delayed(const Duration(milliseconds: 500)); + await controller.resumeVideoRecording(); timePaused += DateTime.now().millisecondsSinceEpoch - startPause; - sleep(const Duration(milliseconds: 500)); + await Future.delayed(const Duration(milliseconds: 500)); } final XFile file = await controller.stopVideoRecording(); final int recordingTime = DateTime.now().millisecondsSinceEpoch - recordingStart; - final File videoFile = File(file.path); - final VideoPlayerController videoController = VideoPlayerController.file( - videoFile, - ); + final videoFile = File(file.path); + final videoController = VideoPlayerController.file(videoFile); await videoController.initialize(); final int duration = videoController.value.duration.inMilliseconds; await videoController.dispose(); expect(duration, lessThan(recordingTime - timePaused)); - }, skip: skipFor157181); + }); testWidgets('Set description while recording captures full video', ( WidgetTester tester, @@ -236,7 +228,7 @@ void main() { return; } - final CameraController controller = CameraController( + final controller = CameraController( cameras[0], mediaSettings: const MediaSettings( resolutionPreset: ResolutionPreset.medium, @@ -248,20 +240,20 @@ void main() { await controller.startVideoRecording(); + await Future.delayed(const Duration(seconds: 1)); + await controller.setDescription(cameras[1]); - await tester.pumpAndSettle(const Duration(seconds: 4)); + await Future.delayed(const Duration(seconds: 4)); await controller.setDescription(cameras[0]); - await tester.pumpAndSettle(const Duration(seconds: 1)); + await Future.delayed(const Duration(seconds: 1)); final XFile file = await controller.stopVideoRecording(); - final File videoFile = File(file.path); - final VideoPlayerController videoController = VideoPlayerController.file( - videoFile, - ); + final videoFile = File(file.path); + final videoController = VideoPlayerController.file(videoFile); await videoController.initialize(); final int duration = videoController.value.duration.inMilliseconds; await videoController.dispose(); diff --git a/packages/camera/camera_android_camerax/example/lib/camera_controller.dart b/packages/camera/camera_android_camerax/example/lib/camera_controller.dart index 2974dbe64ee9..7d456043fa4a 100644 --- a/packages/camera/camera_android_camerax/example/lib/camera_controller.dart +++ b/packages/camera/camera_android_camerax/example/lib/camera_controller.dart @@ -28,10 +28,6 @@ Future> availableCameras() async { return CameraPlatform.instance.availableCameras(); } -// TODO(stuartmorgan): Remove this once the package requires 2.10, where the -// dart:async `unawaited` accepts a nullable future. -void _unawaited(Future? future) {} - /// The state of a [CameraController]. class CameraValue { /// Creates a new camera controller state. @@ -291,8 +287,7 @@ class CameraController extends ValueNotifier { ); } try { - final Completer initializeCompleter = - Completer(); + final initializeCompleter = Completer(); _deviceOrientationSubscription = CameraPlatform.instance .onDeviceOrientationChanged() @@ -305,7 +300,7 @@ class CameraController extends ValueNotifier { mediaSettings ?? const MediaSettings(), ); - _unawaited( + unawaited( CameraPlatform.instance.onCameraInitialized(_cameraId).first.then(( CameraInitializedEvent event, ) { @@ -717,7 +712,7 @@ class CameraController extends ValueNotifier { Future getMinExposureOffset() async { _throwIfNotInitialized('getMinExposureOffset'); try { - return CameraPlatform.instance.getMinExposureOffset(_cameraId); + return await CameraPlatform.instance.getMinExposureOffset(_cameraId); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } @@ -727,7 +722,7 @@ class CameraController extends ValueNotifier { Future getMaxExposureOffset() async { _throwIfNotInitialized('getMaxExposureOffset'); try { - return CameraPlatform.instance.getMaxExposureOffset(_cameraId); + return await CameraPlatform.instance.getMaxExposureOffset(_cameraId); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } @@ -739,7 +734,7 @@ class CameraController extends ValueNotifier { Future getExposureOffsetStepSize() async { _throwIfNotInitialized('getExposureOffsetStepSize'); try { - return CameraPlatform.instance.getExposureOffsetStepSize(_cameraId); + return await CameraPlatform.instance.getExposureOffsetStepSize(_cameraId); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } @@ -784,7 +779,7 @@ class CameraController extends ValueNotifier { } try { - return CameraPlatform.instance.setExposureOffset(_cameraId, offset); + return await CameraPlatform.instance.setExposureOffset(_cameraId, offset); } on PlatformException catch (e) { throw CameraException(e.code, e.message); } @@ -858,7 +853,7 @@ class CameraController extends ValueNotifier { if (_isDisposed) { return; } - _unawaited(_deviceOrientationSubscription?.cancel()); + unawaited(_deviceOrientationSubscription?.cancel()); _isDisposed = true; super.dispose(); if (_initCalled != null) { @@ -903,13 +898,7 @@ class Optional extends IterableBase { const Optional.absent() : _value = null; /// Constructs an Optional of the given [value]. - /// - /// Throws [ArgumentError] if [value] is null. - Optional.of(T value) : _value = value { - // TODO(cbracken): Delete and make this ctor const once mixed-mode - // execution is no longer around. - ArgumentError.checkNotNull(value); - } + const Optional.of(T value) : _value = value; /// Constructs an Optional of the given [value]. /// diff --git a/packages/camera/camera_android_camerax/example/lib/camera_preview.dart b/packages/camera/camera_android_camerax/example/lib/camera_preview.dart index 54d5b43a240a..656bb8c4772a 100644 --- a/packages/camera/camera_android_camerax/example/lib/camera_preview.dart +++ b/packages/camera/camera_android_camerax/example/lib/camera_preview.dart @@ -59,7 +59,7 @@ class CameraPreview extends StatelessWidget { } int _getQuarterTurns() { - final Map turns = { + final turns = { DeviceOrientation.portraitUp: 0, DeviceOrientation.landscapeRight: 1, DeviceOrientation.portraitDown: 2, diff --git a/packages/camera/camera_android_camerax/example/lib/main.dart b/packages/camera/camera_android_camerax/example/lib/main.dart index bbb860f7cea9..c3aba39ed60f 100644 --- a/packages/camera/camera_android_camerax/example/lib/main.dart +++ b/packages/camera/camera_android_camerax/example/lib/main.dart @@ -568,7 +568,7 @@ class _CameraExampleHomeState extends State /// Display a row of toggle to select the camera (or a message if no camera is available). Widget _cameraTogglesRowWidget() { - final List toggles = []; + final toggles = []; void onChanged(CameraDescription? description) { if (description == null) { @@ -619,7 +619,7 @@ class _CameraExampleHomeState extends State final CameraController cameraController = controller!; - final Offset offset = Offset( + final offset = Offset( details.localPosition.dx / constraints.maxWidth, details.localPosition.dy / constraints.maxHeight, ); @@ -638,7 +638,7 @@ class _CameraExampleHomeState extends State Future _initializeCameraController( CameraDescription cameraDescription, ) async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( cameraDescription, mediaSettings: MediaSettings( resolutionPreset: ResolutionPreset.low, @@ -898,7 +898,7 @@ class _CameraExampleHomeState extends State } try { - return cameraController.stopVideoRecording(); + return await cameraController.stopVideoRecording(); } on CameraException catch (e) { _showCameraException(e); return null; @@ -995,7 +995,7 @@ class _CameraExampleHomeState extends State return; } - final VideoPlayerController vController = kIsWeb + final vController = kIsWeb ? VideoPlayerController.networkUrl(Uri.parse(videoFile!.path)) : VideoPlayerController.file(File(videoFile!.path)); 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 f88abd5eb7e5..e52e4bd09cf1 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 @@ -13,7 +13,6 @@ import 'package:flutter/services.dart' import 'package:flutter/widgets.dart' show Texture, Widget, visibleForTesting; import 'package:stream_transform/stream_transform.dart'; import 'camerax_library.dart'; -import 'camerax_proxy.dart'; import 'rotated_preview_delegate.dart'; /// The Android implementation of [CameraPlatform] that uses the CameraX library. @@ -26,11 +25,6 @@ class AndroidCameraCameraX extends CameraPlatform { CameraPlatform.instance = AndroidCameraCameraX(); } - /// Proxy for creating `JavaObject`s and calling their methods that require - /// testing. - @visibleForTesting - CameraXProxy proxy = CameraXProxy(); - /// The [ProcessCameraProvider] instance used to access camera functionality. @visibleForTesting ProcessCameraProvider? processCameraProvider; @@ -77,16 +71,16 @@ class AndroidCameraCameraX extends CameraPlatform { String? videoOutputPath; /// Handles access to system resources. - late final SystemServicesManager systemServicesManager = proxy - .newSystemServicesManager( + late final SystemServicesManager systemServicesManager = + SystemServicesManager( onCameraError: (_, String errorDescription) { cameraErrorStreamController.add(errorDescription); }, ); /// Handles retrieving media orientation for a device. - late final DeviceOrientationManager deviceOrientationManager = proxy - .newDeviceOrientationManager( + late final DeviceOrientationManager deviceOrientationManager = + DeviceOrientationManager( onDeviceOrientationChanged: (_, String orientation) { final DeviceOrientation deviceOrientation = _deserializeDeviceOrientation(orientation); @@ -118,8 +112,8 @@ class AndroidCameraCameraX extends CameraPlatform { final StreamQueue videoRecordingEventStreamQueue = StreamQueue(videoRecordingEventStreamController.stream); - late final VideoRecordEventListener _videoRecordingEventListener = proxy - .newVideoRecordEventListener( + late final VideoRecordEventListener _videoRecordingEventListener = + VideoRecordEventListener( onEvent: (_, VideoRecordEvent event) { videoRecordingEventStreamController.add(event); }, @@ -166,7 +160,7 @@ class AndroidCameraCameraX extends CameraPlatform { final StreamController cameraEventStreamController = StreamController.broadcast(); - /// The stream of camera events. + /// The stream of camera events for the camera with ID cameraId. Stream _cameraEvents(int cameraId) => cameraEventStreamController .stream .where((CameraEvent event) => event.cameraId == cameraId); @@ -288,6 +282,9 @@ class AndroidCameraCameraX extends CameraPlatform { /// The preset resolution selector for the camera. ResolutionSelector? _presetResolutionSelector; + /// The configured target FPS range for the camera. + CameraIntegerRange? _targetFpsRange; + /// The ID of the surface texture that the camera preview is drawn to. late int _flutterSurfaceTextureId; @@ -297,45 +294,39 @@ class AndroidCameraCameraX extends CameraPlatform { /// Returns list of all available cameras and their descriptions. @override Future> availableCameras() async { - proxy.setUpGenericsProxy(); + setUpGenerics(); - final List cameraDescriptions = []; + final cameraDescriptions = []; - processCameraProvider ??= await proxy.getInstanceProcessCameraProvider(); + processCameraProvider ??= await ProcessCameraProvider.getInstance(); final List cameraInfos = (await processCameraProvider!.getAvailableCameraInfos()).cast(); CameraLensDirection? cameraLensDirection; - int cameraCount = 0; int? cameraSensorOrientation; String? cameraName; - for (final CameraInfo cameraInfo in cameraInfos) { - // 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 - .newCameraSelector(requireLensFacing: LensFacing.back) - .filter([cameraInfo])) - .isNotEmpty) { - cameraLensDirection = CameraLensDirection.back; - } else if ((await proxy - .newCameraSelector(requireLensFacing: LensFacing.front) - .filter([cameraInfo])) - .isNotEmpty) { - cameraLensDirection = CameraLensDirection.front; - } else { - //Skip this CameraInfo as its lens direction is unknown - continue; + for (final cameraInfo in cameraInfos) { + final LensFacing lensFacing = cameraInfo.lensFacing; + switch (lensFacing) { + case LensFacing.front: + cameraLensDirection = CameraLensDirection.front; + case LensFacing.back: + cameraLensDirection = CameraLensDirection.back; + case LensFacing.external: + cameraLensDirection = CameraLensDirection.external; + case LensFacing.unknown: + // Skip this CameraInfo as its lens direction is unknown + continue; } cameraSensorOrientation = cameraInfo.sensorRotationDegrees; - cameraName = 'Camera $cameraCount'; - cameraCount++; + cameraName = await Camera2CameraInfo.from( + cameraInfo: cameraInfo, + ).getCameraId(); _savedCameras[cameraName] = cameraInfo; - // TODO(camsim99): Use camera ID retrieved from Camera2CameraInfo as - // camera name: https://github.com/flutter/flutter/issues/147545. cameraDescriptions.add( CameraDescription( name: cameraName, @@ -396,9 +387,7 @@ class AndroidCameraCameraX extends CameraPlatform { final LensFacing cameraSelectorLensDirection = _getCameraSelectorLensDirection(cameraDescription.lensDirection); cameraIsFrontFacing = cameraSelectorLensDirection == LensFacing.front; - cameraSelector = proxy.newCameraSelector( - cameraInfoForFilter: chosenCameraInfo, - ); + cameraSelector = CameraSelector(cameraInfoForFilter: chosenCameraInfo); // Start listening for device orientation changes preceding camera creation. unawaited( deviceOrientationManager.startListeningForDeviceOrientationChange(), @@ -408,32 +397,41 @@ class AndroidCameraCameraX extends CameraPlatform { _presetResolutionSelector = _getResolutionSelectorFromPreset( mediaSettings?.resolutionPreset, ); + + final int? targetFps = mediaSettings?.fps; + if (targetFps != null) { + _targetFpsRange = CameraIntegerRange(lower: targetFps, upper: targetFps); + } + final QualitySelector? presetQualitySelector = _getQualitySelectorFromPreset(mediaSettings?.resolutionPreset); // Retrieve a fresh ProcessCameraProvider instance. - processCameraProvider ??= await proxy.getInstanceProcessCameraProvider(); + processCameraProvider ??= await ProcessCameraProvider.getInstance(); unawaited(processCameraProvider!.unbindAll()); // Configure Preview instance. - preview = proxy.newPreview( + preview = Preview( resolutionSelector: _presetResolutionSelector, - /* use CameraX default target rotation */ targetRotation: null, + targetFpsRange: _targetFpsRange, ); _flutterSurfaceTextureId = await preview!.setSurfaceProvider( systemServicesManager, ); // Configure ImageCapture instance. - imageCapture = proxy.newImageCapture( + imageCapture = ImageCapture( resolutionSelector: _presetResolutionSelector, /* use CameraX default target rotation */ targetRotation: await deviceOrientationManager.getDefaultDisplayRotation(), ); // Configure VideoCapture and Recorder instances. - recorder = proxy.newRecorder(qualitySelector: presetQualitySelector); - videoCapture = proxy.withOutputVideoCapture(videoOutput: recorder!); + recorder = Recorder(qualitySelector: presetQualitySelector); + videoCapture = VideoCapture.withOutput( + videoOutput: recorder!, + targetFpsRange: _targetFpsRange, + ); // Retrieve info required for correcting the rotation of the camera preview // if necessary. @@ -449,7 +447,7 @@ class AndroidCameraCameraX extends CameraPlatform { return _flutterSurfaceTextureId; } - /// Initializes the camera on the device. + /// Initializes the camera with ID [cameraId] on the device. /// /// Specifically, this method: /// * Configures the [ImageAnalysis] instance according to the specified @@ -478,10 +476,10 @@ class AndroidCameraCameraX extends CameraPlatform { // Defaults to YUV_420_888 image format. _imageAnalysisOutputImageFormat = _imageAnalysisOutputFormatFromImageFormatGroup(imageFormatGroup); - imageAnalysis = proxy.newImageAnalysis( + imageAnalysis = ImageAnalysis( resolutionSelector: _presetResolutionSelector, + targetFpsRange: _targetFpsRange, outputImageFormat: _imageAnalysisOutputImageFormat, - /* use CameraX default target rotation */ targetRotation: null, ); // Bind configured UseCases to ProcessCameraProvider instance & mark Preview @@ -507,8 +505,8 @@ class AndroidCameraCameraX extends CameraPlatform { // support these by default. const ExposureMode exposureMode = ExposureMode.auto; const FocusMode focusMode = FocusMode.auto; - const bool exposurePointSupported = true; - const bool focusPointSupported = true; + const exposurePointSupported = true; + const focusPointSupported = true; cameraEventStreamController.add( CameraInitializedEvent( @@ -523,9 +521,7 @@ class AndroidCameraCameraX extends CameraPlatform { ); } - /// Releases the resources of the accessed camera. - /// - /// [cameraId] not used. + /// Releases the resources of the accessed camera with ID [cameraId]. @override Future dispose(int cameraId) async { await preview?.releaseSurfaceProvider(); @@ -535,13 +531,13 @@ class AndroidCameraCameraX extends CameraPlatform { await deviceOrientationManager.stopListeningForDeviceOrientationChange(); } - /// The camera has been initialized. + /// The camera with ID [cameraId] has been initialized. @override Stream onCameraInitialized(int cameraId) { return _cameraEvents(cameraId).whereType(); } - /// The camera's resolution has changed. + /// The resolution of camera with ID [cameraId] has changed. /// /// This stream currently has no events being added to it from this plugin. @override @@ -549,13 +545,13 @@ class AndroidCameraCameraX extends CameraPlatform { return _cameraEvents(cameraId).whereType(); } - /// The camera started to close. + /// The camera with ID [cameraId] has started to close. @override Stream onCameraClosing(int cameraId) { return _cameraEvents(cameraId).whereType(); } - /// The camera experienced an error. + /// The camera with ID [cameraId] experienced an error. @override Stream onCameraError(int cameraId) { return StreamGroup.mergeBroadcast( @@ -570,13 +566,13 @@ class AndroidCameraCameraX extends CameraPlatform { ); } - /// The camera finished recording a video. + /// The camera with ID [cameraId] finished recording a video. @override Stream onVideoRecordedEvent(int cameraId) { return _cameraEvents(cameraId).whereType(); } - /// Locks the capture orientation. + /// Locks the capture orientation of camera with ID [cameraId]. @override Future lockCaptureOrientation( int cameraId, @@ -599,22 +595,21 @@ class AndroidCameraCameraX extends CameraPlatform { await videoCapture!.setTargetRotation(targetLockedRotation); } - /// Unlocks the capture orientation. + /// Unlocks the capture orientation of camera with ID [cameraId]. @override Future unlockCaptureOrientation(int cameraId) async { // Flag that default rotation should be set for UseCases as needed. captureOrientationLocked = false; } - /// Sets the exposure point for automatically determining the exposure values. + /// Sets the exposure point for automatically determining the exposure values for + /// camera with ID [cameraId]. /// /// Supplying `null` for the [point] argument will result in resetting to the /// original exposure point value. /// /// Supplied non-null point must be mapped to the entire un-altered preview /// surface for the exposure point to be applied accurately. - /// - /// [cameraId] is not used. @override Future setExposurePoint(int cameraId, Point? point) async { // We lock the new focus and metering action if focus mode has been locked @@ -629,9 +624,7 @@ class AndroidCameraCameraX extends CameraPlatform { ); } - /// Gets the minimum supported exposure offset for the selected camera in EV units. - /// - /// [cameraId] not used. + /// Gets the minimum supported exposure offset for the camera with ID [cameraId] in EV units. @override Future getMinExposureOffset(int cameraId) async { final ExposureState exposureState = cameraInfo!.exposureState; @@ -639,9 +632,7 @@ class AndroidCameraCameraX extends CameraPlatform { exposureState.exposureCompensationStep; } - /// Gets the maximum supported exposure offset for the selected camera in EV units. - /// - /// [cameraId] not used. + /// Gets the maximum supported exposure offset for the camera with ID [cameraId] in EV units. @override Future getMaxExposureOffset(int cameraId) async { final ExposureState exposureState = cameraInfo!.exposureState; @@ -649,7 +640,7 @@ class AndroidCameraCameraX extends CameraPlatform { exposureState.exposureCompensationStep; } - /// Sets the focus mode for taking pictures. + /// Sets the focus mode for taking pictures with camera with ID [cameraId] /// /// Setting [FocusMode.locked] will lock the current focus point if one exists /// or the center of entire sensor area if not, and will stay locked until @@ -690,12 +681,11 @@ class AndroidCameraCameraX extends CameraPlatform { // If there isn't, lock center of entire sensor area by default. if (lockedFocusPoint == null) { - final DisplayOrientedMeteringPointFactory meteringPointFactory = proxy - .newDisplayOrientedMeteringPointFactory( - cameraInfo: cameraInfo!, - width: 1, - height: 1, - ); + final meteringPointFactory = DisplayOrientedMeteringPointFactory( + cameraInfo: cameraInfo!, + width: 1, + height: 1, + ); lockedFocusPoint = await meteringPointFactory.createPointWithSize( 0.5, 0.5, @@ -731,11 +721,9 @@ class AndroidCameraCameraX extends CameraPlatform { } } - /// Gets the supported step size for exposure offset for the selected camera in EV units. + /// Gets the supported step size for exposure offset for the camera with ID [cameraId] in EV units. /// /// Returns -1 if exposure compensation is not supported for the device. - /// - /// [cameraId] not used. @override Future getExposureOffsetStepSize(int cameraId) async { final ExposureState exposureState = cameraInfo!.exposureState; @@ -749,7 +737,7 @@ class AndroidCameraCameraX extends CameraPlatform { return exposureOffsetStepSize; } - /// Sets the exposure offset for the selected camera. + /// Sets the exposure offset for the camera with ID [cameraId]. /// /// The supplied [offset] value should be in EV units. 1 EV unit represents a /// doubling in brightness. It should be between the minimum and maximum offsets @@ -808,15 +796,14 @@ class AndroidCameraCameraX extends CameraPlatform { } } - /// Sets the focus point for automatically determining the focus values. + /// Sets the focus point for automatically determining the focus values for the + /// camera with ID [cameraId]. /// /// Supplying `null` for the [point] argument will result in resetting to the /// original focus point value. /// /// Supplied non-null point must be mapped to the entire un-altered preview /// surface for the focus point to be applied accurately. - /// - /// [cameraId] is not used. @override Future setFocusPoint(int cameraId, Point? point) async { // We lock the new focus and metering action if focus mode has been locked @@ -831,25 +818,22 @@ class AndroidCameraCameraX extends CameraPlatform { ); } - /// Sets the exposure mode for taking pictures. + /// Sets the exposure mode for taking pictures with the camera with ID [cameraId]. /// /// Setting [ExposureMode.locked] will lock current exposure point until it /// is unset by setting [ExposureMode.auto]. - /// - /// [cameraId] is not used. @override Future setExposureMode(int cameraId, ExposureMode mode) async { - final Camera2CameraControl camera2Control = proxy.fromCamera2CameraControl( + final camera2Control = Camera2CameraControl.from( cameraControl: cameraControl, ); - final bool lockExposureMode = mode == ExposureMode.locked; + final lockExposureMode = mode == ExposureMode.locked; - final CaptureRequestOptions captureRequestOptions = proxy - .newCaptureRequestOptions( - options: { - proxy.controlAELockCaptureRequest(): lockExposureMode, - }, - ); + final captureRequestOptions = CaptureRequestOptions( + options: { + CaptureRequest.controlAELock: lockExposureMode, + }, + ); try { await camera2Control.addCaptureRequestOptions(captureRequestOptions); @@ -863,9 +847,7 @@ class AndroidCameraCameraX extends CameraPlatform { _currentExposureMode = mode; } - /// Gets the maximum supported zoom level for the selected camera. - /// - /// [cameraId] not used. + /// Gets the maximum supported zoom level for the camera with ID [cameraId]. @override Future getMaxZoomLevel(int cameraId) async { final LiveData liveZoomState = await cameraInfo!.getZoomState(); @@ -880,9 +862,7 @@ class AndroidCameraCameraX extends CameraPlatform { return zoomState.maxZoomRatio; } - /// Gets the minimum supported zoom level for the selected camera. - /// - /// [cameraId] not used. + /// Gets the minimum supported zoom level for the camera with ID [cameraId]. @override Future getMinZoomLevel(int cameraId) async { final LiveData liveZoomState = await cameraInfo!.getZoomState(); @@ -897,7 +877,7 @@ class AndroidCameraCameraX extends CameraPlatform { return zoomState.minZoomRatio; } - /// Set the zoom level for the selected camera. + /// Set the zoom level for the camera with ID [cameraId]. /// /// The supplied [zoom] value should be between the minimum and the maximum /// supported zoom level returned by [getMinZoomLevel] and [getMaxZoomLevel]. @@ -914,15 +894,77 @@ class AndroidCameraCameraX extends CameraPlatform { } } + @override + Future> getSupportedVideoStabilizationModes( + int cameraId, + ) async { + return (await _getSupportedVideoStabilizationModeMap(cameraId)).keys; + } + + /// Throws a [ArgumentError] when an unsupported [mode] is + /// supplied. + @override + Future setVideoStabilizationMode( + int cameraId, + VideoStabilizationMode mode, + ) async { + final Map availableModes = + await _getSupportedVideoStabilizationModeMap(cameraId); + + final int? controlMode = availableModes[mode]; + if (controlMode == null) { + throw ArgumentError('Unavailable video stabilization mode.', 'mode'); + } + + final captureRequestOptions = CaptureRequestOptions( + options: { + CaptureRequest.controlVideoStabilizationMode: controlMode, + }, + ); + + final camera2Control = Camera2CameraControl.from( + cameraControl: cameraControl, + ); + await camera2Control.addCaptureRequestOptions(captureRequestOptions); + } + + /// Gets a map of video stabilization control modes that are supported for the + /// selected camera, indexed by the respective [VideoStabilizationMode]. + Future> + _getSupportedVideoStabilizationModeMap(int cameraId) async { + if (cameraInfo == null) { + return {}; + } + + final camera2CameraInfo = Camera2CameraInfo.from(cameraInfo: cameraInfo!); + + final List controlModes = + await camera2CameraInfo.getCameraCharacteristic( + CameraCharacteristics.controlAvailableVideoStabilizationModes, + ) + as List? ?? + const []; + + final modes = { + for (final int controlMode in controlModes) + // https://developer.android.com/reference/android/hardware/camera2/CameraMetadata#CONTROL_VIDEO_STABILIZATION_MODE_OFF + if (controlMode == 0) + VideoStabilizationMode.off: 0 + // https://developer.android.com/reference/android/hardware/camera2/CameraMetadata#CONTROL_VIDEO_STABILIZATION_MODE_ON + else if (controlMode == 1) + VideoStabilizationMode.level1: 1, + }; + + return modes; + } + /// The ui orientation changed. @override Stream onDeviceOrientationChanged() { return deviceOrientationChangedStreamController.stream; } - /// Pause the active preview on the current frame for the selected camera. - /// - /// [cameraId] not used. + /// Pause the active preview on the current frame for the camera with ID [cameraId]. @override Future pausePreview(int cameraId) async { _previewIsPaused = true; @@ -950,12 +992,10 @@ class AndroidCameraCameraX extends CameraPlatform { final LensFacing cameraSelectorLensDirection = _getCameraSelectorLensDirection(description.lensDirection); cameraIsFrontFacing = cameraSelectorLensDirection == LensFacing.front; - cameraSelector = proxy.newCameraSelector( - cameraInfoForFilter: chosenCameraInfo, - ); + cameraSelector = CameraSelector(cameraInfoForFilter: chosenCameraInfo); // Unbind all use cases and rebind to new CameraSelector - final List useCases = [videoCapture!]; + final useCases = [videoCapture!]; if (!_previewIsPaused) { useCases.add(preview!); } @@ -979,18 +1019,17 @@ class AndroidCameraCameraX extends CameraPlatform { await _updateCameraInfoAndLiveCameraState(_flutterSurfaceTextureId); } - /// Resume the paused preview for the selected camera. - /// - /// [cameraId] not used. + /// Resume the paused preview for the camera with ID [cameraId]. @override Future resumePreview(int cameraId) async { _previewIsPaused = false; await _bindUseCaseToLifecycle(preview!, cameraId); } - /// Returns a widget showing a live camera preview. + /// Returns a widget showing a live camera preview for the camera with ID [cameraId]. /// - /// [createCamera] must be called before attempting to build this preview. + /// [createCamera] must be called before attempting to build this preview, and + /// [cameraId] can be retrieved from that call. @override Widget buildPreview(int cameraId) { if (!previewInitiallyBound) { @@ -1021,9 +1060,7 @@ class AndroidCameraCameraX extends CameraPlatform { ); } - /// Captures an image and returns the file where it was saved. - /// - /// [cameraId] is not used. + /// Captures an image using the camera with ID [cameraId] and returns the file where it was saved. @override Future takePicture(int cameraId) async { await _bindUseCaseToLifecycle(imageCapture!, cameraId); @@ -1044,11 +1081,13 @@ class AndroidCameraCameraX extends CameraPlatform { ); } - final String picturePath = await imageCapture!.takePicture(); + final String picturePath = await imageCapture!.takePicture( + systemServicesManager, + ); return XFile(picturePath); } - /// Sets the flash mode for the selected camera. + /// Sets the flash mode for the camera with ID [cameraId]. /// /// When the [FlashMode.torch] is enabled, any previously set [FlashMode] with /// this method will be disabled, just as with any other [FlashMode]; while @@ -1096,8 +1135,9 @@ class AndroidCameraCameraX extends CameraPlatform { return Future.value(); } - /// Configures and starts a video recording. Returns silently without doing - /// anything if there is currently an active recording. + /// Configures and starts a video recording with the camera with ID [cameraId]. + /// Returns silently without doing anything if there is currently an active + /// recording. /// /// Note that the preset resolution is used to configure the recording, but /// 240p ([ResolutionPreset.low]) is unsupported and will fallback to @@ -1124,49 +1164,13 @@ class AndroidCameraCameraX extends CameraPlatform { // There is currently an active recording, so do not start a new one. return; } - - dynamic Function(CameraImageData)? streamCallback = options.streamCallback; - if (!_previewIsPaused) { - // The plugin binds the preview use case to the camera lifecycle when - // createCamera is called, but camera use cases can become limited - // when video recording and displaying a preview concurrently. This logic - // will prioritize attempting to continue displaying the preview, - // stream images, and record video if specified and supported. Otherwise, - // 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 = proxy.fromCamera2CameraInfo( - cameraInfo: cameraInfo!, - ); - final InfoSupportedHardwareLevel cameraInfoSupportedHardwareLevel = - (await camera2CameraInfo.getCameraCharacteristic( - proxy.infoSupportedHardwareLevelCameraCharacteristics(), - ))! - as InfoSupportedHardwareLevel; - - // Handle limited level device restrictions: - final bool cameraSupportsConcurrentImageCapture = - cameraInfoSupportedHardwareLevel != InfoSupportedHardwareLevel.legacy; - if (!cameraSupportsConcurrentImageCapture) { - // Concurrent preview + video recording + image capture is not supported - // unless the camera device is cameraSupportsHardwareLevelLimited or - // better. - await _unbindUseCaseFromLifecycle(imageCapture!); - } - - // Handle level 3 device restrictions: - final bool cameraSupportsHardwareLevel3 = - cameraInfoSupportedHardwareLevel == InfoSupportedHardwareLevel.level3; - if (!cameraSupportsHardwareLevel3 || streamCallback == null) { - // Concurrent preview + video recording + image streaming is not supported - // unless the camera device is cameraSupportsHardwareLevel3 or better. - streamCallback = null; - await _unbindUseCaseFromLifecycle(imageAnalysis!); - } else { - // If image streaming concurrently with video recording, image capture - // is unsupported. - await _unbindUseCaseFromLifecycle(imageCapture!); - } + final dynamic Function(CameraImageData)? streamCallback = + options.streamCallback; + if (streamCallback == null) { + // For potential performance improvements, unbind imageAnalysis if not in use. + // See https://developer.android.com/media/camera/camerax/architecture#combine-use-cases + // for details. + await _unbindUseCaseFromLifecycle(imageAnalysis!); } await _bindUseCaseToLifecycle(videoCapture!, options.cameraId); @@ -1193,7 +1197,8 @@ class AndroidCameraCameraX extends CameraPlatform { // and permission was not granted when the camera was created, then recording // audio will be disabled to respect the denied permission. pendingRecording = await pendingRecording!.withAudioEnabled( - /* initialMuted */ !enableRecordingAudio, + /* initialMuted */ + !enableRecordingAudio, ); recording = await pendingRecording!.start(_videoRecordingEventListener); @@ -1245,14 +1250,14 @@ class AndroidCameraCameraX extends CameraPlatform { } await _unbindUseCaseFromLifecycle(videoCapture!); - final XFile videoFile = XFile(videoOutputPath!); + final videoFile = XFile(videoOutputPath!); cameraEventStreamController.add( VideoRecordedEvent(cameraId, videoFile, /* duration */ null), ); return videoFile; } - /// Pause the current video recording if it is not null. + /// Pause the current video recording of the camera with ID [cameraId] if it is not null. @override Future pauseVideoRecording(int cameraId) async { if (recording != null) { @@ -1260,7 +1265,7 @@ class AndroidCameraCameraX extends CameraPlatform { } } - /// Resume the current video recording if it is not null. + /// Resume the current video recording of the camera with ID [cameraId] if it is not null. @override Future resumeVideoRecording(int cameraId) async { if (recording != null) { @@ -1271,7 +1276,7 @@ class AndroidCameraCameraX extends CameraPlatform { @override bool supportsImageStreaming() => true; - /// A new streamed frame is available. + /// A new streamed frame is available from the camera with ID [cameraId]. /// /// Listening to this stream will start streaming, and canceling will stop. /// To temporarily stop receiving frames, cancel, then listen again later. @@ -1284,7 +1289,7 @@ class AndroidCameraCameraX extends CameraPlatform { /// streamed images will still have format [ImageFormatGroup.yuv420], but /// their image data will be formatted in NV21. /// - /// [cameraId] and [options] are not used. + /// [options] are not used. @override Stream onStreamedFrameAvailable( int cameraId, { @@ -1305,7 +1310,7 @@ class AndroidCameraCameraX extends CameraPlatform { /// /// [cameraId] used to build [CameraEvent]s should you wish to filter /// these based on a reference to a cameraId received from calling - /// `createCamera(...)`. + /// [createCamera]. Future _bindUseCaseToLifecycle(UseCase useCase, int cameraId) async { final bool useCaseIsBound = await processCameraProvider!.isBound(useCase); final bool useCaseIsPausedPreview = useCase is Preview && _previewIsPaused; @@ -1337,11 +1342,10 @@ class AndroidCameraCameraX extends CameraPlatform { } // Create and set Analyzer that can read image data for image streaming. - final WeakReference weakThis = - WeakReference(this); + final weakThis = WeakReference(this); Future analyze(ImageProxy imageProxy) async { final List planes = await imageProxy.getPlanes(); - final List cameraImagePlanes = []; + final cameraImagePlanes = []; // Determine image planes. if (_imageAnalysisOutputImageFormat == @@ -1349,7 +1353,7 @@ class AndroidCameraCameraX extends CameraPlatform { // Convert three generically YUV_420_888 formatted image planes into one singular // NV21 formatted image plane if NV21 was requested for image streaming. The conversion // should be null safe. - final Uint8List? bytes = await proxy.getNv21BufferImageProxyUtils( + final Uint8List bytes = await ImageProxyUtils.getNv21Buffer( imageProxy.width, imageProxy.height, planes, @@ -1357,7 +1361,7 @@ class AndroidCameraCameraX extends CameraPlatform { cameraImagePlanes.add( CameraImagePlane( - bytes: bytes!, + bytes: bytes, bytesPerRow: imageProxy.width, // NV21 has 1.5 bytes per pixel (Y plane has width * height; VU plane has width * height / 2), // but this is rounded up because an int is expected. camera_android reports the same. @@ -1365,7 +1369,7 @@ class AndroidCameraCameraX extends CameraPlatform { ), ); } else { - for (final PlaneProxy plane in planes) { + for (final plane in planes) { cameraImagePlanes.add( CameraImagePlane( bytes: plane.buffer, @@ -1396,7 +1400,7 @@ class AndroidCameraCameraX extends CameraPlatform { } // Send out CameraImageData. - final CameraImageData cameraImageData = CameraImageData( + final cameraImageData = CameraImageData( format: cameraImageFormat, planes: cameraImagePlanes, height: imageProxy.height, @@ -1408,7 +1412,7 @@ class AndroidCameraCameraX extends CameraPlatform { } await imageAnalysis!.setAnalyzer( - proxy.newAnalyzer(analyze: (_, ImageProxy image) => analyze(image)), + Analyzer(analyze: (_, ImageProxy image) => analyze(image)), ); } @@ -1487,8 +1491,7 @@ class AndroidCameraCameraX extends CameraPlatform { /// * Send a [CameraErrorEvent] if the [CameraState] indicates that the /// camera is in error state. Observer _createCameraClosingObserver(int cameraId) { - final WeakReference weakThis = - WeakReference(this); + final weakThis = WeakReference(this); // Callback method used to implement the behavior described above: void onChanged(CameraState state) { @@ -1530,7 +1533,7 @@ class AndroidCameraCameraX extends CameraPlatform { } } - return proxy.newObserver( + return Observer( onChanged: (_, CameraState value) => onChanged(value), ); } @@ -1584,47 +1587,43 @@ class AndroidCameraCameraX extends CameraPlatform { ResolutionStrategy? resolutionStrategy; switch (preset) { case ResolutionPreset.low: - boundSize = proxy.newCameraSize(width: 320, height: 240); + boundSize = CameraSize(width: 320, height: 240); aspectRatio = AspectRatio.ratio4To3; case ResolutionPreset.medium: - boundSize = proxy.newCameraSize(width: 720, height: 480); + boundSize = CameraSize(width: 720, height: 480); case ResolutionPreset.high: - boundSize = proxy.newCameraSize(width: 1280, height: 720); + boundSize = CameraSize(width: 1280, height: 720); aspectRatio = AspectRatio.ratio16To9; case ResolutionPreset.veryHigh: - boundSize = proxy.newCameraSize(width: 1920, height: 1080); + boundSize = CameraSize(width: 1920, height: 1080); aspectRatio = AspectRatio.ratio16To9; case ResolutionPreset.ultraHigh: - boundSize = proxy.newCameraSize(width: 3840, height: 2160); + boundSize = CameraSize(width: 3840, height: 2160); aspectRatio = AspectRatio.ratio16To9; case ResolutionPreset.max: // Automatically set strategy to choose highest available. - resolutionStrategy = proxy.highestAvailableStrategyResolutionStrategy(); - return proxy.newResolutionSelector( - resolutionStrategy: resolutionStrategy, - ); + resolutionStrategy = ResolutionStrategy.highestAvailableStrategy; + return ResolutionSelector(resolutionStrategy: resolutionStrategy); case null: // If no preset is specified, default to CameraX's default behavior // for each UseCase. return null; } - resolutionStrategy = proxy.newResolutionStrategy( - boundSize: proxy.newCameraSize( - width: boundSize.width, - height: boundSize.height, - ), + resolutionStrategy = ResolutionStrategy( + boundSize: CameraSize(width: boundSize.width, height: boundSize.height), fallbackRule: fallbackRule, ); - final ResolutionFilter resolutionFilter = proxy - .createWithOnePreferredSizeResolutionFilter(preferredSize: boundSize); + final resolutionFilter = ResolutionFilter.createWithOnePreferredSize( + preferredSize: boundSize, + ); final AspectRatioStrategy? aspectRatioStrategy = aspectRatio == null ? null - : proxy.newAspectRatioStrategy( + : AspectRatioStrategy( preferredAspectRatio: aspectRatio, fallbackRule: AspectRatioStrategyFallbackRule.auto, ); - return proxy.newResolutionSelector( + return ResolutionSelector( resolutionStrategy: resolutionStrategy, resolutionFilter: resolutionFilter, aspectRatioStrategy: aspectRatioStrategy, @@ -1659,10 +1658,11 @@ class AndroidCameraCameraX extends CameraPlatform { // We will choose the next highest video quality if the one desired // is unavailable. - final FallbackStrategy fallbackStrategy = proxy - .lowerQualityOrHigherThanFallbackStrategy(quality: videoQuality); + final fallbackStrategy = FallbackStrategy.lowerQualityOrHigherThan( + quality: videoQuality, + ); - return proxy.fromQualitySelector( + return QualitySelector.from( quality: videoQuality, fallbackStrategy: fallbackStrategy, ); @@ -1684,12 +1684,11 @@ class AndroidCameraCameraX extends CameraPlatform { ); } - final DisplayOrientedMeteringPointFactory meteringPointFactory = proxy - .newDisplayOrientedMeteringPointFactory( - width: 1.0, - height: 1.0, - cameraInfo: cameraInfo!, - ); + final meteringPointFactory = DisplayOrientedMeteringPointFactory( + width: 1.0, + height: 1.0, + cameraInfo: cameraInfo!, + ); meteringPoint = await meteringPointFactory.createPoint(point.x, point.y); } return _startFocusAndMeteringFor( @@ -1760,11 +1759,10 @@ class AndroidCameraCameraX extends CameraPlatform { return true; } // Create builder to potentially add more MeteringPoints to. - final FocusMeteringActionBuilder actionBuilder = proxy - .withModeFocusMeteringActionBuilder( - point: newMeteringPointInfos.first.$1, - mode: newMeteringPointInfos.first.$2, - ); + final actionBuilder = FocusMeteringActionBuilder.withMode( + point: newMeteringPointInfos.first.$1, + mode: newMeteringPointInfos.first.$2, + ); if (disableAutoCancel) { unawaited(actionBuilder.disableAutoCancel()); } @@ -1780,8 +1778,7 @@ class AndroidCameraCameraX extends CameraPlatform { // 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, MeteringMode)> newMeteringPointInfos = - <(MeteringPoint, MeteringMode)>[]; + var newMeteringPointInfos = <(MeteringPoint, MeteringMode)>[]; if (currentFocusMeteringAction != null) { final Iterable<(MeteringPoint, MeteringMode)> originalMeteringPoints = @@ -1801,11 +1798,10 @@ class AndroidCameraCameraX extends CameraPlatform { newMeteringPointInfos.add((meteringPoint, meteringMode)); - final FocusMeteringActionBuilder actionBuilder = proxy - .withModeFocusMeteringActionBuilder( - point: newMeteringPointInfos.first.$1, - mode: newMeteringPointInfos.first.$2, - ); + final actionBuilder = FocusMeteringActionBuilder.withMode( + point: newMeteringPointInfos.first.$1, + mode: newMeteringPointInfos.first.$2, + ); if (disableAutoCancel) { unawaited(actionBuilder.disableAutoCancel()); diff --git a/packages/camera/camera_android_camerax/lib/src/camerax_library.dart b/packages/camera/camera_android_camerax/lib/src/camerax_library.dart index ba884275d35b..1731bca4680b 100644 --- a/packages/camera/camera_android_camerax/lib/src/camerax_library.dart +++ b/packages/camera/camera_android_camerax/lib/src/camerax_library.dart @@ -9,14 +9,34 @@ import 'camerax_library.g.dart' as camerax; export 'camerax_library.g.dart' hide CameraInfo, LiveData, Observer; +/// Provides overrides for the constructors and static members of classes that +/// extend Dart proxy classes. +/// +/// Intended to be similar to [camerax.PigeonOverrides]. +/// +/// This is only intended to be used with unit tests to prevent errors from +/// making message calls in a unit test. +/// +/// See [GenericsPigeonOverrides.reset] to set all overrides back to null. +@visibleForTesting +final class GenericsPigeonOverrides { + /// Overrides [Observer.new]. + static Observer Function({ + required void Function(Observer pigeonInstance, T value) onChanged, + })? + observerNew; + + /// Sets all overridden ProxyApi class members to null. + static void reset() { + observerNew = null; + } +} + /// 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, -}) { +void setUpGenerics({BinaryMessenger? pigeonBinaryMessenger}) { camerax.LiveData.pigeon_setUpMessageHandlers( pigeon_newInstance: (camerax.LiveDataSupportedType type) { switch (type) { @@ -24,13 +44,11 @@ void setUpGenerics({ 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, ); } }, @@ -38,12 +56,16 @@ void setUpGenerics({ camerax.CameraInfo.pigeon_setUpMessageHandlers( pigeon_newInstance: - (int sensorRotationDegrees, camerax.ExposureState exposureState) { + ( + int sensorRotationDegrees, + camerax.LensFacing lensFacing, + camerax.ExposureState exposureState, + ) { return CameraInfo.detached( sensorRotationDegrees: sensorRotationDegrees, + lensFacing: lensFacing, exposureState: exposureState, pigeon_binaryMessenger: pigeonBinaryMessenger, - pigeon_instanceManager: pigeonInstanceManager, ); }, ); @@ -84,11 +106,10 @@ class CameraInfo extends camerax.CameraInfo { /// create copies for an [PigeonInstanceManager]. CameraInfo.detached({ required super.sensorRotationDegrees, + required super.lensFacing, required super.exposureState, // ignore: non_constant_identifier_names super.pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - super.pigeon_instanceManager, }) : super.pigeon_detached(); @override @@ -106,9 +127,9 @@ class CameraInfo extends camerax.CameraInfo { CameraInfo pigeon_copy() { return CameraInfo.detached( sensorRotationDegrees: sensorRotationDegrees, + lensFacing: lensFacing, exposureState: exposureState, pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, ); } } @@ -130,8 +151,6 @@ class LiveData extends camerax.LiveData { required super.type, // ignore: non_constant_identifier_names super.pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - super.pigeon_instanceManager, }) : super.pigeon_detached(); @override @@ -150,7 +169,6 @@ class LiveData extends camerax.LiveData { return LiveData.detached( type: type, pigeon_binaryMessenger: pigeon_binaryMessenger, - pigeon_instanceManager: pigeon_instanceManager, ); } } @@ -160,12 +178,25 @@ class LiveData extends camerax.LiveData { /// See https://developer.android.com/reference/androidx/lifecycle/Observer. class Observer extends camerax.Observer { /// Constructs an [Observer]. - Observer({ + factory Observer({ + required void Function(Observer instance, T value) onChanged, + BinaryMessenger? binaryMessenger, + }) { + if (GenericsPigeonOverrides.observerNew != null) { + return GenericsPigeonOverrides.observerNew!(onChanged: onChanged); + } + return Observer.pigeonNew( + pigeon_binaryMessenger: binaryMessenger, + onChanged: onChanged, + ); + } + + /// Constructs an [Observer]. + @protected + Observer.pigeonNew({ 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_new( onChanged: (camerax.Observer instance, Object value) { @@ -181,8 +212,6 @@ class Observer extends camerax.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.pigeon_detached( onChanged: (camerax.Observer instance, Object value) { @@ -198,7 +227,6 @@ class Observer extends camerax.Observer { 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 6b45756e5562..7b642695e0b0 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,9 +1,9 @@ // Copyright 2013 The Flutter Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// Autogenerated from Pigeon (v26.1.0), do not edit directly. +// Autogenerated from Pigeon (v26.1.7), 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 +// 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, omit_obvious_local_variable_types, unused_shown_name, unnecessary_import, no_leading_underscores_for_local_identifiers import 'dart:async'; import 'dart:io' show Platform; @@ -89,11 +89,15 @@ class PigeonOverrides { static Preview Function({ ResolutionSelector? resolutionSelector, int? targetRotation, + CameraIntegerRange? targetFpsRange, })? preview_new; /// Overrides [VideoCapture.withOutput]. - static VideoCapture Function({required VideoOutput videoOutput})? + static VideoCapture Function({ + required VideoOutput videoOutput, + CameraIntegerRange? targetFpsRange, + })? videoCapture_withOutput; /// Overrides [Recorder.new]. @@ -148,6 +152,7 @@ class PigeonOverrides { static ImageAnalysis Function({ ResolutionSelector? resolutionSelector, int? targetRotation, + CameraIntegerRange? targetFpsRange, int? outputImageFormat, })? imageAnalysis_new; @@ -244,6 +249,9 @@ class PigeonOverrides { /// Overrides [CaptureRequest.controlAELock]. static CaptureRequestKey? captureRequest_controlAELock; + /// Overrides [CaptureRequest.controlVideoStabilizationMode]. + static CaptureRequestKey? captureRequest_controlVideoStabilizationMode; + /// Overrides [CameraCharacteristics.infoSupportedHardwareLevel]. static CameraCharacteristicsKey? cameraCharacteristics_infoSupportedHardwareLevel; @@ -251,6 +259,10 @@ class PigeonOverrides { /// Overrides [CameraCharacteristics.sensorOrientation]. static CameraCharacteristicsKey? cameraCharacteristics_sensorOrientation; + /// Overrides [CameraCharacteristics.controlAvailableVideoStabilizationModes]. + static CameraCharacteristicsKey? + cameraCharacteristics_controlAvailableVideoStabilizationModes; + /// Overrides [ProcessCameraProvider.getInstance]. static Future Function()? processCameraProvider_getInstance; @@ -298,11 +310,13 @@ class PigeonOverrides { focusMeteringActionBuilder_new = null; focusMeteringActionBuilder_withMode = null; captureRequest_controlAELock = null; + captureRequest_controlVideoStabilizationMode = null; captureRequestOptions_new = null; camera2CameraControl_from = null; resolutionFilter_createWithOnePreferredSize = null; cameraCharacteristics_infoSupportedHardwareLevel = null; cameraCharacteristics_sensorOrientation = null; + cameraCharacteristics_controlAvailableVideoStabilizationModes = null; camera2CameraInfo_from = null; displayOrientedMeteringPointFactory_new = null; } @@ -734,8 +748,7 @@ class _PigeonInternalInstanceManagerApi { PigeonInstanceManager? instanceManager, }) { { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.PigeonInternalInstanceManager.removeStrongReference', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -772,19 +785,17 @@ class _PigeonInternalInstanceManagerApi { } Future removeStrongReference(int identifier) async { - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.PigeonInternalInstanceManager.removeStrongReference'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -802,17 +813,15 @@ class _PigeonInternalInstanceManagerApi { /// /// This is typically called after a hot restart. Future clear() async { - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.PigeonInternalInstanceManager.clear'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1138,41 +1147,41 @@ class _PigeonCodec extends StandardMessageCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 129: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : InfoSupportedHardwareLevel.values[value]; case 130: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : AspectRatio.values[value]; case 131: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : CameraStateType.values[value]; case 132: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : LiveDataSupportedType.values[value]; case 133: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : VideoQuality.values[value]; case 134: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : MeteringMode.values[value]; case 135: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : LensFacing.values[value]; case 136: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : CameraXFlashMode.values[value]; case 137: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : ResolutionStrategyFallbackRule.values[value]; case 138: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : AspectRatioStrategyFallbackRule.values[value]; case 139: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : CameraStateErrorCode.values[value]; default: return super.readValueOfType(type, buffer); @@ -1213,20 +1222,18 @@ class CameraSize extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraSize; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraSize.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1274,8 +1281,7 @@ class CameraSize extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.CameraSize.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -1371,8 +1377,7 @@ class ResolutionInfo extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.ResolutionInfo.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -1468,20 +1473,18 @@ class CameraIntegerRange extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraIntegerRange; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraIntegerRange.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1531,8 +1534,7 @@ class CameraIntegerRange extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.CameraIntegerRange.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -1623,8 +1625,7 @@ class VideoRecordEvent extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.VideoRecordEvent.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -1701,8 +1702,7 @@ class VideoRecordEventStart extends VideoRecordEvent { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.VideoRecordEventStart.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -1779,8 +1779,7 @@ class VideoRecordEventFinalize extends VideoRecordEvent { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.VideoRecordEventFinalize.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -1861,8 +1860,7 @@ class MeteringPoint extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.MeteringPoint.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -1912,19 +1910,17 @@ class MeteringPoint extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecMeteringPoint; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.MeteringPoint.getSize'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1982,20 +1978,18 @@ class Observer extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecObserver; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Observer.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2057,12 +2051,11 @@ class Observer extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - 'dev.flutter.pigeon.camera_android_camerax.Observer.onChanged', - pigeonChannelCodec, - binaryMessenger: binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.camera_android_camerax.Observer.onChanged', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { @@ -2123,6 +2116,7 @@ class CameraInfo extends PigeonInternalProxyApiBaseClass { super.pigeon_binaryMessenger, super.pigeon_instanceManager, required this.sensorRotationDegrees, + required this.lensFacing, required this.exposureState, }); @@ -2133,6 +2127,9 @@ class CameraInfo extends PigeonInternalProxyApiBaseClass { /// (default) orientation. final int sensorRotationDegrees; + /// Returns the lens direction of this camera. + final LensFacing lensFacing; + /// Returns a ExposureState. final ExposureState exposureState; @@ -2140,7 +2137,11 @@ class CameraInfo extends PigeonInternalProxyApiBaseClass { bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, - CameraInfo Function(int sensorRotationDegrees, ExposureState exposureState)? + CameraInfo Function( + int sensorRotationDegrees, + LensFacing lensFacing, + ExposureState exposureState, + )? pigeon_newInstance, }) { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = @@ -2149,8 +2150,7 @@ class CameraInfo extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.CameraInfo.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2174,7 +2174,12 @@ class CameraInfo extends PigeonInternalProxyApiBaseClass { 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?); + final LensFacing? arg_lensFacing = (args[2] as LensFacing?); + assert( + arg_lensFacing != null, + 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraInfo.pigeon_newInstance was null, expected non-null LensFacing.', + ); + final ExposureState? arg_exposureState = (args[3] as ExposureState?); assert( arg_exposureState != null, 'Argument for dev.flutter.pigeon.camera_android_camerax.CameraInfo.pigeon_newInstance was null, expected non-null ExposureState.', @@ -2184,12 +2189,14 @@ class CameraInfo extends PigeonInternalProxyApiBaseClass { .addHostCreatedInstance( pigeon_newInstance?.call( arg_sensorRotationDegrees!, + arg_lensFacing!, arg_exposureState!, ) ?? CameraInfo.pigeon_detached( pigeon_binaryMessenger: pigeon_binaryMessenger, pigeon_instanceManager: pigeon_instanceManager, sensorRotationDegrees: arg_sensorRotationDegrees!, + lensFacing: arg_lensFacing!, exposureState: arg_exposureState!, ), arg_pigeon_instanceIdentifier!, @@ -2212,19 +2219,17 @@ class CameraInfo extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraInfo; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraInfo.getCameraState'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2248,19 +2253,17 @@ class CameraInfo extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraInfo; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraInfo.getZoomState'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2285,6 +2288,7 @@ class CameraInfo extends PigeonInternalProxyApiBaseClass { pigeon_binaryMessenger: pigeon_binaryMessenger, pigeon_instanceManager: pigeon_instanceManager, sensorRotationDegrees: sensorRotationDegrees, + lensFacing: lensFacing, exposureState: exposureState, ); } @@ -2327,14 +2331,13 @@ class CameraSelector extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraSelector; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraSelector.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [ pigeonVar_instanceIdentifier, @@ -2343,8 +2346,7 @@ class CameraSelector extends PigeonInternalProxyApiBaseClass { ], ); () async { - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2400,8 +2402,7 @@ class CameraSelector extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.CameraSelector.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2452,19 +2453,17 @@ class CameraSelector extends PigeonInternalProxyApiBaseClass { final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance .addDartCreatedInstance(pigeonVar_instance); () async { - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraSelector.defaultBackCamera'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2489,19 +2488,17 @@ class CameraSelector extends PigeonInternalProxyApiBaseClass { final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance .addDartCreatedInstance(pigeonVar_instance); () async { - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraSelector.defaultFrontCamera'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2523,19 +2520,17 @@ class CameraSelector extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraSelector; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraSelector.filter'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2595,8 +2590,7 @@ class ProcessCameraProvider extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2651,17 +2645,15 @@ class ProcessCameraProvider extends PigeonInternalProxyApiBaseClass { pigeon_instanceManager ?? PigeonInstanceManager.instance, ); final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.getInstance'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2685,19 +2677,17 @@ class ProcessCameraProvider extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProcessCameraProvider; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.getAvailableCameraInfos'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2724,19 +2714,17 @@ class ProcessCameraProvider extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProcessCameraProvider; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.bindToLifecycle'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2760,19 +2748,17 @@ class ProcessCameraProvider extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProcessCameraProvider; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.isBound'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2796,19 +2782,17 @@ class ProcessCameraProvider extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProcessCameraProvider; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.unbind'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2828,19 +2812,17 @@ class ProcessCameraProvider extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProcessCameraProvider; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ProcessCameraProvider.unbindAll'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -2889,8 +2871,7 @@ class UseCase extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.UseCase.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2976,8 +2957,7 @@ class Camera extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.Camera.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -3030,19 +3010,17 @@ class Camera extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCamera; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Camera.getCameraInfo'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -3105,20 +3083,18 @@ class SystemServicesManager extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecSystemServicesManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.SystemServicesManager.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -3190,8 +3166,7 @@ class SystemServicesManager extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.SystemServicesManager.onCameraError', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -3240,19 +3215,17 @@ class SystemServicesManager extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecSystemServicesManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.SystemServicesManager.requestCameraPermissions'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -3272,19 +3245,17 @@ class SystemServicesManager extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecSystemServicesManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.SystemServicesManager.getTempFilePath'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -3344,8 +3315,7 @@ class CameraPermissionsError extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.CameraPermissionsError.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -3445,20 +3415,18 @@ class DeviceOrientationManager extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecDeviceOrientationManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -3527,8 +3495,7 @@ class DeviceOrientationManager extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.onDeviceOrientationChanged', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -3574,19 +3541,17 @@ class DeviceOrientationManager extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecDeviceOrientationManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.startListeningForDeviceOrientationChange'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -3604,19 +3569,17 @@ class DeviceOrientationManager extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecDeviceOrientationManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.stopListeningForDeviceOrientationChange'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -3634,19 +3597,17 @@ class DeviceOrientationManager extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecDeviceOrientationManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.getDefaultDisplayRotation'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -3669,19 +3630,17 @@ class DeviceOrientationManager extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecDeviceOrientationManager; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.DeviceOrientationManager.getUiOrientation'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -3719,11 +3678,13 @@ class Preview extends UseCase { PigeonInstanceManager? pigeon_instanceManager, ResolutionSelector? resolutionSelector, int? targetRotation, + CameraIntegerRange? targetFpsRange, }) { if (PigeonOverrides.preview_new != null) { return PigeonOverrides.preview_new!( resolutionSelector: resolutionSelector, targetRotation: targetRotation, + targetFpsRange: targetFpsRange, ); } return Preview.pigeon_new( @@ -3731,6 +3692,7 @@ class Preview extends UseCase { pigeon_instanceManager: pigeon_instanceManager, resolutionSelector: resolutionSelector, targetRotation: targetRotation, + targetFpsRange: targetFpsRange, ); } @@ -3740,30 +3702,29 @@ class Preview extends UseCase { super.pigeon_instanceManager, this.resolutionSelector, int? targetRotation, + CameraIntegerRange? targetFpsRange, }) : 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 = + const 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, - ], + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, ); + final Future pigeonVar_sendFuture = pigeonVar_channel + .send([ + pigeonVar_instanceIdentifier, + resolutionSelector, + targetRotation, + targetFpsRange, + ]); () async { - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -3807,8 +3768,7 @@ class Preview extends UseCase { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.Preview.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -3867,19 +3827,17 @@ class Preview extends UseCase { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPreview; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Preview.setSurfaceProvider'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -3904,19 +3862,17 @@ class Preview extends UseCase { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPreview; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Preview.releaseSurfaceProvider'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -3935,19 +3891,17 @@ class Preview extends UseCase { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPreview; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Preview.getResolutionInfo'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -3966,19 +3920,17 @@ class Preview extends UseCase { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPreview; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Preview.setTargetRotation'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -3998,19 +3950,17 @@ class Preview extends UseCase { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPreview; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Preview.surfaceProducerHandlesCropAndRotation'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -4048,14 +3998,19 @@ class VideoCapture extends UseCase { BinaryMessenger? pigeon_binaryMessenger, PigeonInstanceManager? pigeon_instanceManager, required VideoOutput videoOutput, + CameraIntegerRange? targetFpsRange, }) { if (PigeonOverrides.videoCapture_withOutput != null) { - return PigeonOverrides.videoCapture_withOutput!(videoOutput: videoOutput); + return PigeonOverrides.videoCapture_withOutput!( + videoOutput: videoOutput, + targetFpsRange: targetFpsRange, + ); } return VideoCapture.pigeon_withOutput( pigeon_binaryMessenger: pigeon_binaryMessenger, pigeon_instanceManager: pigeon_instanceManager, videoOutput: videoOutput, + targetFpsRange: targetFpsRange, ); } @@ -4065,26 +4020,25 @@ class VideoCapture extends UseCase { super.pigeon_binaryMessenger, super.pigeon_instanceManager, required VideoOutput videoOutput, + CameraIntegerRange? targetFpsRange, }) : 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 = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.VideoCapture.withOutput'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [pigeonVar_instanceIdentifier, videoOutput], + [pigeonVar_instanceIdentifier, videoOutput, targetFpsRange], ); () async { - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -4124,8 +4078,7 @@ class VideoCapture extends UseCase { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.VideoCapture.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -4172,19 +4125,17 @@ class VideoCapture extends UseCase { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecVideoCapture; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.VideoCapture.getOutput'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -4208,19 +4159,17 @@ class VideoCapture extends UseCase { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecVideoCapture; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.VideoCapture.setTargetRotation'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -4269,8 +4218,7 @@ class VideoOutput extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.VideoOutput.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -4362,14 +4310,13 @@ class Recorder extends PigeonInternalProxyApiBaseClass implements VideoOutput { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecorder; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Recorder.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel .send([ pigeonVar_instanceIdentifier, @@ -4378,8 +4325,7 @@ class Recorder extends PigeonInternalProxyApiBaseClass implements VideoOutput { qualitySelector, ]); () async { - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -4419,8 +4365,7 @@ class Recorder extends PigeonInternalProxyApiBaseClass implements VideoOutput { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.Recorder.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -4467,19 +4412,17 @@ class Recorder extends PigeonInternalProxyApiBaseClass implements VideoOutput { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecorder; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Recorder.getAspectRatio'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -4503,19 +4446,17 @@ class Recorder extends PigeonInternalProxyApiBaseClass implements VideoOutput { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecorder; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Recorder.getTargetVideoEncodingBitRate'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -4539,19 +4480,17 @@ class Recorder extends PigeonInternalProxyApiBaseClass implements VideoOutput { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecorder; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Recorder.getQualitySelector'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -4575,19 +4514,17 @@ class Recorder extends PigeonInternalProxyApiBaseClass implements VideoOutput { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecorder; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Recorder.prepareRecording'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -4647,20 +4584,18 @@ class VideoRecordEventListener extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecVideoRecordEventListener; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.VideoRecordEventListener.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -4732,8 +4667,7 @@ class VideoRecordEventListener extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.VideoRecordEventListener.onEvent', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -4815,8 +4749,7 @@ class PendingRecording extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.PendingRecording.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -4863,19 +4796,17 @@ class PendingRecording extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPendingRecording; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.PendingRecording.withAudioEnabled'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, initialMuted], ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -4907,19 +4838,17 @@ class PendingRecording extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPendingRecording; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.PendingRecording.asPersistentRecording'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -4943,19 +4872,17 @@ class PendingRecording extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecPendingRecording; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.PendingRecording.start'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5012,8 +4939,7 @@ class Recording extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.Recording.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -5060,19 +4986,17 @@ class Recording extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecording; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Recording.close'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5091,19 +5015,17 @@ class Recording extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecording; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Recording.pause'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5122,19 +5044,17 @@ class Recording extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecording; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Recording.resume'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5155,19 +5075,17 @@ class Recording extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecRecording; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Recording.stop'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5230,14 +5148,13 @@ class ImageCapture extends UseCase { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageCapture; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageCapture.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [ pigeonVar_instanceIdentifier, @@ -5247,8 +5164,7 @@ class ImageCapture extends UseCase { ], ); () async { - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5292,8 +5208,7 @@ class ImageCapture extends UseCase { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.ImageCapture.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -5343,19 +5258,17 @@ class ImageCapture extends UseCase { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageCapture; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageCapture.setFlashMode'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5370,23 +5283,23 @@ class ImageCapture extends UseCase { } /// Captures a new still image for in memory access. - Future takePicture() async { + Future takePicture( + SystemServicesManager systemServicesManager, + ) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageCapture; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageCapture.takePicture'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( - [this], + [this, systemServicesManager], ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5410,19 +5323,17 @@ class ImageCapture extends UseCase { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageCapture; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageCapture.setTargetRotation'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5483,20 +5394,18 @@ class ResolutionStrategy extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecResolutionStrategy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5547,8 +5456,7 @@ class ResolutionStrategy extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -5600,19 +5508,17 @@ class ResolutionStrategy extends PigeonInternalProxyApiBaseClass { final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance .addDartCreatedInstance(pigeonVar_instance); () async { - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.highestAvailableStrategy'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5633,19 +5539,17 @@ class ResolutionStrategy extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecResolutionStrategy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.getBoundSize'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5665,19 +5569,17 @@ class ResolutionStrategy extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecResolutionStrategy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ResolutionStrategy.getFallbackRule'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5746,14 +5648,13 @@ class ResolutionSelector extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecResolutionSelector; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ResolutionSelector.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel .send([ pigeonVar_instanceIdentifier, @@ -5762,8 +5663,7 @@ class ResolutionSelector extends PigeonInternalProxyApiBaseClass { aspectRatioStrategy, ]); () async { - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5817,8 +5717,7 @@ class ResolutionSelector extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.ResolutionSelector.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -5876,19 +5775,17 @@ class ResolutionSelector extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecResolutionSelector; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ResolutionSelector.getAspectRatioStrategy'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -5959,14 +5856,13 @@ class AspectRatioStrategy extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAspectRatioStrategy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [ pigeonVar_instanceIdentifier, @@ -5975,8 +5871,7 @@ class AspectRatioStrategy extends PigeonInternalProxyApiBaseClass { ], ); () async { - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -6040,8 +5935,7 @@ class AspectRatioStrategy extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6093,19 +5987,17 @@ class AspectRatioStrategy extends PigeonInternalProxyApiBaseClass { final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance .addDartCreatedInstance(pigeonVar_instance); () async { - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.ratio_16_9FallbackAutoStrategy'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -6131,19 +6023,17 @@ class AspectRatioStrategy extends PigeonInternalProxyApiBaseClass { final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance .addDartCreatedInstance(pigeonVar_instance); () async { - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.ratio_4_3FallbackAutoStrategy'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -6165,19 +6055,17 @@ class AspectRatioStrategy extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAspectRatioStrategy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.getFallbackRule'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -6201,19 +6089,17 @@ class AspectRatioStrategy extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAspectRatioStrategy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.AspectRatioStrategy.getPreferredAspectRatio'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -6276,8 +6162,7 @@ class CameraState extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.CameraState.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6378,8 +6263,7 @@ class ExposureState extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.ExposureState.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6484,8 +6368,7 @@ class ZoomState extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.ZoomState.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6563,12 +6446,14 @@ class ImageAnalysis extends UseCase { PigeonInstanceManager? pigeon_instanceManager, ResolutionSelector? resolutionSelector, int? targetRotation, + CameraIntegerRange? targetFpsRange, int? outputImageFormat, }) { if (PigeonOverrides.imageAnalysis_new != null) { return PigeonOverrides.imageAnalysis_new!( resolutionSelector: resolutionSelector, targetRotation: targetRotation, + targetFpsRange: targetFpsRange, outputImageFormat: outputImageFormat, ); } @@ -6577,6 +6462,7 @@ class ImageAnalysis extends UseCase { pigeon_instanceManager: pigeon_instanceManager, resolutionSelector: resolutionSelector, targetRotation: targetRotation, + targetFpsRange: targetFpsRange, outputImageFormat: outputImageFormat, ); } @@ -6587,6 +6473,7 @@ class ImageAnalysis extends UseCase { super.pigeon_instanceManager, this.resolutionSelector, int? targetRotation, + CameraIntegerRange? targetFpsRange, int? outputImageFormat, }) : super.pigeon_detached() { final int pigeonVar_instanceIdentifier = pigeon_instanceManager @@ -6594,24 +6481,23 @@ class ImageAnalysis extends UseCase { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageAnalysis; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel .send([ pigeonVar_instanceIdentifier, resolutionSelector, targetRotation, + targetFpsRange, outputImageFormat, ]); () async { - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -6655,8 +6541,7 @@ class ImageAnalysis extends UseCase { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6706,19 +6591,17 @@ class ImageAnalysis extends UseCase { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageAnalysis; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.setAnalyzer'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -6737,19 +6620,17 @@ class ImageAnalysis extends UseCase { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageAnalysis; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.clearAnalyzer'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -6768,19 +6649,17 @@ class ImageAnalysis extends UseCase { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageAnalysis; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageAnalysis.setTargetRotation'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -6834,20 +6713,18 @@ class Analyzer extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecAnalyzer; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Analyzer.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -6909,12 +6786,11 @@ class Analyzer extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - 'dev.flutter.pigeon.camera_android_camerax.Analyzer.analyze', - pigeonChannelCodec, - binaryMessenger: binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.camera_android_camerax.Analyzer.analyze', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); if (pigeon_clearHandlers) { pigeonVar_channel.setMessageHandler(null); } else { @@ -6993,8 +6869,7 @@ class CameraStateStateError extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.CameraStateStateError.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7090,8 +6965,7 @@ class LiveData extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.LiveData.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7146,19 +7020,17 @@ class LiveData extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecLiveData; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.LiveData.observe'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -7177,19 +7049,17 @@ class LiveData extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecLiveData; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.LiveData.removeObservers'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -7208,19 +7078,17 @@ class LiveData extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecLiveData; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.LiveData.getValue'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -7285,8 +7153,7 @@ class ImageProxy extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.ImageProxy.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7355,19 +7222,17 @@ class ImageProxy extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageProxy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageProxy.getPlanes'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -7391,19 +7256,17 @@ class ImageProxy extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecImageProxy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageProxy.close'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -7456,8 +7319,7 @@ class ImageProxyUtils extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.ImageProxyUtils.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7519,19 +7381,17 @@ class ImageProxyUtils extends PigeonInternalProxyApiBaseClass { pigeon_instanceManager ?? PigeonInstanceManager.instance, ); final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ImageProxyUtils.getNv21Buffer'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [imageWidth, imageHeight, planes], ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -7599,8 +7459,7 @@ class PlaneProxy extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.PlaneProxy.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7715,20 +7574,18 @@ class QualitySelector extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecQualitySelector; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.QualitySelector.from'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -7777,20 +7634,18 @@ class QualitySelector extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecQualitySelector; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.QualitySelector.fromOrderedList'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -7830,8 +7685,7 @@ class QualitySelector extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.QualitySelector.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7891,19 +7745,17 @@ class QualitySelector extends PigeonInternalProxyApiBaseClass { pigeon_instanceManager ?? PigeonInstanceManager.instance, ); final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.QualitySelector.getResolution'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -7964,20 +7816,18 @@ class FallbackStrategy extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecFallbackStrategy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.higherQualityOrLowerThan'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -8024,20 +7874,18 @@ class FallbackStrategy extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecFallbackStrategy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.higherQualityThan'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -8084,20 +7932,18 @@ class FallbackStrategy extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecFallbackStrategy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.lowerQualityOrHigherThan'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -8144,20 +7990,18 @@ class FallbackStrategy extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecFallbackStrategy; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.lowerQualityThan'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -8197,8 +8041,7 @@ class FallbackStrategy extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.FallbackStrategy.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -8280,8 +8123,7 @@ class CameraControl extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.CameraControl.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -8328,19 +8170,17 @@ class CameraControl extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraControl; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraControl.enableTorch'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -8359,19 +8199,17 @@ class CameraControl extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraControl; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraControl.setZoomRatio'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -8393,19 +8231,17 @@ class CameraControl extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraControl; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraControl.startFocusAndMetering'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -8424,19 +8260,17 @@ class CameraControl extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraControl; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraControl.cancelFocusAndMetering'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -8455,19 +8289,17 @@ class CameraControl extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCameraControl; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraControl.setExposureCompensationIndex'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -8524,20 +8356,18 @@ class FocusMeteringActionBuilder extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecFocusMeteringActionBuilder; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -8586,20 +8416,18 @@ class FocusMeteringActionBuilder extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecFocusMeteringActionBuilder; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.withMode'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -8641,8 +8469,7 @@ class FocusMeteringActionBuilder extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -8689,19 +8516,17 @@ class FocusMeteringActionBuilder extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecFocusMeteringActionBuilder; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.addPoint'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -8720,19 +8545,17 @@ class FocusMeteringActionBuilder extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecFocusMeteringActionBuilder; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.addPointWithMode'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -8751,19 +8574,17 @@ class FocusMeteringActionBuilder extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecFocusMeteringActionBuilder; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.disableAutoCancel'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -8782,19 +8603,17 @@ class FocusMeteringActionBuilder extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecFocusMeteringActionBuilder; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.FocusMeteringActionBuilder.build'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -8870,8 +8689,7 @@ class FocusMeteringAction extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.FocusMeteringAction.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -8988,8 +8806,7 @@ class FocusMeteringResult extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.FocusMeteringResult.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -9070,6 +8887,14 @@ class CaptureRequest extends PigeonInternalProxyApiBaseClass { /// This key is available on all devices. static final CaptureRequestKey _controlAELock = pigeonVar_controlAELock(); + /// Whether video stabilization is active. + /// + /// Value is int. + /// + /// This key is available on all devices. + static final CaptureRequestKey _controlVideoStabilizationMode = + pigeonVar_controlVideoStabilizationMode(); + /// Whether auto-exposure (AE) is currently locked to its latest calculated /// values. /// @@ -9079,6 +8904,15 @@ class CaptureRequest extends PigeonInternalProxyApiBaseClass { static CaptureRequestKey get controlAELock => PigeonOverrides.captureRequest_controlAELock ?? _controlAELock; + /// Whether video stabilization is active. + /// + /// Value is int. + /// + /// This key is available on all devices. + static CaptureRequestKey get controlVideoStabilizationMode => + PigeonOverrides.captureRequest_controlVideoStabilizationMode ?? + _controlVideoStabilizationMode; + static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, @@ -9091,8 +8925,7 @@ class CaptureRequest extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.CaptureRequest.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -9144,19 +8977,53 @@ class CaptureRequest extends PigeonInternalProxyApiBaseClass { final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance .addDartCreatedInstance(pigeonVar_instance); () async { - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CaptureRequest.controlAELock'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final 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 CaptureRequestKey pigeonVar_controlVideoStabilizationMode() { + 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 pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.CaptureRequest.controlVideoStabilizationMode'; + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], + ); + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -9208,8 +9075,7 @@ class CaptureRequestKey extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.CaptureRequestKey.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -9290,20 +9156,18 @@ class CaptureRequestOptions extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCaptureRequestOptions; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CaptureRequestOptions.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -9345,8 +9209,7 @@ class CaptureRequestOptions extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.CaptureRequestOptions.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -9394,19 +9257,17 @@ class CaptureRequestOptions extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCaptureRequestOptions; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CaptureRequestOptions.getCaptureRequestOption'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -9464,20 +9325,18 @@ class Camera2CameraControl extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCamera2CameraControl; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Camera2CameraControl.from'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -9519,8 +9378,7 @@ class Camera2CameraControl extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.Camera2CameraControl.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -9568,19 +9426,17 @@ class Camera2CameraControl extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCamera2CameraControl; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Camera2CameraControl.addCaptureRequestOptions'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -9636,20 +9492,18 @@ class ResolutionFilter extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecResolutionFilter; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.ResolutionFilter.createWithOnePreferredSize'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -9689,8 +9543,7 @@ class ResolutionFilter extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.ResolutionFilter.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -9768,8 +9621,7 @@ class CameraCharacteristicsKey extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.CameraCharacteristicsKey.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -9851,6 +9703,16 @@ class CameraCharacteristics extends PigeonInternalProxyApiBaseClass { static final CameraCharacteristicsKey _sensorOrientation = pigeonVar_sensorOrientation(); + /// List of video stabilization modes for android.control.videoStabilizationMode + /// that are supported by this camera device. + /// + /// Value is `ControlAvailableVideoStabilizationMode`. + /// + /// This key is available on all devices. + static final CameraCharacteristicsKey + _controlAvailableVideoStabilizationModes = + pigeonVar_controlAvailableVideoStabilizationModes(); + /// Generally classifies the overall set of the camera device functionality. /// /// Value is `InfoSupportedHardwareLevel`. @@ -9870,6 +9732,17 @@ class CameraCharacteristics extends PigeonInternalProxyApiBaseClass { PigeonOverrides.cameraCharacteristics_sensorOrientation ?? _sensorOrientation; + /// List of video stabilization modes for android.control.videoStabilizationMode + /// that are supported by this camera device. + /// + /// Value is `ControlAvailableVideoStabilizationMode`. + /// + /// This key is available on all devices. + static CameraCharacteristicsKey get controlAvailableVideoStabilizationModes => + PigeonOverrides + .cameraCharacteristics_controlAvailableVideoStabilizationModes ?? + _controlAvailableVideoStabilizationModes; + static void pigeon_setUpMessageHandlers({ bool pigeon_clearHandlers = false, BinaryMessenger? pigeon_binaryMessenger, @@ -9882,8 +9755,7 @@ class CameraCharacteristics extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.CameraCharacteristics.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -9935,19 +9807,17 @@ class CameraCharacteristics extends PigeonInternalProxyApiBaseClass { final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance .addDartCreatedInstance(pigeonVar_instance); () async { - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraCharacteristics.infoSupportedHardwareLevel'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -9973,19 +9843,54 @@ class CameraCharacteristics extends PigeonInternalProxyApiBaseClass { final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance .addDartCreatedInstance(pigeonVar_instance); () async { - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.CameraCharacteristics.sensorOrientation'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final 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_controlAvailableVideoStabilizationModes() { + 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 pigeonVar_channelName = + 'dev.flutter.pigeon.camera_android_camerax.CameraCharacteristics.controlAvailableVideoStabilizationModes'; + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [pigeonVar_instanceIdentifier], + ); + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -10042,20 +9947,18 @@ class Camera2CameraInfo extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCamera2CameraInfo; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Camera2CameraInfo.from'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -10097,8 +10000,7 @@ class Camera2CameraInfo extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.Camera2CameraInfo.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -10145,19 +10047,17 @@ class Camera2CameraInfo extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCamera2CameraInfo; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Camera2CameraInfo.getCameraId'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -10181,19 +10081,17 @@ class Camera2CameraInfo extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecCamera2CameraInfo; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.Camera2CameraInfo.getCameraCharacteristic'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -10247,8 +10145,7 @@ class MeteringPointFactory extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.MeteringPointFactory.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -10295,19 +10192,17 @@ class MeteringPointFactory extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecMeteringPointFactory; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.MeteringPointFactory.createPoint'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -10335,19 +10230,17 @@ class MeteringPointFactory extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecMeteringPointFactory; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.MeteringPointFactory.createPointWithSize'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -10423,20 +10316,18 @@ class DisplayOrientedMeteringPointFactory extends MeteringPointFactory { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecDisplayOrientedMeteringPointFactory; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.camera_android_camerax.DisplayOrientedMeteringPointFactory.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -10477,8 +10368,7 @@ class DisplayOrientedMeteringPointFactory extends MeteringPointFactory { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_android_camerax.DisplayOrientedMeteringPointFactory.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, diff --git a/packages/camera/camera_android_camerax/lib/src/camerax_proxy.dart b/packages/camera/camera_android_camerax/lib/src/camerax_proxy.dart deleted file mode 100644 index 3885e720387f..000000000000 --- a/packages/camera/camera_android_camerax/lib/src/camerax_proxy.dart +++ /dev/null @@ -1,416 +0,0 @@ -// Copyright 2013 The Flutter Authors -// 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'; - -// 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. -/// -/// 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 an [CameraXProxy]. - CameraXProxy({ - 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, - this.getNv21BufferImageProxyUtils = ImageProxyUtils.getNv21Buffer, - }); - - /// 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, - CameraInfo? cameraInfoForFilter, - 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, - 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, - int? outputImageFormat, - 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; - - /// Calls to [ImageProxyUtils.getNv21Buffer]. - final Future Function( - int imageWidth, - int imageHeight, - List planes, { - BinaryMessenger? pigeon_binaryMessenger, - PigeonInstanceManager? pigeon_instanceManager, - }) - getNv21BufferImageProxyUtils; - - 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/pigeons/camerax_library.dart b/packages/camera/camera_android_camerax/pigeons/camerax_library.dart index 8d0a05fbf073..611157f65248 100644 --- a/packages/camera/camera_android_camerax/pigeons/camerax_library.dart +++ b/packages/camera/camera_android_camerax/pigeons/camerax_library.dart @@ -112,7 +112,7 @@ enum CameraStateType { unknown, } -/// The types (T) properly wrapped to be used as a LiveData. +/// 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. @@ -251,6 +251,9 @@ abstract class CameraInfo { /// (default) orientation. late int sensorRotationDegrees; + /// Returns the lens direction of this camera. + late LensFacing lensFacing; + /// Returns a ExposureState. late ExposureState exposureState; @@ -416,7 +419,7 @@ abstract class DeviceOrientationManager { ), ) abstract class Preview extends UseCase { - Preview(int? targetRotation); + Preview(int? targetRotation, CameraIntegerRange? targetFpsRange); late final ResolutionSelector? resolutionSelector; @@ -455,7 +458,10 @@ abstract class Preview extends UseCase { ) abstract class VideoCapture extends UseCase { /// Create a `VideoCapture` associated with the given `VideoOutput`. - VideoCapture.withOutput(VideoOutput videoOutput); + VideoCapture.withOutput( + VideoOutput videoOutput, + CameraIntegerRange? targetFpsRange, + ); /// Gets the VideoOutput associated with this VideoCapture. VideoOutput getOutput(); @@ -601,7 +607,7 @@ abstract class ImageCapture extends UseCase { /// Captures a new still image for in memory access. @async - String takePicture(); + String takePicture(SystemServicesManager systemServicesManager); /// Sets the desired rotation of the output image. void setTargetRotation(int rotation); @@ -803,7 +809,11 @@ abstract class ZoomState { ), ) abstract class ImageAnalysis extends UseCase { - ImageAnalysis(int? targetRotation, int? outputImageFormat); + ImageAnalysis( + int? targetRotation, + CameraIntegerRange? targetFpsRange, + int? outputImageFormat, + ); late final ResolutionSelector? resolutionSelector; @@ -1136,6 +1146,14 @@ abstract class CaptureRequest { /// This key is available on all devices. @static late CaptureRequestKey controlAELock; + + /// Whether video stabilization is active. + /// + /// Value is int. + /// + /// This key is available on all devices. + @static + late CaptureRequestKey controlVideoStabilizationMode; } /// A Key is used to do capture request field lookups with CaptureRequest.get or @@ -1233,6 +1251,15 @@ abstract class CameraCharacteristics { /// This key is available on all devices. @static late CameraCharacteristicsKey sensorOrientation; + + /// List of video stabilization modes for android.control.videoStabilizationMode + /// that are supported by this camera device. + /// + /// Value is `ControlAvailableVideoStabilizationMode`. + /// + /// This key is available on all devices. + @static + late CameraCharacteristicsKey controlAvailableVideoStabilizationModes; } /// An interface for retrieving Camera2-related camera information. diff --git a/packages/camera/camera_android_camerax/pubspec.yaml b/packages/camera/camera_android_camerax/pubspec.yaml index dc86c19fe67c..2dda62c4a153 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.24+3 +version: 0.7.1+2 environment: sdk: ^3.9.0 @@ -19,7 +19,7 @@ flutter: dependencies: async: ^2.5.0 - camera_platform_interface: ^2.11.0 + camera_platform_interface: ^2.12.0 flutter: sdk: flutter meta: ^1.7.0 @@ -31,7 +31,7 @@ dev_dependencies: sdk: flutter leak_tracker_flutter_testing: any mockito: ^5.4.4 - pigeon: ^26.1.0 + pigeon: ^26.1.4 topics: - camera 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 3df67d25f35b..71ed3d58ccde 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 @@ -8,10 +8,9 @@ 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/camerax_library.dart'; -import 'package:camera_android_camerax/src/camerax_proxy.dart'; import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:flutter/services.dart' - show BinaryMessenger, DeviceOrientation, PlatformException, Uint8List; + show DeviceOrientation, PlatformException, Uint8List; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; @@ -30,7 +29,6 @@ import 'android_camera_camerax_test.mocks.dart'; MockSpec(), MockSpec(), MockSpec(), - MockSpec(), MockSpec(), MockSpec(), MockSpec(), @@ -66,42 +64,42 @@ import 'android_camera_camerax_test.mocks.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); + setUp(() { + PigeonOverrides.pigeon_reset(); + GenericsPigeonOverrides.reset(); + }); + /// Helper method for testing sending/receiving CameraErrorEvents. Future testCameraClosingObserver( AndroidCameraCameraX camera, int cameraId, Observer observer, ) async { - final CameraStateStateError testCameraStateError = - CameraStateStateError.pigeon_detached( - code: CameraStateErrorCode.doNotDisturbModeEnabled, - pigeon_instanceManager: PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), - ); + final testCameraStateError = CameraStateStateError.pigeon_detached( + code: CameraStateErrorCode.doNotDisturbModeEnabled, + ); final Stream cameraClosingEventStream = camera .onCameraClosing(cameraId); - final StreamQueue cameraClosingStreamQueue = - StreamQueue(cameraClosingEventStream); + final cameraClosingStreamQueue = StreamQueue( + cameraClosingEventStream, + ); final Stream cameraErrorEventStream = camera .onCameraError(cameraId); - final StreamQueue cameraErrorStreamQueue = - StreamQueue(cameraErrorEventStream); + final cameraErrorStreamQueue = StreamQueue( + cameraErrorEventStream, + ); observer.onChanged( observer, CameraState.pigeon_detached( type: CameraStateType.closing, error: testCameraStateError, - pigeon_instanceManager: PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), ), ); - final bool cameraClosingEventSent = + final cameraClosingEventSent = await cameraClosingStreamQueue.next == CameraClosingEvent(cameraId); - final bool cameraErrorSent = + final cameraErrorSent = await cameraErrorStreamQueue.next == CameraErrorEvent( cameraId, @@ -114,444 +112,272 @@ void main() { return cameraClosingEventSent && cameraErrorSent; } - /// CameraXProxy for testing functionality related to the configuration + /// Set up testing functionality related to the configuration /// of CameraX UseCases. - CameraXProxy getProxyForTestingUseCaseConfiguration( + void setUpOverridesForTestingUseCaseConfiguration( MockProcessCameraProvider mockProcessCameraProvider, { - ResolutionFilter Function({ - required CameraSize preferredSize, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - })? + ResolutionFilter Function({required CameraSize preferredSize})? createWithOnePreferredSizeResolutionFilter, - FallbackStrategy Function({ - required VideoQuality quality, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - })? + FallbackStrategy Function({required VideoQuality quality})? 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, + CameraIntegerRange? targetFpsRange, ResolutionSelector? resolutionSelector, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, })? newPreview, + VideoCapture Function({ + required VideoOutput videoOutput, + CameraIntegerRange? targetFpsRange, + })? + withOutputVideoCapture, ImageAnalysis Function({ - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, ResolutionSelector? resolutionSelector, int? outputImageFormat, int? targetRotation, + CameraIntegerRange? targetFpsRange, })? newImageAnalysis, - Analyzer Function({ - required void Function(Analyzer, ImageProxy) analyze, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - })? + Analyzer Function({required void Function(Analyzer, ImageProxy) analyze})? newAnalyzer, - Future Function( + Future Function( int imageWidth, int imageHeight, - List planes, { - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - })? + List planes, + )? getNv21BufferImageProxyUtils, }) { - 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, - CameraInfo? cameraInfoForFilter, - // 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(); - final ResolutionInfo testResolutionInfo = - ResolutionInfo.pigeon_detached(resolution: MockCameraSize()); - when( - mockPreview.surfaceProducerHandlesCropAndRotation(), - ).thenAnswer((_) async => false); - when(mockPreview.resolutionSelector).thenReturn(resolutionSelector); - when( - mockPreview.getResolutionInfo(), - ).thenAnswer((_) async => testResolutionInfo); - 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: - newImageAnalysis ?? - ({ - int? targetRotation, - int? outputImageFormat, - 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(); - }, - newAnalyzer: - 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(); - }, - getNv21BufferImageProxyUtils: - getNv21BufferImageProxyUtils ?? - ( - int imageWidth, - int imageHeight, - List planes, { - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - }) { - return Future.value(Uint8List(0)); - }, - ); + PigeonOverrides.processCameraProvider_getInstance = () async { + return mockProcessCameraProvider; + }; + PigeonOverrides.cameraSelector_new = + ({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) { + switch (requireLensFacing) { + case LensFacing.front: + return MockCameraSelector(); + case LensFacing.back: + case LensFacing.external: + case LensFacing.unknown: + case null: + } - return proxy; + return MockCameraSelector(); + }; + PigeonOverrides.preview_new = + newPreview ?? + ({ + int? targetRotation, + CameraIntegerRange? targetFpsRange, + ResolutionSelector? resolutionSelector, + }) { + final mockPreview = MockPreview(); + final testResolutionInfo = ResolutionInfo.pigeon_detached( + resolution: MockCameraSize(), + ); + when( + mockPreview.surfaceProducerHandlesCropAndRotation(), + ).thenAnswer((_) async => false); + when(mockPreview.resolutionSelector).thenReturn(resolutionSelector); + when( + mockPreview.getResolutionInfo(), + ).thenAnswer((_) async => testResolutionInfo); + return mockPreview; + }; + PigeonOverrides.imageCapture_new = + ({ + int? targetRotation, + CameraXFlashMode? flashMode, + ResolutionSelector? resolutionSelector, + }) { + final mockImageCapture = MockImageCapture(); + when( + mockImageCapture.resolutionSelector, + ).thenReturn(resolutionSelector); + return mockImageCapture; + }; + PigeonOverrides.recorder_new = + ({ + int? aspectRatio, + int? targetVideoEncodingBitRate, + QualitySelector? qualitySelector, + }) { + final mockRecorder = MockRecorder(); + when( + mockRecorder.getQualitySelector(), + ).thenAnswer((_) async => qualitySelector ?? MockQualitySelector()); + return mockRecorder; + }; + PigeonOverrides.videoCapture_withOutput = + withOutputVideoCapture ?? + ({ + required VideoOutput videoOutput, + CameraIntegerRange? targetFpsRange, + }) { + return MockVideoCapture(); + }; + PigeonOverrides.imageAnalysis_new = + newImageAnalysis ?? + ({ + int? targetRotation, + CameraIntegerRange? targetFpsRange, + int? outputImageFormat, + ResolutionSelector? resolutionSelector, + }) { + final mockImageAnalysis = MockImageAnalysis(); + when( + mockImageAnalysis.resolutionSelector, + ).thenReturn(resolutionSelector); + return mockImageAnalysis; + }; + PigeonOverrides.resolutionStrategy_new = + ({ + required CameraSize boundSize, + required ResolutionStrategyFallbackRule fallbackRule, + }) { + final resolutionStrategy = MockResolutionStrategy(); + when( + resolutionStrategy.getBoundSize(), + ).thenAnswer((_) async => boundSize); + when( + resolutionStrategy.getFallbackRule(), + ).thenAnswer((_) async => fallbackRule); + return resolutionStrategy; + }; + PigeonOverrides.resolutionSelector_new = + ({ + AspectRatioStrategy? aspectRatioStrategy, + ResolutionStrategy? resolutionStrategy, + ResolutionFilter? resolutionFilter, + }) { + final mockResolutionSelector = MockResolutionSelector(); + when(mockResolutionSelector.getAspectRatioStrategy()).thenAnswer( + (_) async => + aspectRatioStrategy ?? + AspectRatioStrategy.ratio_4_3FallbackAutoStrategy, + ); + when( + mockResolutionSelector.resolutionStrategy, + ).thenReturn(resolutionStrategy); + when( + mockResolutionSelector.resolutionFilter, + ).thenReturn(resolutionFilter); + return mockResolutionSelector; + }; + PigeonOverrides.qualitySelector_from = + fromQualitySelector ?? + ({required VideoQuality quality, FallbackStrategy? fallbackStrategy}) { + return MockQualitySelector(); + }; + GenericsPigeonOverrides.observerNew = + ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; + PigeonOverrides.systemServicesManager_new = + ({ + required void Function(SystemServicesManager, String) onCameraError, + }) { + return MockSystemServicesManager(); + }; + PigeonOverrides.deviceOrientationManager_new = + ({ + required void Function(DeviceOrientationManager, String) + onDeviceOrientationChanged, + }) { + final manager = MockDeviceOrientationManager(); + when(manager.getUiOrientation()).thenAnswer((_) async { + return 'PORTRAIT_UP'; + }); + return manager; + }; + PigeonOverrides.aspectRatioStrategy_new = + ({ + required AspectRatio preferredAspectRatio, + required AspectRatioStrategyFallbackRule fallbackRule, + }) { + final mockAspectRatioStrategy = MockAspectRatioStrategy(); + when( + mockAspectRatioStrategy.getFallbackRule(), + ).thenAnswer((_) async => fallbackRule); + when( + mockAspectRatioStrategy.getPreferredAspectRatio(), + ).thenAnswer((_) async => preferredAspectRatio); + return mockAspectRatioStrategy; + }; + PigeonOverrides.resolutionFilter_createWithOnePreferredSize = + createWithOnePreferredSizeResolutionFilter ?? + ({required CameraSize preferredSize}) => MockResolutionFilter(); + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { + final camera2cameraInfo = MockCamera2CameraInfo(); + when( + camera2cameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => 90); + return camera2cameraInfo; + }; + PigeonOverrides.cameraSize_new = + ({required int width, required int height}) { + return CameraSize.pigeon_detached(width: width, height: height); + }; + PigeonOverrides.cameraCharacteristics_sensorOrientation = + MockCameraCharacteristicsKey(); + PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan = + lowerQualityOrHigherThanFallbackStrategy ?? + ({required VideoQuality quality}) { + return MockFallbackStrategy(); + }; + PigeonOverrides.resolutionStrategy_highestAvailableStrategy = + highestAvailableStrategyResolutionStrategy; + PigeonOverrides.aspectRatioStrategy_ratio_4_3FallbackAutoStrategy = + ratio_4_3FallbackAutoStrategyAspectRatioStrategy; + PigeonOverrides.fallbackStrategy_lowerQualityThan = + ({required VideoQuality quality}) { + return MockFallbackStrategy(); + }; + PigeonOverrides.analyzer_new = + newAnalyzer ?? + ({required void Function(Analyzer, ImageProxy) analyze}) { + return MockAnalyzer(); + }; + PigeonOverrides.imageProxyUtils_getNv21Buffer = + getNv21BufferImageProxyUtils ?? + (int imageWidth, int imageHeight, List planes) { + return Future.value(Uint8List(0)); + }; } - /// CameraXProxy for testing exposure and focus related controls. + /// Set up overrides 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({ + void setUpOverridesForExposureAndFocus({ 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 dynamic 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: + }) { + PigeonOverrides.displayOrientedMeteringPointFactory_new = newDisplayOrientedMeteringPointFactory ?? ({ - required CameraInfo cameraInfo, + required dynamic 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(); + final mockFactory = MockDisplayOrientedMeteringPointFactory(); when(mockFactory.createPoint(any, any)).thenAnswer( (Invocation invocation) async => TestMeteringPoint.detached( x: invocation.positionalArguments[0]! as double, @@ -566,28 +392,18 @@ void main() { ), ); return mockFactory; - }, - withModeFocusMeteringActionBuilder: + }; + PigeonOverrides.focusMeteringActionBuilder_withMode = 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; + ({required MeteringPoint point, required MeteringMode mode}) { + final mockBuilder = MockFocusMeteringActionBuilder(); + var disableAutoCancelCalled = false; when(mockBuilder.disableAutoCancel()).thenAnswer((_) async { disableAutoCancelCalled = true; }); - final List meteringPointsAe = []; - final List meteringPointsAf = []; - final List meteringPointsAwb = []; + final meteringPointsAe = []; + final meteringPointsAf = []; + final meteringPointsAwb = []; switch (mode) { case MeteringMode.ae: @@ -623,76 +439,52 @@ void main() { meteringPointsAf: meteringPointsAf, meteringPointsAwb: meteringPointsAwb, isAutoCancelEnabled: !disableAutoCancelCalled, - pigeon_instanceManager: testInstanceManager, ), ); return mockBuilder; - }, - ); + }; + } - /// CameraXProxy for testing setting focus and exposure points. + /// Set up overrides for testing setting focus and exposure points. /// /// Modifies the retrieval of a [Camera2CameraControl] instance to depend on /// interaction with expected [cameraControl] instance and modifies creation /// of [CaptureRequestOptions] to return objects detached from a native object. - CameraXProxy getProxyForSettingFocusandExposurePoints( + void setUpOverridesForSettingFocusandExposurePoints( 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 dynamic 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(); + setUpOverridesForExposureAndFocus(); - final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); if (withModeFocusMeteringActionBuilder != null) { - proxy.withModeFocusMeteringActionBuilder = + PigeonOverrides.focusMeteringActionBuilder_withMode = withModeFocusMeteringActionBuilder; } if (newDisplayOrientedMeteringPointFactory != null) { - proxy.newDisplayOrientedMeteringPointFactory = + PigeonOverrides.displayOrientedMeteringPointFactory_new = 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.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(); + + PigeonOverrides.camera2CameraControl_from = + ({required CameraControl cameraControl}) => + cameraControl == cameraControlForComparison + ? camera2cameraControl + : Camera2CameraControl.pigeon_detached(); + + PigeonOverrides.captureRequestOptions_new = + ({required Map options}) { + final mockCaptureRequestOptions = MockCaptureRequestOptions(); options.forEach((CaptureRequestKey key, Object? value) { when( mockCaptureRequestOptions.getCaptureRequestOption(key), @@ -700,115 +492,72 @@ void main() { }); return mockCaptureRequestOptions; }; - final CaptureRequestKey controlAeLock = CaptureRequestKey.pigeon_detached( - pigeon_instanceManager: testInstanceManager, - ); - proxy.controlAELockCaptureRequest = () => controlAeLock; - - return proxy; + PigeonOverrides.captureRequest_controlAELock = + CaptureRequestKey.pigeon_detached(); } test( 'Should fetch CameraDescription instances for available cameras', () async { // Arrange - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final List returnData = [ + final camera = AndroidCameraCameraX(); + final returnData = [ { - 'name': 'Camera 0', + 'name': '0', 'lensFacing': 'back', 'sensorOrientation': 0, }, { - 'name': 'Camera 1', + 'name': '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(); + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockFrontCameraInfo = MockCameraInfo(); + final mockBackCameraInfo = MockCameraInfo(); // 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, - CameraInfo? cameraInfoForFilter, - // 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: - } - - 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(); - }, - ); + PigeonOverrides.processCameraProvider_getInstance = () async => + mockProcessCameraProvider; + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { + final camera2cameraInfo = MockCamera2CameraInfo(); + var cameraId = ''; + if (cameraInfo == mockBackCameraInfo) { + cameraId = '0'; + } else if (cameraInfo == mockFrontCameraInfo) { + cameraId = '1'; + } + when(camera2cameraInfo.getCameraId()).thenAnswer((_) async => cameraId); + return camera2cameraInfo; + }; + PigeonOverrides.systemServicesManager_new = + ({ + required void Function(SystemServicesManager, String) onCameraError, + }) { + 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(mockBackCameraInfo.lensFacing).thenReturn(LensFacing.back); + when(mockFrontCameraInfo.sensorRotationDegrees).thenReturn(90); + when(mockFrontCameraInfo.lensFacing).thenReturn(LensFacing.front); final List cameraDescriptions = await camera .availableCameras(); expect(cameraDescriptions.length, returnData.length); - for (int i = 0; i < returnData.length; i++) { + for (var i = 0; i < returnData.length; i++) { final Map typedData = (returnData[i] as Map).cast(); - final CameraDescription cameraDescription = CameraDescription( + final cameraDescription = CameraDescription( name: typedData['name']! as String, lensDirection: (typedData['lensFacing']! as String) == 'front' ? CameraLensDirection.front @@ -823,277 +572,179 @@ void main() { 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(); + final camera = AndroidCameraCameraX(); const CameraLensDirection testLensDirection = CameraLensDirection.back; - const int testSensorOrientation = 90; - const CameraDescription testCameraDescription = CameraDescription( + const testSensorOrientation = 90; + const testCameraDescription = CameraDescription( name: 'cameraName', lensDirection: testLensDirection, sensorOrientation: testSensorOrientation, ); - const int testSurfaceTextureId = 6; + const 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 MockSystemServicesManager mockSystemServicesManager = - MockSystemServicesManager(); - final MockCameraCharacteristicsKey mockCameraCharacteristicsKey = - MockCameraCharacteristicsKey(); - - bool cameraPermissionsRequested = false; - bool startedListeningForDeviceOrientationChanges = false; - - 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, - CameraInfo? cameraInfoForFilter, - // 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: - } + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockPreview = MockPreview(); + final mockBackCameraSelector = MockCameraSelector(); + final mockImageCapture = MockImageCapture(); + final mockImageAnalysis = MockImageAnalysis(); + final mockRecorder = MockRecorder(); + final mockVideoCapture = MockVideoCapture(); + final mockCamera = MockCamera(); + final mockCameraInfo = MockCameraInfo(); + final mockLiveCameraState = MockLiveCameraState(); + final mockSystemServicesManager = MockSystemServicesManager(); + final mockCameraCharacteristicsKey = MockCameraCharacteristicsKey(); + + var cameraPermissionsRequested = false; + var startedListeningForDeviceOrientationChanges = false; + + PigeonOverrides.processCameraProvider_getInstance = () async { + return mockProcessCameraProvider; + }; + PigeonOverrides.cameraSelector_new = + ({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) { + 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, - int? outputImageFormat, - 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 { + return mockBackCameraSelector; + }; + PigeonOverrides.preview_new = + ({ + int? targetRotation, + CameraIntegerRange? targetFpsRange, + ResolutionSelector? resolutionSelector, + }) { + return mockPreview; + }; + PigeonOverrides.imageCapture_new = + ({ + int? targetRotation, + CameraXFlashMode? flashMode, + ResolutionSelector? resolutionSelector, + }) { + return mockImageCapture; + }; + PigeonOverrides.recorder_new = + ({ + int? aspectRatio, + int? targetVideoEncodingBitRate, + QualitySelector? qualitySelector, + }) { + return mockRecorder; + }; + PigeonOverrides.videoCapture_withOutput = + ({ + required VideoOutput videoOutput, + CameraIntegerRange? targetFpsRange, + }) { + return mockVideoCapture; + }; + PigeonOverrides.imageAnalysis_new = + ({ + int? targetRotation, + CameraIntegerRange? targetFpsRange, + int? outputImageFormat, + ResolutionSelector? resolutionSelector, + }) { + return mockImageAnalysis; + }; + PigeonOverrides.resolutionStrategy_new = + ({ + required CameraSize boundSize, + required ResolutionStrategyFallbackRule fallbackRule, + }) { + return MockResolutionStrategy(); + }; + PigeonOverrides.resolutionSelector_new = + ({ + AspectRatioStrategy? aspectRatioStrategy, + ResolutionStrategy? resolutionStrategy, + ResolutionFilter? resolutionFilter, + }) { + return MockResolutionSelector(); + }; + PigeonOverrides.qualitySelector_from = + ({ + required VideoQuality quality, + FallbackStrategy? fallbackStrategy, + }) { + return MockQualitySelector(); + }; + GenericsPigeonOverrides.observerNew = + ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; + PigeonOverrides.systemServicesManager_new = + ({ + required void Function(SystemServicesManager, String) onCameraError, + }) { + when( + mockSystemServicesManager.requestCameraPermissions(any), + ).thenAnswer((_) async { + cameraPermissionsRequested = true; + return null; + }); + return mockSystemServicesManager; + }; + PigeonOverrides.deviceOrientationManager_new = + ({ + required void Function(DeviceOrientationManager, String) + onDeviceOrientationChanged, + }) { + final 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(); - }, - ); + }, + ); + when(manager.getUiOrientation()).thenAnswer((_) async { + return 'PORTRAIT_UP'; + }); + return manager; + }; + PigeonOverrides.aspectRatioStrategy_new = + ({ + required AspectRatio preferredAspectRatio, + required AspectRatioStrategyFallbackRule fallbackRule, + }) { + return MockAspectRatioStrategy(); + }; + PigeonOverrides.resolutionFilter_createWithOnePreferredSize = + ({required CameraSize preferredSize}) { + return MockResolutionFilter(); + }; + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { + final camera2cameraInfo = MockCamera2CameraInfo(); + when( + camera2cameraInfo.getCameraCharacteristic( + mockCameraCharacteristicsKey, + ), + ).thenAnswer((_) async => testSensorOrientation); + return camera2cameraInfo; + }; + PigeonOverrides.cameraSize_new = + ({required int width, required int height}) { + return MockCameraSize(); + }; + PigeonOverrides.cameraCharacteristics_sensorOrientation = + mockCameraCharacteristicsKey; + PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan = + ({required VideoQuality quality}) { + return MockFallbackStrategy(); + }; camera.processCameraProvider = mockProcessCameraProvider; + PigeonOverrides.cameraIntegerRange_new = + CameraIntegerRange.pigeon_detached; when( mockPreview.setSurfaceProvider(mockSystemServicesManager), @@ -1148,22 +799,21 @@ void main() { test( 'createCamera and initializeCamera properly set preset resolution selection strategy for non-video capture use cases', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final camera = AndroidCameraCameraX(); const CameraLensDirection testLensDirection = CameraLensDirection.back; - const int testSensorOrientation = 90; - const CameraDescription testCameraDescription = CameraDescription( + const testSensorOrientation = 90; + const testCameraDescription = CameraDescription( name: 'cameraName', lensDirection: testLensDirection, sensorOrientation: testSensorOrientation, ); - const bool enableAudio = true; - final MockCamera mockCamera = MockCamera(); + const enableAudio = true; + final mockCamera = MockCamera(); // Mock/Detached objects for (typically attached) objects created by // createCamera. - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockCameraInfo = MockCameraInfo(); when( mockProcessCameraProvider.bindToLifecycle(any, any), @@ -1176,9 +826,7 @@ void main() { // Tell plugin to create mock/detached objects for testing createCamera // as needed. - camera.proxy = getProxyForTestingUseCaseConfiguration( - mockProcessCameraProvider, - ); + setUpOverridesForTestingUseCaseConfiguration(mockProcessCameraProvider); // Test non-null resolution presets. for (final ResolutionPreset resolutionPreset in ResolutionPreset.values) { @@ -1190,39 +838,32 @@ void main() { await camera.initializeCamera(flutterSurfaceTextureId); 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; @@ -1277,15 +918,15 @@ void main() { expect( camera.preview!.resolutionSelector!.resolutionStrategy, - equals(camera.proxy.highestAvailableStrategyResolutionStrategy()), + equals(ResolutionStrategy.highestAvailableStrategy), ); expect( camera.imageCapture!.resolutionSelector!.resolutionStrategy, - equals(camera.proxy.highestAvailableStrategyResolutionStrategy()), + equals(ResolutionStrategy.highestAvailableStrategy), ); expect( camera.imageAnalysis!.resolutionSelector!.resolutionStrategy, - equals(camera.proxy.highestAvailableStrategyResolutionStrategy()), + equals(ResolutionStrategy.highestAvailableStrategy), ); // Test null case. @@ -1304,36 +945,29 @@ void main() { test( 'createCamera and initializeCamera properly set filter for resolution preset for non-video capture use cases', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final camera = AndroidCameraCameraX(); const CameraLensDirection testLensDirection = CameraLensDirection.front; - const int testSensorOrientation = 180; - const CameraDescription testCameraDescription = CameraDescription( + const testSensorOrientation = 180; + const testCameraDescription = CameraDescription( name: 'cameraName', lensDirection: testLensDirection, sensorOrientation: testSensorOrientation, ); - const bool enableAudio = true; - final MockCamera mockCamera = MockCamera(); + const enableAudio = true; + final mockCamera = MockCamera(); // Mock/Detached objects for (typically attached) objects created by // createCamera. - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockCameraInfo = MockCameraInfo(); // Tell plugin to create mock/detached objects for testing createCamera // as needed. CameraSize? lastSetPreferredSize; - camera.proxy = getProxyForTestingUseCaseConfiguration( + setUpOverridesForTestingUseCaseConfiguration( mockProcessCameraProvider, createWithOnePreferredSizeResolutionFilter: - ({ - required CameraSize preferredSize, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - }) { + ({required CameraSize preferredSize}) { lastSetPreferredSize = preferredSize; return MockResolutionFilter(); }, @@ -1358,39 +992,32 @@ void main() { await camera.initializeCamera(flutterSurfaceTextureId); 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; @@ -1463,29 +1090,26 @@ void main() { test( 'createCamera and initializeCamera properly set aspect ratio based on preset resolution for non-video capture use cases', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final camera = AndroidCameraCameraX(); const CameraLensDirection testLensDirection = CameraLensDirection.back; - const int testSensorOrientation = 90; - const CameraDescription testCameraDescription = CameraDescription( + const testSensorOrientation = 90; + const testCameraDescription = CameraDescription( name: 'cameraName', lensDirection: testLensDirection, sensorOrientation: testSensorOrientation, ); - const bool enableAudio = true; - const int testCameraId = 12; - final MockCamera mockCamera = MockCamera(); + const enableAudio = true; + const testCameraId = 12; + final mockCamera = MockCamera(); // Mock/Detached objects for (typically attached) objects created by // createCamera. - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockCameraInfo = MockCameraInfo(); // Tell plugin to create mock/detached objects for testing createCamera // as needed. - camera.proxy = getProxyForTestingUseCaseConfiguration( - mockProcessCameraProvider, - ); + setUpOverridesForTestingUseCaseConfiguration(mockProcessCameraProvider); when( mockProcessCameraProvider.bindToLifecycle(any, any), ).thenAnswer((_) async => mockCamera); @@ -1524,23 +1148,17 @@ void main() { if (expectedAspectRatio == null) { expect( await camera.preview!.resolutionSelector!.getAspectRatioStrategy(), - equals( - camera.proxy.ratio_4_3FallbackAutoStrategyAspectRatioStrategy(), - ), + equals(AspectRatioStrategy.ratio_4_3FallbackAutoStrategy), ); expect( await camera.imageCapture!.resolutionSelector! .getAspectRatioStrategy(), - equals( - camera.proxy.ratio_4_3FallbackAutoStrategyAspectRatioStrategy(), - ), + equals(AspectRatioStrategy.ratio_4_3FallbackAutoStrategy), ); expect( await camera.imageAnalysis!.resolutionSelector! .getAspectRatioStrategy(), - equals( - camera.proxy.ratio_4_3FallbackAutoStrategyAspectRatioStrategy(), - ), + equals(AspectRatioStrategy.ratio_4_3FallbackAutoStrategy), ); continue; } @@ -1600,288 +1218,192 @@ void main() { test( 'createCamera and initializeCamera binds Preview, ImageCapture, and ImageAnalysis use cases to ProcessCameraProvider instance', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final camera = AndroidCameraCameraX(); const CameraLensDirection testLensDirection = CameraLensDirection.back; - const int testSensorOrientation = 90; - const CameraDescription testCameraDescription = CameraDescription( + const testSensorOrientation = 90; + const testCameraDescription = CameraDescription( name: 'cameraName', lensDirection: testLensDirection, sensorOrientation: testSensorOrientation, ); const ResolutionPreset testResolutionPreset = ResolutionPreset.veryHigh; - const bool enableAudio = true; + const 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 MockCameraCharacteristicsKey mockCameraCharacteristicsKey = - MockCameraCharacteristicsKey(); + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockPreview = MockPreview(); + final mockBackCameraSelector = MockCameraSelector(); + final mockImageCapture = MockImageCapture(); + final mockImageAnalysis = MockImageAnalysis(); + final mockRecorder = MockRecorder(); + final mockVideoCapture = MockVideoCapture(); + final mockCamera = MockCamera(); + final mockCameraInfo = MockCameraInfo(); + final mockCameraControl = MockCameraControl(); + final mockCamera2CameraInfo = MockCamera2CameraInfo(); + final mockCameraCharacteristicsKey = MockCameraCharacteristicsKey(); // 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, - CameraInfo? cameraInfoForFilter, - // 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, - }) { - final ResolutionInfo testResolutionInfo = - ResolutionInfo.pigeon_detached(resolution: MockCameraSize()); - when( - mockPreview.getResolutionInfo(), - ).thenAnswer((_) async => testResolutionInfo); - 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, - int? outputImageFormat, - 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(); - }, - ); - - 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); - - camera.processCameraProvider = mockProcessCameraProvider; + PigeonOverrides.processCameraProvider_getInstance = () async { + return mockProcessCameraProvider; + }; + PigeonOverrides.cameraSelector_new = + ({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) { + switch (requireLensFacing) { + case LensFacing.front: + return MockCameraSelector(); + case LensFacing.back: + case LensFacing.external: + case LensFacing.unknown: + case null: + } - final int flutterSurfaceTextureId = await camera.createCameraWithSettings( - testCameraDescription, - const MediaSettings( - resolutionPreset: testResolutionPreset, - fps: 15, - videoBitrate: 2000000, - audioBitrate: 64000, + return mockBackCameraSelector; + }; + PigeonOverrides.preview_new = + ({ + int? targetRotation, + CameraIntegerRange? targetFpsRange, + ResolutionSelector? resolutionSelector, + }) { + final testResolutionInfo = ResolutionInfo.pigeon_detached( + resolution: MockCameraSize(), + ); + when( + mockPreview.getResolutionInfo(), + ).thenAnswer((_) async => testResolutionInfo); + return mockPreview; + }; + PigeonOverrides.imageCapture_new = + ({ + int? targetRotation, + CameraXFlashMode? flashMode, + ResolutionSelector? resolutionSelector, + }) { + return mockImageCapture; + }; + PigeonOverrides.recorder_new = + ({ + int? aspectRatio, + int? targetVideoEncodingBitRate, + QualitySelector? qualitySelector, + }) { + return mockRecorder; + }; + PigeonOverrides.videoCapture_withOutput = + ({ + required VideoOutput videoOutput, + CameraIntegerRange? targetFpsRange, + }) { + return mockVideoCapture; + }; + PigeonOverrides.imageAnalysis_new = + ({ + int? targetRotation, + CameraIntegerRange? targetFpsRange, + int? outputImageFormat, + ResolutionSelector? resolutionSelector, + }) { + return mockImageAnalysis; + }; + PigeonOverrides.resolutionStrategy_new = + ({ + required CameraSize boundSize, + required ResolutionStrategyFallbackRule fallbackRule, + }) { + return MockResolutionStrategy(); + }; + PigeonOverrides.resolutionSelector_new = + ({ + AspectRatioStrategy? aspectRatioStrategy, + ResolutionStrategy? resolutionStrategy, + ResolutionFilter? resolutionFilter, + }) { + return MockResolutionSelector(); + }; + PigeonOverrides.qualitySelector_from = + ({ + required VideoQuality quality, + FallbackStrategy? fallbackStrategy, + }) { + return MockQualitySelector(); + }; + GenericsPigeonOverrides.observerNew = + ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; + PigeonOverrides.systemServicesManager_new = + ({ + required void Function(SystemServicesManager, String) onCameraError, + }) { + return MockSystemServicesManager(); + }; + PigeonOverrides.deviceOrientationManager_new = + ({ + required void Function(DeviceOrientationManager, String) + onDeviceOrientationChanged, + }) { + final manager = MockDeviceOrientationManager(); + when(manager.getUiOrientation()).thenAnswer((_) async { + return 'PORTRAIT_UP'; + }); + return manager; + }; + PigeonOverrides.aspectRatioStrategy_new = + ({ + required AspectRatio preferredAspectRatio, + required AspectRatioStrategyFallbackRule fallbackRule, + }) { + return MockAspectRatioStrategy(); + }; + PigeonOverrides.resolutionFilter_createWithOnePreferredSize = + ({required CameraSize preferredSize}) { + return MockResolutionFilter(); + }; + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { + when( + mockCamera2CameraInfo.getCameraCharacteristic( + mockCameraCharacteristicsKey, + ), + ).thenAnswer((_) async => testSensorOrientation); + return mockCamera2CameraInfo; + }; + PigeonOverrides.cameraSize_new = + ({required int width, required int height}) { + return MockCameraSize(); + }; + PigeonOverrides.cameraCharacteristics_sensorOrientation = + mockCameraCharacteristicsKey; + PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan = + ({required VideoQuality quality}) { + return MockFallbackStrategy(); + }; + + 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); + + camera.processCameraProvider = mockProcessCameraProvider; + PigeonOverrides.cameraIntegerRange_new = + CameraIntegerRange.pigeon_detached; + + final int flutterSurfaceTextureId = await camera.createCameraWithSettings( + testCameraDescription, + const MediaSettings( + resolutionPreset: testResolutionPreset, + fps: 15, + videoBitrate: 2000000, + audioBitrate: 64000, enableAudio: enableAudio, ), ); @@ -1910,40 +1432,33 @@ void main() { test( 'createCamera properly sets preset resolution for video capture use case', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final camera = AndroidCameraCameraX(); const CameraLensDirection testLensDirection = CameraLensDirection.back; - const int testSensorOrientation = 90; - const CameraDescription testCameraDescription = CameraDescription( + const testSensorOrientation = 90; + const testCameraDescription = CameraDescription( name: 'cameraName', lensDirection: testLensDirection, sensorOrientation: testSensorOrientation, ); - const bool enableAudio = true; - final MockCamera mockCamera = MockCamera(); + const enableAudio = true; + final mockCamera = MockCamera(); // Mock/Detached objects for (typically attached) objects created by // createCamera. - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockCameraInfo = MockCameraInfo(); // 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 = getProxyForTestingUseCaseConfiguration( + final mockFallbackStrategy = MockFallbackStrategy(); + final mockQualitySelector = MockQualitySelector(); + setUpOverridesForTestingUseCaseConfiguration( mockProcessCameraProvider, lowerQualityOrHigherThanFallbackStrategy: - ({ - required VideoQuality quality, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - }) { + ({required VideoQuality quality}) { fallbackStrategyVideoQuality = quality; return mockFallbackStrategy; }, @@ -1951,10 +1466,6 @@ void main() { ({ 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; @@ -2018,40 +1529,36 @@ void main() { test( 'createCamera sets sensorOrientationDegrees and enableRecordingAudio as expected', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final camera = AndroidCameraCameraX(); const CameraLensDirection testLensDirection = CameraLensDirection.back; - const int testSensorOrientation = 90; - const CameraDescription testCameraDescription = CameraDescription( + const testSensorOrientation = 90; + const testCameraDescription = CameraDescription( name: 'cameraName', lensDirection: testLensDirection, sensorOrientation: testSensorOrientation, ); - const bool enableAudio = true; + const enableAudio = true; const ResolutionPreset testResolutionPreset = ResolutionPreset.veryHigh; - const bool testHandlesCropAndRotation = true; + const testHandlesCropAndRotation = true; // Mock/Detached objects for (typically attached) objects created by // createCamera. - final MockCamera mockCamera = MockCamera(); - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final mockCamera = MockCamera(); + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockCameraInfo = MockCameraInfo(); // 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 = getProxyForTestingUseCaseConfiguration( + setUpOverridesForTestingUseCaseConfiguration( mockProcessCameraProvider, newPreview: ({ int? targetRotation, + CameraIntegerRange? targetFpsRange, ResolutionSelector? resolutionSelector, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, }) { - final MockPreview mockPreview = MockPreview(); + final mockPreview = MockPreview(); when( mockPreview.surfaceProducerHandlesCropAndRotation(), ).thenAnswer((_) async => testHandlesCropAndRotation); @@ -2082,343 +1589,340 @@ void main() { ); test( - 'createCamera properly selects specific back camera by specifying a CameraInfo', + 'createCamera and initializeCamera sets targetFps as expected', () async { - // Arrange - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final List returnData = [ - { - 'name': 'Camera 0', - 'lensFacing': 'back', - 'sensorOrientation': 0, - }, - { - 'name': 'Camera 1', - 'lensFacing': 'back', - 'sensorOrientation': 0, - }, - { - 'name': 'Camera 2', - 'lensFacing': 'front', - 'sensorOrientation': 0, - }, - ]; - - List mockCameraInfosList = []; - final Map cameraNameToInfos = - {}; - - const int testSensorOrientation = 0; - - // Mocks for objects created by availableCameras. - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockCameraSelector mockFrontCameraSelector = MockCameraSelector(); - final MockCameraSelector mockBackCameraSelector = MockCameraSelector(); - final MockCameraSelector mockChosenCameraInfoCameraSelector = - MockCameraSelector(); - - final MockCameraInfo mockFrontCameraInfo = MockCameraInfo(); - final MockCameraInfo mockBackCameraInfoOne = MockCameraInfo(); - final MockCameraInfo mockBackCameraInfoTwo = MockCameraInfo(); + final camera = AndroidCameraCameraX(); + const CameraLensDirection testLensDirection = CameraLensDirection.back; + const testSensorOrientation = 90; + const testCameraDescription = CameraDescription( + name: 'cameraName', + lensDirection: testLensDirection, + sensorOrientation: testSensorOrientation, + ); + const fastTargetFps = 60; + const testCameraId = 12; + final mockCamera = MockCamera(); // Mock/Detached objects for (typically attached) objects created by // createCamera. - final MockPreview mockPreview = MockPreview(); - 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(); + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockCameraInfo = MockCameraInfo(); - // Tell plugin to create mock/detached objects and stub method calls for the - // testing of availableCameras and createCamera. - 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, - }) { - return Future.value( - mockProcessCameraProvider, - ); - }, - newCameraSelector: - ({ - LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, - // 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: - } - if (cameraInfoForFilter == mockBackCameraInfoOne) { - return mockChosenCameraInfoCameraSelector; - } + when( + mockProcessCameraProvider.bindToLifecycle(any, any), + ).thenAnswer((_) async => mockCamera); + when(mockCamera.getCameraInfo()).thenAnswer((_) async => mockCameraInfo); + when( + mockCameraInfo.getCameraState(), + ).thenAnswer((_) async => MockLiveCameraState()); + camera.processCameraProvider = mockProcessCameraProvider; + PigeonOverrides.cameraIntegerRange_new = + CameraIntegerRange.pigeon_detached; - 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(); - }, + CameraIntegerRange? targetPreviewFpsRange; + CameraIntegerRange? targetVideoCaptureFpsRange; + CameraIntegerRange? targetImageAnalysisFpsRange; + + setUpOverridesForTestingUseCaseConfiguration( + mockProcessCameraProvider, newPreview: ({ - int? targetRotation, ResolutionSelector? resolutionSelector, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - }) { - return mockPreview; - }, - newImageCapture: - ({ + CameraIntegerRange? targetFpsRange, 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; + targetPreviewFpsRange = targetFpsRange; + final mockPreview = MockPreview(); + final testResolutionInfo = ResolutionInfo.pigeon_detached( + resolution: MockCameraSize(), + ); + when( + mockPreview.getResolutionInfo(), + ).thenAnswer((_) async => testResolutionInfo); + return mockPreview; }, withOutputVideoCapture: ({ + CameraIntegerRange? targetFpsRange, required VideoOutput videoOutput, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, }) { - return mockVideoCapture; + targetVideoCaptureFpsRange = targetFpsRange; + return MockVideoCapture(); }, newImageAnalysis: ({ - int? targetRotation, int? outputImageFormat, 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: (_) {}, - ), - ); - }, - 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, + CameraIntegerRange? targetFpsRange, + int? targetRotation, }) { - return MockFallbackStrategy(); + targetImageAnalysisFpsRange = targetFpsRange; + return MockImageAnalysis(); }, ); - // Mock calls to native platform - when(mockProcessCameraProvider.getAvailableCameraInfos()).thenAnswer(( - _, - ) async { - mockCameraInfosList = [ - mockBackCameraInfoOne, - mockBackCameraInfoTwo, - mockFrontCameraInfo, - ]; - return [ - mockBackCameraInfoOne, - mockBackCameraInfoTwo, - mockFrontCameraInfo, - ]; - }); - when( - mockBackCameraSelector.filter([mockBackCameraInfoOne]), - ).thenAnswer((_) async => [mockBackCameraInfoOne]); - when( - mockBackCameraSelector.filter([mockBackCameraInfoTwo]), - ).thenAnswer((_) async => [mockBackCameraInfoTwo]); - when( - mockBackCameraSelector.filter([mockFrontCameraInfo]), - ).thenAnswer((_) async => []); - when( - mockFrontCameraSelector.filter([mockBackCameraInfoOne]), - ).thenAnswer((_) async => []); - when( - mockFrontCameraSelector.filter([mockBackCameraInfoTwo]), - ).thenAnswer((_) async => []); - when( - mockFrontCameraSelector.filter([mockFrontCameraInfo]), - ).thenAnswer((_) async => [mockFrontCameraInfo]); + await camera.createCameraWithSettings( + testCameraDescription, + const MediaSettings(fps: fastTargetFps), + ); + await camera.initializeCamera(testCameraId); - final List cameraDescriptions = await camera - .availableCameras(); - expect(cameraDescriptions.length, returnData.length); + expect(targetPreviewFpsRange?.lower, fastTargetFps); + expect(targetPreviewFpsRange?.upper, fastTargetFps); + expect(targetVideoCaptureFpsRange?.lower, fastTargetFps); + expect(targetVideoCaptureFpsRange?.upper, fastTargetFps); + expect(targetImageAnalysisFpsRange?.lower, fastTargetFps); + expect(targetImageAnalysisFpsRange?.upper, fastTargetFps); + }, + ); - for (int i = 0; i < returnData.length; i++) { - final Map savedData = - (returnData[i] as Map).cast(); + test( + 'createCamera properly selects specific back camera by specifying a CameraInfo', + () async { + // Arrange + final camera = AndroidCameraCameraX(); + final returnData = [ + { + 'name': '0', + 'lensFacing': 'back', + 'sensorOrientation': 0, + }, + { + 'name': '1', + 'lensFacing': 'back', + 'sensorOrientation': 0, + }, + { + 'name': '2', + 'lensFacing': 'front', + 'sensorOrientation': 0, + }, + ]; - cameraNameToInfos[savedData['name']! as String] = - mockCameraInfosList[i]; - final CameraDescription cameraDescription = CameraDescription( + var mockCameraInfosList = []; + final cameraNameToInfos = {}; + + const testSensorOrientation = 0; + + // Mocks for objects created by availableCameras. + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockFrontCameraSelector = MockCameraSelector(); + final mockBackCameraSelector = MockCameraSelector(); + final mockChosenCameraInfoCameraSelector = MockCameraSelector(); + + final mockFrontCameraInfo = MockCameraInfo(); + final mockBackCameraInfoOne = MockCameraInfo(); + final mockBackCameraInfoTwo = MockCameraInfo(); + + when(mockFrontCameraInfo.lensFacing).thenReturn(LensFacing.front); + when(mockBackCameraInfoOne.lensFacing).thenReturn(LensFacing.back); + when(mockBackCameraInfoTwo.lensFacing).thenReturn(LensFacing.back); + + // Mock/Detached objects for (typically attached) objects created by + // createCamera. + final mockPreview = MockPreview(); + final mockImageCapture = MockImageCapture(); + final mockImageAnalysis = MockImageAnalysis(); + final mockRecorder = MockRecorder(); + final mockVideoCapture = MockVideoCapture(); + final mockCamera = MockCamera(); + final mockCameraInfo = MockCameraInfo(); + final mockCameraControl = MockCameraControl(); + final mockCamera2CameraInfo = MockCamera2CameraInfo(); + final mockCameraCharacteristicsKey = MockCameraCharacteristicsKey(); + + // Tell plugin to create mock/detached objects and stub method calls for the + // testing of availableCameras and createCamera. + PigeonOverrides.processCameraProvider_getInstance = () { + return Future.value(mockProcessCameraProvider); + }; + PigeonOverrides.cameraSelector_new = + ({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) { + switch (requireLensFacing) { + case LensFacing.front: + return mockFrontCameraSelector; + case LensFacing.back: + case LensFacing.external: + case LensFacing.unknown: + case null: + } + if (cameraInfoForFilter == mockBackCameraInfoOne) { + return mockChosenCameraInfoCameraSelector; + } + + return mockBackCameraSelector; + }; + PigeonOverrides.systemServicesManager_new = + ({ + required void Function(SystemServicesManager, String) onCameraError, + }) { + return MockSystemServicesManager(); + }; + PigeonOverrides.preview_new = + ({ + int? targetRotation, + CameraIntegerRange? targetFpsRange, + ResolutionSelector? resolutionSelector, + }) { + return mockPreview; + }; + PigeonOverrides.imageCapture_new = + ({ + int? targetRotation, + CameraXFlashMode? flashMode, + ResolutionSelector? resolutionSelector, + }) { + return mockImageCapture; + }; + PigeonOverrides.recorder_new = + ({ + int? aspectRatio, + int? targetVideoEncodingBitRate, + QualitySelector? qualitySelector, + }) { + return mockRecorder; + }; + PigeonOverrides.recorder_new = + ({ + int? aspectRatio, + int? targetVideoEncodingBitRate, + QualitySelector? qualitySelector, + }) { + return mockRecorder; + }; + PigeonOverrides.videoCapture_withOutput = + ({ + required VideoOutput videoOutput, + CameraIntegerRange? targetFpsRange, + }) { + return mockVideoCapture; + }; + PigeonOverrides.imageAnalysis_new = + ({ + int? targetRotation, + CameraIntegerRange? targetFpsRange, + int? outputImageFormat, + ResolutionSelector? resolutionSelector, + }) { + return mockImageAnalysis; + }; + PigeonOverrides.resolutionStrategy_new = + ({ + required CameraSize boundSize, + required ResolutionStrategyFallbackRule fallbackRule, + }) { + return MockResolutionStrategy(); + }; + PigeonOverrides.resolutionSelector_new = + ({ + AspectRatioStrategy? aspectRatioStrategy, + ResolutionStrategy? resolutionStrategy, + ResolutionFilter? resolutionFilter, + }) { + return MockResolutionSelector(); + }; + PigeonOverrides.resolutionSelector_new = + ({ + AspectRatioStrategy? aspectRatioStrategy, + ResolutionStrategy? resolutionStrategy, + ResolutionFilter? resolutionFilter, + }) { + return MockResolutionSelector(); + }; + PigeonOverrides.qualitySelector_from = + ({ + required VideoQuality quality, + FallbackStrategy? fallbackStrategy, + }) { + return MockQualitySelector(); + }; + GenericsPigeonOverrides.observerNew = + ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; + PigeonOverrides.deviceOrientationManager_new = + ({ + required void Function(DeviceOrientationManager, String) + onDeviceOrientationChanged, + }) { + final manager = MockDeviceOrientationManager(); + when(manager.getUiOrientation()).thenAnswer((_) async { + return 'PORTRAIT_UP'; + }); + return manager; + }; + PigeonOverrides.aspectRatioStrategy_new = + ({ + required AspectRatio preferredAspectRatio, + required AspectRatioStrategyFallbackRule fallbackRule, + }) { + return MockAspectRatioStrategy(); + }; + PigeonOverrides.resolutionFilter_createWithOnePreferredSize = + ({required CameraSize preferredSize}) { + return MockResolutionFilter(); + }; + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { + var cameraId = ''; + if (cameraInfo == mockBackCameraInfoOne) { + cameraId = '0'; + } else if (cameraInfo == mockBackCameraInfoTwo) { + cameraId = '1'; + } else if (cameraInfo == mockFrontCameraInfo) { + cameraId = '2'; + } + when( + mockCamera2CameraInfo.getCameraId(), + ).thenAnswer((_) async => cameraId); + when( + mockCamera2CameraInfo.getCameraCharacteristic( + mockCameraCharacteristicsKey, + ), + ).thenAnswer((_) async => testSensorOrientation); + return mockCamera2CameraInfo; + }; + PigeonOverrides.cameraSize_new = + ({required int width, required int height}) { + return MockCameraSize(); + }; + PigeonOverrides.cameraCharacteristics_sensorOrientation = + mockCameraCharacteristicsKey; + PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan = + ({required VideoQuality quality}) { + return MockFallbackStrategy(); + }; + PigeonOverrides.cameraIntegerRange_new = + ({required int lower, required int upper}) { + return CameraIntegerRange.pigeon_detached(lower: 0, upper: 0); + }; + + // Mock calls to native platform + when(mockProcessCameraProvider.getAvailableCameraInfos()).thenAnswer(( + _, + ) async { + mockCameraInfosList = [ + mockBackCameraInfoOne, + mockBackCameraInfoTwo, + mockFrontCameraInfo, + ]; + return [ + mockBackCameraInfoOne, + mockBackCameraInfoTwo, + mockFrontCameraInfo, + ]; + }); + + final List cameraDescriptions = await camera + .availableCameras(); + expect(cameraDescriptions.length, returnData.length); + + for (var i = 0; i < returnData.length; i++) { + final Map savedData = + (returnData[i] as Map).cast(); + + cameraNameToInfos[savedData['name']! as String] = + mockCameraInfosList[i]; + final cameraDescription = CameraDescription( name: savedData['name']! as String, lensDirection: (savedData['lensFacing']! as String) == 'front' ? CameraLensDirection.front @@ -2470,7 +1974,7 @@ void main() { test( 'initializeCamera throws a CameraException when createCamera has not been called before initializedCamera', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final camera = AndroidCameraCameraX(); await expectLater(() async { await camera.initializeCamera(3); }, throwsA(isA())); @@ -2478,26 +1982,25 @@ void main() { ); test('initializeCamera sets camera state observer as expected', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final camera = AndroidCameraCameraX(); const CameraLensDirection testLensDirection = CameraLensDirection.back; - const int testSensorOrientation = 90; - const CameraDescription testCameraDescription = CameraDescription( + const testSensorOrientation = 90; + const testCameraDescription = CameraDescription( name: 'cameraName', lensDirection: testLensDirection, sensorOrientation: testSensorOrientation, ); - const bool enableAudio = true; - final MockCamera mockCamera = MockCamera(); - const int testSurfaceTextureId = 244; + const enableAudio = true; + final mockCamera = MockCamera(); + const testSurfaceTextureId = 244; // Mock/Detached objects for (typically attached) objects created by // createCamera. - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final MockLiveCameraState mockLiveCameraState = MockLiveCameraState(); - final MockPreview mockPreview = MockPreview(); - final ResolutionInfo testResolutionInfo = ResolutionInfo.pigeon_detached( + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockCameraInfo = MockCameraInfo(); + final mockLiveCameraState = MockLiveCameraState(); + final mockPreview = MockPreview(); + final testResolutionInfo = ResolutionInfo.pigeon_detached( resolution: MockCameraSize(), ); @@ -2518,16 +2021,13 @@ void main() { // Tell plugin to create mock/detached objects for testing createCamera // as needed. - camera.proxy = getProxyForTestingUseCaseConfiguration( + setUpOverridesForTestingUseCaseConfiguration( mockProcessCameraProvider, newPreview: ({ - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, ResolutionSelector? resolutionSelector, int? targetRotation, + CameraIntegerRange? targetFpsRange, }) => mockPreview, ); @@ -2553,29 +2053,28 @@ void main() { test( 'initializeCamera sets image format of ImageAnalysis use case as expected', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final camera = AndroidCameraCameraX(); const CameraLensDirection testLensDirection = CameraLensDirection.back; - const int testSensorOrientation = 90; - const CameraDescription testCameraDescription = CameraDescription( + const testSensorOrientation = 90; + const testCameraDescription = CameraDescription( name: 'cameraName', lensDirection: testLensDirection, sensorOrientation: testSensorOrientation, ); - const bool enableAudio = true; - final MockCamera mockCamera = MockCamera(); - const int testSurfaceTextureId = 244; + const enableAudio = true; + final mockCamera = MockCamera(); + const testSurfaceTextureId = 244; // Mock/Detached objects for (typically attached) objects created by // createCamera. - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final MockLiveCameraState mockLiveCameraState = MockLiveCameraState(); - final MockPreview mockPreview = MockPreview(); - final ResolutionInfo testResolutionInfo = ResolutionInfo.pigeon_detached( + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockCameraInfo = MockCameraInfo(); + final mockLiveCameraState = MockLiveCameraState(); + final mockPreview = MockPreview(); + final testResolutionInfo = ResolutionInfo.pigeon_detached( resolution: MockCameraSize(), ); - final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); + final mockImageAnalysis = MockImageAnalysis(); // Configure mocks for camera initialization. when( @@ -2605,16 +2104,13 @@ void main() { // Tell plugin to create mock/detached objects for testing createCamera // as needed. int? imageAnalysisOutputImageFormat; - camera.proxy = getProxyForTestingUseCaseConfiguration( + setUpOverridesForTestingUseCaseConfiguration( mockProcessCameraProvider, newImageAnalysis: ({ - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, ResolutionSelector? resolutionSelector, int? targetRotation, + CameraIntegerRange? targetFpsRange, int? outputImageFormat, }) { imageAnalysisOutputImageFormat = outputImageFormat; @@ -2622,12 +2118,9 @@ void main() { }, newPreview: ({ - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, ResolutionSelector? resolutionSelector, int? targetRotation, + CameraIntegerRange? targetFpsRange, }) => mockPreview, ); @@ -2648,244 +2141,146 @@ void main() { ); test('initializeCamera sends expected CameraInitializedEvent', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final camera = AndroidCameraCameraX(); - const int cameraId = 10; + const cameraId = 10; const CameraLensDirection testLensDirection = CameraLensDirection.back; - const int testSensorOrientation = 90; - const CameraDescription testCameraDescription = CameraDescription( + const testSensorOrientation = 90; + const testCameraDescription = CameraDescription( name: 'cameraName', lensDirection: testLensDirection, sensorOrientation: testSensorOrientation, ); - const int resolutionWidth = 350; - const int resolutionHeight = 750; + const resolutionWidth = 350; + const resolutionHeight = 750; final Camera mockCamera = MockCamera(); - final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final ResolutionInfo testResolutionInfo = ResolutionInfo.pigeon_detached( + + final 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 = - MockProcessCameraProvider(); + final mockProcessCameraProvider = MockProcessCameraProvider(); final CameraInfo mockCameraInfo = MockCameraInfo(); - final MockCameraSelector mockBackCameraSelector = MockCameraSelector(); - final MockCameraSelector mockFrontCameraSelector = MockCameraSelector(); - final MockPreview mockPreview = MockPreview(); - final MockImageCapture mockImageCapture = MockImageCapture(); - final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); + final mockBackCameraSelector = MockCameraSelector(); + final mockFrontCameraSelector = MockCameraSelector(); + final mockPreview = MockPreview(); + final mockImageCapture = MockImageCapture(); + final mockImageAnalysis = MockImageAnalysis(); // Tell plugin to create mock/detached objects for testing createCamera // as needed. - camera.proxy = CameraXProxy( - getInstanceProcessCameraProvider: - ({ - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - }) => Future.value(mockProcessCameraProvider), - newCameraSelector: - ({ - LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - }) { - switch (requireLensFacing) { - case LensFacing.front: - return mockFrontCameraSelector; - case _: - return mockBackCameraSelector; - } - }, - 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, - int? outputImageFormat, - 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(), - 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(), - fromQualitySelector: - ({ - required VideoQuality quality, - FallbackStrategy? fallbackStrategy, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - }) => 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, - }) => 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(), - ); + PigeonOverrides.processCameraProvider_getInstance = () => + Future.value(mockProcessCameraProvider); + PigeonOverrides.cameraSelector_new = + ({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) { + switch (requireLensFacing) { + case LensFacing.front: + return mockFrontCameraSelector; + case _: + return mockBackCameraSelector; + } + }; + PigeonOverrides.preview_new = + ({ + int? targetRotation, + CameraIntegerRange? targetFpsRange, + ResolutionSelector? resolutionSelector, + }) => mockPreview; + PigeonOverrides.imageCapture_new = + ({ + int? targetRotation, + CameraXFlashMode? flashMode, + ResolutionSelector? resolutionSelector, + }) => mockImageCapture; + PigeonOverrides.recorder_new = + ({ + int? aspectRatio, + int? targetVideoEncodingBitRate, + QualitySelector? qualitySelector, + }) => MockRecorder(); + PigeonOverrides.videoCapture_withOutput = + ({ + required VideoOutput videoOutput, + CameraIntegerRange? targetFpsRange, + }) => MockVideoCapture(); + PigeonOverrides.imageAnalysis_new = + ({ + int? targetRotation, + CameraIntegerRange? targetFpsRange, + int? outputImageFormat, + ResolutionSelector? resolutionSelector, + }) => mockImageAnalysis; + PigeonOverrides.resolutionStrategy_new = + ({ + required CameraSize boundSize, + required ResolutionStrategyFallbackRule fallbackRule, + }) => MockResolutionStrategy(); + PigeonOverrides.resolutionSelector_new = + ({ + AspectRatioStrategy? aspectRatioStrategy, + ResolutionStrategy? resolutionStrategy, + ResolutionFilter? resolutionFilter, + }) => MockResolutionSelector(); + PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan = + ({required VideoQuality quality}) => MockFallbackStrategy(); + PigeonOverrides.qualitySelector_from = + ({required VideoQuality quality, FallbackStrategy? fallbackStrategy}) => + MockQualitySelector(); + GenericsPigeonOverrides.observerNew = + ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; + PigeonOverrides.systemServicesManager_new = + ({ + required void Function(SystemServicesManager, String) onCameraError, + }) => MockSystemServicesManager(); + PigeonOverrides.deviceOrientationManager_new = + ({ + required void Function(DeviceOrientationManager, String) + onDeviceOrientationChanged, + }) { + final manager = MockDeviceOrientationManager(); + when(manager.getUiOrientation()).thenAnswer((_) async { + return 'PORTRAIT_UP'; + }); + return manager; + }; + PigeonOverrides.aspectRatioStrategy_new = + ({ + required AspectRatio preferredAspectRatio, + required AspectRatioStrategyFallbackRule fallbackRule, + }) => MockAspectRatioStrategy(); + PigeonOverrides.resolutionFilter_createWithOnePreferredSize = + ({required CameraSize preferredSize}) => MockResolutionFilter(); + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { + final mockCamera2CameraInfo = MockCamera2CameraInfo(); + when( + mockCamera2CameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => 90); + return mockCamera2CameraInfo; + }; + PigeonOverrides.cameraSize_new = + ({required int width, required int height}) => MockCameraSize(); + PigeonOverrides.cameraCharacteristics_sensorOrientation = + MockCameraCharacteristicsKey(); + PigeonOverrides.cameraIntegerRange_new = + ({required int lower, required int upper}) { + return CameraIntegerRange.pigeon_detached(lower: 0, upper: 0); + }; - final CameraInitializedEvent testCameraInitializedEvent = - CameraInitializedEvent( - cameraId, - resolutionWidth.toDouble(), - resolutionHeight.toDouble(), - ExposureMode.auto, - true, - FocusMode.auto, - true, - ); + final testCameraInitializedEvent = CameraInitializedEvent( + cameraId, + resolutionWidth.toDouble(), + resolutionHeight.toDouble(), + ExposureMode.auto, + true, + FocusMode.auto, + true, + ); // Call createCamera. when(mockPreview.setSurfaceProvider(any)).thenAnswer((_) async => cameraId); @@ -2930,29 +2325,22 @@ void main() { test( 'dispose releases Flutter surface texture, removes camera state observers, and unbinds all use cases', () async { - bool stoppedListeningForDeviceOrientationChange = false; - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - 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 - .stopListeningForDeviceOrientationChange(), - ).thenAnswer((_) async { - stoppedListeningForDeviceOrientationChange = true; - }); - return mockDeviceOrientationManager; - }, - ); + var stoppedListeningForDeviceOrientationChange = false; + final camera = AndroidCameraCameraX(); + PigeonOverrides.deviceOrientationManager_new = + ({ + required void Function(DeviceOrientationManager, String) + onDeviceOrientationChanged, + }) { + final mockDeviceOrientationManager = MockDeviceOrientationManager(); + when( + mockDeviceOrientationManager + .stopListeningForDeviceOrientationChange(), + ).thenAnswer((_) async { + stoppedListeningForDeviceOrientationChange = true; + }); + return mockDeviceOrientationManager; + }; camera.preview = MockPreview(); camera.processCameraProvider = MockProcessCameraProvider(); @@ -2970,13 +2358,12 @@ void main() { ); test('onCameraInitialized stream emits CameraInitializedEvents', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 16; + final camera = AndroidCameraCameraX(); + const cameraId = 16; final Stream eventStream = camera .onCameraInitialized(cameraId); - final StreamQueue streamQueue = - StreamQueue(eventStream); - const CameraInitializedEvent testEvent = CameraInitializedEvent( + final streamQueue = StreamQueue(eventStream); + const testEvent = CameraInitializedEvent( cameraId, 320, 80, @@ -2995,16 +2382,13 @@ 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 camera = AndroidCameraCameraX(); + const cameraId = 99; + const cameraClosingEvent = CameraClosingEvent(cameraId); final Stream eventStream = camera.onCameraClosing( cameraId, ); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); camera.cameraEventStreamController.add(cameraClosingEvent); @@ -3016,38 +2400,29 @@ void main() { 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( + final camera = AndroidCameraCameraX(); + const cameraId = 27; + const firstTestErrorDescription = 'Test error description 1!'; + const secondTestErrorDescription = 'Test error description 2!'; + const secondCameraErrorEvent = CameraErrorEvent( cameraId, secondTestErrorDescription, ); final Stream eventStream = camera.onCameraError( cameraId, ); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); - 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; - }, - ); + PigeonOverrides.systemServicesManager_new = + ({ + required void Function(SystemServicesManager, String) onCameraError, + }) { + final mockSystemServicesManager = MockSystemServicesManager(); + when( + mockSystemServicesManager.onCameraError, + ).thenReturn(onCameraError); + return mockSystemServicesManager; + }; camera.systemServicesManager.onCameraError( camera.systemServicesManager, @@ -3068,33 +2443,28 @@ void main() { test( 'onDeviceOrientationChanged stream emits changes in device orientation detected by system services', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final camera = AndroidCameraCameraX(); final Stream eventStream = camera .onDeviceOrientationChanged(); - final StreamQueue streamQueue = - StreamQueue(eventStream); - const DeviceOrientationChangedEvent testEvent = - DeviceOrientationChangedEvent(DeviceOrientation.portraitDown); - - 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; - }, + final streamQueue = StreamQueue( + eventStream, + ); + const testEvent = DeviceOrientationChangedEvent( + DeviceOrientation.portraitDown, ); + PigeonOverrides.deviceOrientationManager_new = + ({ + required void Function(DeviceOrientationManager, String) + onDeviceOrientationChanged, + }) { + final mockDeviceOrientationManager = MockDeviceOrientationManager(); + when( + mockDeviceOrientationManager.onDeviceOrientationChanged, + ).thenReturn(onDeviceOrientationChanged); + return mockDeviceOrientationManager; + }; + camera.deviceOrientationManager.onDeviceOrientationChanged( camera.deviceOrientationManager, 'PORTRAIT_DOWN', @@ -3108,7 +2478,7 @@ void main() { test( 'pausePreview unbinds preview from lifecycle when preview is nonnull and has been bound to lifecycle', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final camera = AndroidCameraCameraX(); // Set directly for test versus calling createCamera. camera.processCameraProvider = MockProcessCameraProvider(); @@ -3127,7 +2497,7 @@ void main() { test( 'pausePreview does not unbind preview from lifecycle when preview has not been bound to lifecycle', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final camera = AndroidCameraCameraX(); // Set directly for test versus calling createCamera. camera.processCameraProvider = MockProcessCameraProvider(); @@ -3144,12 +2514,11 @@ void main() { 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(); + final camera = AndroidCameraCameraX(); + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockCamera = MockCamera(); + final mockCameraInfo = MockCameraInfo(); + final mockLiveCameraState = MockLiveCameraState(); // Set directly for test versus calling createCamera. camera.processCameraProvider = mockProcessCameraProvider; @@ -3187,13 +2556,12 @@ void main() { 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(); + final camera = AndroidCameraCameraX(); + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockCamera = MockCamera(); + final mockCameraInfo = MockCameraInfo(); + final mockCameraControl = MockCameraControl(); + final mockLiveCameraState = MockLiveCameraState(); // Set directly for test versus calling createCamera. camera.processCameraProvider = mockProcessCameraProvider; @@ -3203,23 +2571,10 @@ void main() { // 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( - 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: (_) {}, - ), - ); - }, - ); + GenericsPigeonOverrides.observerNew = + ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; when( mockProcessCameraProvider.bindToLifecycle( @@ -3260,8 +2615,8 @@ void main() { test( 'buildPreview throws an exception if the preview is not bound to the lifecycle', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 73; + final camera = AndroidCameraCameraX(); + const cameraId = 73; // Tell camera that createCamera has not been called and thus, preview has // not been bound to the lifecycle of the camera. @@ -3279,22 +2634,18 @@ void main() { 'startVideoCapturing binds video capture use case, updates saved camera instance and its properties, and starts the recording with audio enabled as desired', () async { // Set up mocks and constants. - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockPendingRecording mockPendingRecording = - MockPendingRecording(); - final MockPendingRecording mockPendingRecordingWithAudio = - 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(); - const bool enableAudio = true; + final camera = AndroidCameraCameraX(); + final mockPendingRecording = MockPendingRecording(); + final mockPendingRecordingWithAudio = MockPendingRecording(); + final mockRecording = MockRecording(); + final mockCamera = MockCamera(); + final newMockCamera = MockCamera(); + final mockCameraInfo = MockCameraInfo(); + final mockCameraControl = MockCameraControl(); + final mockLiveCameraState = MockLiveCameraState(); + final newMockLiveCameraState = MockLiveCameraState(); + final mockCamera2CameraInfo = MockCamera2CameraInfo(); + const enableAudio = true; // Set directly for test versus calling createCamera. camera.processCameraProvider = MockProcessCameraProvider(); @@ -3311,75 +2662,38 @@ void main() { camera.captureOrientationLocked = true; // Tell plugin to create detached Observer when camera info updated. - const String outputPath = '/temp/REC123.mp4'; - 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, - '.mp4', - ), - ).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 outputPath = '/temp/REC123.mp4'; + GenericsPigeonOverrides.observerNew = + ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; + PigeonOverrides.camera2CameraInfo_from = + ({required dynamic cameraInfo}) => mockCamera2CameraInfo; + PigeonOverrides.systemServicesManager_new = + ({ + required void Function(SystemServicesManager, String) + onCameraError, + }) { + final mockSystemServicesManager = MockSystemServicesManager(); + when( + mockSystemServicesManager.getTempFilePath( + camera.videoPrefix, + '.mp4', + ), + ).thenAnswer((_) async => outputPath); + return mockSystemServicesManager; + }; + PigeonOverrides.videoRecordEventListener_new = + ({ + required void Function(VideoRecordEventListener, VideoRecordEvent) + onEvent, + }) { + return VideoRecordEventListener.pigeon_detached(onEvent: onEvent); + }; + PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel = + MockCameraCharacteristicsKey(); - const int cameraId = 17; + const cameraId = 17; // Mock method calls. when( @@ -3416,11 +2730,7 @@ void main() { // Simulate video recording being started so startVideoRecording completes. AndroidCameraCameraX.videoRecordingEventStreamController.add( - VideoRecordEventStart.pigeon_detached( - pigeon_instanceManager: PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), - ), + VideoRecordEventStart.pigeon_detached(), ); await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); @@ -3458,14 +2768,12 @@ void main() { ' 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(); + final camera = AndroidCameraCameraX(); + final mockPendingRecording = MockPendingRecording(); + final mockRecording = MockRecording(); + final mockCamera = MockCamera(); + final mockCameraInfo = MockCameraInfo(); + final mockCamera2CameraInfo = MockCamera2CameraInfo(); // Set directly for test versus calling createCamera. camera.processCameraProvider = MockProcessCameraProvider(); @@ -3480,75 +2788,38 @@ void main() { camera.captureOrientationLocked = true; // Tell plugin to create detached Observer when camera info updated. - const String outputPath = '/temp/REC123.mp4'; - 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, - '.mp4', - ), - ).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 outputPath = '/temp/REC123.mp4'; + GenericsPigeonOverrides.observerNew = + ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; + PigeonOverrides.camera2CameraInfo_from = + ({required dynamic cameraInfo}) => mockCamera2CameraInfo; + PigeonOverrides.systemServicesManager_new = + ({ + required void Function(SystemServicesManager, String) + onCameraError, + }) { + final mockSystemServicesManager = MockSystemServicesManager(); + when( + mockSystemServicesManager.getTempFilePath( + camera.videoPrefix, + '.mp4', + ), + ).thenAnswer((_) async => outputPath); + return mockSystemServicesManager; + }; + PigeonOverrides.videoRecordEventListener_new = + ({ + required void Function(VideoRecordEventListener, VideoRecordEvent) + onEvent, + }) { + return VideoRecordEventListener.pigeon_detached(onEvent: onEvent); + }; + PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel = + MockCameraCharacteristicsKey(); - const int cameraId = 17; + const cameraId = 17; // Mock method calls. when( @@ -3584,11 +2855,7 @@ void main() { // Simulate video recording being started so startVideoRecording completes. AndroidCameraCameraX.videoRecordingEventStreamController.add( - VideoRecordEventStart.pigeon_detached( - pigeon_instanceManager: PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), - ), + VideoRecordEventStart.pigeon_detached(), ); await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); @@ -3624,15 +2891,12 @@ void main() { 'startVideoCapturing called with stream options starts image streaming', () async { // Set up mocks and constants. - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); + final camera = AndroidCameraCameraX(); + final mockProcessCameraProvider = MockProcessCameraProvider(); final Recorder mockRecorder = MockRecorder(); - final MockPendingRecording mockPendingRecording = - MockPendingRecording(); - final MockCameraInfo initialCameraInfo = MockCameraInfo(); - final MockCamera2CameraInfo mockCamera2CameraInfo = - MockCamera2CameraInfo(); + final mockPendingRecording = MockPendingRecording(); + final initialCameraInfo = MockCameraInfo(); + final mockCamera2CameraInfo = MockCamera2CameraInfo(); // Set directly for test versus calling createCamera. @@ -3650,88 +2914,44 @@ void main() { camera.captureOrientationLocked = true; // Tell plugin to create detached Analyzer for testing. - const String outputPath = '/temp/REC123.mp4'; - 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, - '.mp4', - ), - ).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( + const outputPath = '/temp/REC123.mp4'; + GenericsPigeonOverrides.observerNew = + ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; + PigeonOverrides.camera2CameraInfo_from = + ({required dynamic cameraInfo}) => mockCamera2CameraInfo; + PigeonOverrides.systemServicesManager_new = + ({ + required void Function(SystemServicesManager, String) + onCameraError, + }) { + final mockSystemServicesManager = MockSystemServicesManager(); + when( + mockSystemServicesManager.getTempFilePath( + camera.videoPrefix, + '.mp4', + ), + ).thenAnswer((_) async => outputPath); + return mockSystemServicesManager; + }; + PigeonOverrides.videoRecordEventListener_new = + ({ + required void Function(VideoRecordEventListener, VideoRecordEvent) + onEvent, + }) { + return VideoRecordEventListener.pigeon_detached(onEvent: onEvent); + }; + PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel = + MockCameraCharacteristicsKey(); + PigeonOverrides.analyzer_new = + ({required void Function(Analyzer, ImageProxy) analyze}) { + return MockAnalyzer(); + }; + + const cameraId = 17; + final imageDataCompleter = Completer(); + final videoCaptureOptions = VideoCaptureOptions( cameraId, streamCallback: (CameraImageData imageData) => imageDataCompleter.complete(imageData), @@ -3765,11 +2985,7 @@ void main() { // Simulate video recording being started so startVideoRecording completes. AndroidCameraCameraX.videoRecordingEventStreamController.add( - VideoRecordEventStart.pigeon_detached( - pigeon_instanceManager: PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), - ), + VideoRecordEventStart.pigeon_detached(), ); await camera.startVideoCapturing(videoCaptureOptions); @@ -3786,14 +3002,12 @@ void main() { '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 camera = AndroidCameraCameraX(); + final mockPendingRecording = MockPendingRecording(); + final mockRecording = MockRecording(); + final mockVideoCapture = MockVideoCapture(); + final initialCameraInfo = MockCameraInfo(); + final mockCamera2CameraInfo = MockCamera2CameraInfo(); const int defaultTargetRotation = Surface.rotation270; // Set directly for test versus calling createCamera. @@ -3807,93 +3021,52 @@ void main() { camera.enableRecordingAudio = false; // Tell plugin to mock call to get current video orientation and mock Camera2CameraInfo retrieval. - const String outputPath = '/temp/REC123.mp4'; - 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(), - 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, - '.mp4', - ), - ).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 outputPath = '/temp/REC123.mp4'; + GenericsPigeonOverrides.observerNew = + ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; + PigeonOverrides.camera2CameraInfo_from = + ({required dynamic cameraInfo}) => cameraInfo == initialCameraInfo + ? mockCamera2CameraInfo + : MockCamera2CameraInfo(); + PigeonOverrides.systemServicesManager_new = + ({ + required void Function(SystemServicesManager, String) + onCameraError, + }) { + final mockSystemServicesManager = MockSystemServicesManager(); + when( + mockSystemServicesManager.getTempFilePath( + camera.videoPrefix, + '.mp4', + ), + ).thenAnswer((_) async => outputPath); + return mockSystemServicesManager; + }; + PigeonOverrides.deviceOrientationManager_new = + ({ + required void Function(DeviceOrientationManager, String) + onDeviceOrientationChanged, + }) { + final mockDeviceOrientationManager = + MockDeviceOrientationManager(); + when( + mockDeviceOrientationManager.getDefaultDisplayRotation(), + ).thenAnswer((_) async => defaultTargetRotation); + return mockDeviceOrientationManager; + }; + PigeonOverrides.videoRecordEventListener_new = + ({ + required void Function(VideoRecordEventListener, VideoRecordEvent) + onEvent, + }) { + return VideoRecordEventListener.pigeon_detached(onEvent: onEvent); + }; + PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel = + MockCameraCharacteristicsKey(); - const int cameraId = 87; + const cameraId = 87; // Mock method calls. when( @@ -3920,11 +3093,7 @@ void main() { // Simulate video recording being started so startVideoRecording completes. AndroidCameraCameraX.videoRecordingEventStreamController.add( - VideoRecordEventStart.pigeon_detached( - pigeon_instanceManager: PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), - ), + VideoRecordEventStart.pigeon_detached(), ); // Orientation is unlocked and plugin does not need to set default target @@ -3935,11 +3104,7 @@ void main() { // Simulate video recording being started so startVideoRecording completes. AndroidCameraCameraX.videoRecordingEventStreamController.add( - VideoRecordEventStart.pigeon_detached( - pigeon_instanceManager: PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), - ), + VideoRecordEventStart.pigeon_detached(), ); // Orientation is locked and plugin does not need to set default target @@ -3951,11 +3116,7 @@ void main() { // Simulate video recording being started so startVideoRecording completes. AndroidCameraCameraX.videoRecordingEventStreamController.add( - VideoRecordEventStart.pigeon_detached( - pigeon_instanceManager: PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), - ), + VideoRecordEventStart.pigeon_detached(), ); // Orientation is locked and plugin does need to set default target @@ -3968,11 +3129,7 @@ void main() { // Simulate video recording being started so startVideoRecording completes. AndroidCameraCameraX.videoRecordingEventStreamController.add( - VideoRecordEventStart.pigeon_detached( - pigeon_instanceManager: PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), - ), + VideoRecordEventStart.pigeon_detached(), ); // Orientation is unlocked and plugin does need to set default target @@ -3986,8 +3143,8 @@ void main() { ); test('pauseVideoRecording pauses the recording', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockRecording recording = MockRecording(); + final camera = AndroidCameraCameraX(); + final recording = MockRecording(); // Set directly for test versus calling startVideoCapturing. camera.recording = recording; @@ -3998,8 +3155,8 @@ void main() { }); test('resumeVideoRecording resumes the recording', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockRecording recording = MockRecording(); + final camera = AndroidCameraCameraX(); + final recording = MockRecording(); // Set directly for test versus calling startVideoCapturing. camera.recording = recording; @@ -4010,12 +3167,11 @@ void main() { }); test('stopVideoRecording stops the recording', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockRecording recording = MockRecording(); - final MockProcessCameraProvider processCameraProvider = - MockProcessCameraProvider(); - final MockVideoCapture videoCapture = MockVideoCapture(); - const String videoOutputPath = '/test/output/path'; + final camera = AndroidCameraCameraX(); + final recording = MockRecording(); + final processCameraProvider = MockProcessCameraProvider(); + final videoCapture = MockVideoCapture(); + const videoOutputPath = '/test/output/path'; // Set directly for test versus calling createCamera and startVideoCapturing. camera.processCameraProvider = processCameraProvider; @@ -4030,11 +3186,7 @@ void main() { // Simulate video recording being finalized so stopVideoRecording completes. AndroidCameraCameraX.videoRecordingEventStreamController.add( - VideoRecordEventFinalize.pigeon_detached( - pigeon_instanceManager: PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), - ), + VideoRecordEventFinalize.pigeon_detached(), ); final XFile file = await camera.stopVideoRecording(0); @@ -4047,8 +3199,8 @@ void main() { test('stopVideoRecording throws a camera exception if ' 'no recording is in progress', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const String videoOutputPath = '/test/output/path'; + final camera = AndroidCameraCameraX(); + const videoOutputPath = '/test/output/path'; // Set directly for test versus calling startVideoCapturing. camera.recording = null; @@ -4061,9 +3213,9 @@ void main() { test('stopVideoRecording throws a camera exception if ' 'videoOutputPath is null, and sets recording to null', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockRecording mockRecording = MockRecording(); - final MockVideoCapture mockVideoCapture = MockVideoCapture(); + final camera = AndroidCameraCameraX(); + final mockRecording = MockRecording(); + final mockVideoCapture = MockVideoCapture(); // Set directly for test versus calling startVideoCapturing. camera.processCameraProvider = MockProcessCameraProvider(); @@ -4079,11 +3231,7 @@ void main() { await expectLater(() async { // Simulate video recording being finalized so stopVideoRecording completes. AndroidCameraCameraX.videoRecordingEventStreamController.add( - VideoRecordEventFinalize.pigeon_detached( - pigeon_instanceManager: PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), - ), + VideoRecordEventFinalize.pigeon_detached(), ); await camera.stopVideoRecording(0); }, throwsA(isA())); @@ -4092,12 +3240,11 @@ void main() { test('calling stopVideoRecording twice stops the recording ' 'and then throws a CameraException', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockRecording recording = MockRecording(); - final MockProcessCameraProvider processCameraProvider = - MockProcessCameraProvider(); - final MockVideoCapture videoCapture = MockVideoCapture(); - const String videoOutputPath = '/test/output/path'; + final camera = AndroidCameraCameraX(); + final recording = MockRecording(); + final processCameraProvider = MockProcessCameraProvider(); + final videoCapture = MockVideoCapture(); + const videoOutputPath = '/test/output/path'; // Set directly for test versus calling createCamera and startVideoCapturing. camera.processCameraProvider = processCameraProvider; @@ -4107,11 +3254,7 @@ void main() { // Simulate video recording being finalized so stopVideoRecording completes. AndroidCameraCameraX.videoRecordingEventStreamController.add( - VideoRecordEventFinalize.pigeon_detached( - pigeon_instanceManager: PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), - ), + VideoRecordEventFinalize.pigeon_detached(), ); final XFile file = await camera.stopVideoRecording(0); @@ -4125,12 +3268,11 @@ 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'; + final camera = AndroidCameraCameraX(); + final recording = MockRecording(); + final processCameraProvider = MockProcessCameraProvider(); + final videoCapture = MockVideoCapture(); + const videoOutputPath = '/test/output/path'; // Set directly for test versus calling createCamera and startVideoCapturing. camera.processCameraProvider = processCameraProvider; @@ -4145,11 +3287,7 @@ void main() { // Simulate video recording being finalized so stopVideoRecording completes. AndroidCameraCameraX.videoRecordingEventStreamController.add( - VideoRecordEventFinalize.pigeon_detached( - pigeon_instanceManager: PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), - ), + VideoRecordEventFinalize.pigeon_detached(), ); await camera.stopVideoRecording(90); @@ -4162,243 +3300,168 @@ void main() { ); test('setDescriptionWhileRecording changes the camera description', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockRecording mockRecording = MockRecording(); - final MockPendingRecording mockPendingRecording = MockPendingRecording(); - final MockRecorder mockRecorder = MockRecorder(); - - const int testSensorOrientation = 90; - const CameraDescription testBackCameraDescription = CameraDescription( - name: 'Camera 0', + final camera = AndroidCameraCameraX(); + final mockRecording = MockRecording(); + final mockPendingRecording = MockPendingRecording(); + final mockRecorder = MockRecorder(); + + const testSensorOrientation = 90; + const testBackCameraDescription = CameraDescription( + name: '0', lensDirection: CameraLensDirection.back, sensorOrientation: testSensorOrientation, ); - const CameraDescription testFrontCameraDescription = CameraDescription( - name: 'Camera 1', + const testFrontCameraDescription = CameraDescription( + name: '1', lensDirection: CameraLensDirection.front, sensorOrientation: testSensorOrientation, ); // Mock/Detached objects for (typically attached) objects created by // createCamera. - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockPreview mockPreview = MockPreview(); - final MockCamera mockCamera = MockCamera(); - final MockCamera newMockCamera = MockCamera(); - final MockLiveCameraState mockLiveCameraState = MockLiveCameraState(); - final MockLiveCameraState newMockLiveCameraState = MockLiveCameraState(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final MockCameraControl mockCameraControl = MockCameraControl(); - final MockImageCapture mockImageCapture = MockImageCapture(); - final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); - final MockVideoCapture mockVideoCapture = MockVideoCapture(); - final MockCameraSelector mockBackCameraSelector = MockCameraSelector(); - final MockCameraSelector mockFrontCameraSelector = MockCameraSelector(); - final MockCameraInfo mockFrontCameraInfo = MockCameraInfo(); - final MockCameraInfo mockBackCameraInfo = MockCameraInfo(); - final MockCameraCharacteristicsKey mockCameraCharacteristicsKey = + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockPreview = MockPreview(); + final mockCamera = MockCamera(); + final newMockCamera = MockCamera(); + final mockLiveCameraState = MockLiveCameraState(); + final newMockLiveCameraState = MockLiveCameraState(); + final mockCameraInfo = MockCameraInfo(); + final mockCameraControl = MockCameraControl(); + final mockImageCapture = MockImageCapture(); + final mockImageAnalysis = MockImageAnalysis(); + final mockVideoCapture = MockVideoCapture(); + final mockBackCameraSelector = MockCameraSelector(); + final mockFrontCameraSelector = MockCameraSelector(); + final mockFrontCameraInfo = MockCameraInfo(); + final mockBackCameraInfo = MockCameraInfo(); + final mockCameraCharacteristicsKey = MockCameraCharacteristicsKey(); + + const outputPath = 'file/output.mp4'; + + PigeonOverrides.preview_new = + ({ + ResolutionSelector? resolutionSelector, + int? targetRotation, + CameraIntegerRange? targetFpsRange, + }) { + when( + mockPreview.setSurfaceProvider(any), + ).thenAnswer((_) async => 19); + final testResolutionInfo = ResolutionInfo.pigeon_detached( + resolution: MockCameraSize(), + ); + when( + mockPreview.surfaceProducerHandlesCropAndRotation(), + ).thenAnswer((_) async => false); + when(mockPreview.resolutionSelector).thenReturn(resolutionSelector); + when( + mockPreview.getResolutionInfo(), + ).thenAnswer((_) async => testResolutionInfo); + return mockPreview; + }; + PigeonOverrides.imageCapture_new = + ({ + CameraXFlashMode? flashMode, + ResolutionSelector? resolutionSelector, + int? targetRotation, + }) { + return mockImageCapture; + }; + PigeonOverrides.recorder_new = + ({ + int? aspectRatio, + QualitySelector? qualitySelector, + int? targetVideoEncodingBitRate, + }) { + when( + mockRecorder.prepareRecording(outputPath), + ).thenAnswer((_) async => mockPendingRecording); + return mockRecorder; + }; + PigeonOverrides.videoCapture_withOutput = + ({ + required VideoOutput videoOutput, + CameraIntegerRange? targetFpsRange, + }) { + return mockVideoCapture; + }; + PigeonOverrides.imageAnalysis_new = + ({ + int? outputImageFormat, + ResolutionSelector? resolutionSelector, + int? targetRotation, + CameraIntegerRange? targetFpsRange, + }) { + return mockImageAnalysis; + }; + PigeonOverrides.cameraSelector_new = + ({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) { + if (cameraInfoForFilter == mockFrontCameraInfo) { + return mockFrontCameraSelector; + } + return mockBackCameraSelector; + }; + PigeonOverrides.deviceOrientationManager_new = + ({ + required void Function(DeviceOrientationManager, String) + onDeviceOrientationChanged, + }) { + final manager = MockDeviceOrientationManager(); + when(manager.getUiOrientation()).thenAnswer((_) async { + return 'PORTRAIT_UP'; + }); + return manager; + }; + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { + final camera2cameraInfo = MockCamera2CameraInfo(); + var cameraId = ''; + if (cameraInfo == mockBackCameraInfo) { + cameraId = '0'; + } else if (cameraInfo == mockFrontCameraInfo) { + cameraId = '1'; + } + when(camera2cameraInfo.getCameraId()).thenAnswer((_) async => cameraId); + when( + camera2cameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => InfoSupportedHardwareLevel.limited); + return camera2cameraInfo; + }; + PigeonOverrides.cameraCharacteristics_sensorOrientation = + mockCameraCharacteristicsKey; + GenericsPigeonOverrides.observerNew = + ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; + PigeonOverrides.systemServicesManager_new = + ({ + required void Function(SystemServicesManager, String) onCameraError, + }) { + final mockSystemServicesManager = MockSystemServicesManager(); + when( + mockSystemServicesManager.getTempFilePath( + camera.videoPrefix, + '.mp4', + ), + ).thenAnswer((_) async => outputPath); + return mockSystemServicesManager; + }; + PigeonOverrides.videoRecordEventListener_new = + ({ + required void Function(VideoRecordEventListener, VideoRecordEvent) + onEvent, + }) { + return VideoRecordEventListener.pigeon_detached(onEvent: onEvent); + }; + PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel = MockCameraCharacteristicsKey(); - const String outputPath = 'file/output.mp4'; - - camera.proxy = CameraXProxy( - newPreview: - ({ - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - ResolutionSelector? resolutionSelector, - int? targetRotation, - }) { - when( - mockPreview.setSurfaceProvider(any), - ).thenAnswer((_) async => 19); - final ResolutionInfo testResolutionInfo = - ResolutionInfo.pigeon_detached(resolution: MockCameraSize()); - when( - mockPreview.surfaceProducerHandlesCropAndRotation(), - ).thenAnswer((_) async => false); - when( - mockPreview.resolutionSelector, - ).thenReturn(resolutionSelector); - when( - mockPreview.getResolutionInfo(), - ).thenAnswer((_) async => testResolutionInfo); - return mockPreview; - }, - newImageCapture: - ({ - CameraXFlashMode? flashMode, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - ResolutionSelector? resolutionSelector, - int? targetRotation, - }) { - return mockImageCapture; - }, - newRecorder: - ({ - int? aspectRatio, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - QualitySelector? qualitySelector, - int? targetVideoEncodingBitRate, - }) { - when( - mockRecorder.prepareRecording(outputPath), - ).thenAnswer((_) async => mockPendingRecording); - return mockRecorder; - }, - withOutputVideoCapture: - ({ - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - required VideoOutput videoOutput, - }) { - return mockVideoCapture; - }, - newImageAnalysis: - ({ - int? outputImageFormat, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - ResolutionSelector? resolutionSelector, - int? targetRotation, - }) { - return mockImageAnalysis; - }, - newCameraSelector: - ({ - LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - }) { - if (cameraInfoForFilter == mockFrontCameraInfo) { - return mockFrontCameraSelector; - } - return mockBackCameraSelector; - }, - 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; - }, - 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 => InfoSupportedHardwareLevel.limited); - return camera2cameraInfo; - }, - sensorOrientationCameraCharacteristics: () { - return mockCameraCharacteristicsKey; - }, - 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, - }) { - final MockSystemServicesManager mockSystemServicesManager = - MockSystemServicesManager(); - when( - mockSystemServicesManager.getTempFilePath( - camera.videoPrefix, - '.mp4', - ), - ).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(); - }, - ); - - // mock functions - when(mockProcessCameraProvider.getAvailableCameraInfos()).thenAnswer( - (_) async => [mockBackCameraInfo, mockFrontCameraInfo], - ); - when( - mockProcessCameraProvider.bindToLifecycle(any, any), - ).thenAnswer((_) async => mockCamera); - when( - mockBackCameraSelector.filter([mockBackCameraInfo]), - ).thenAnswer((_) async => [mockBackCameraInfo]); - when( - mockBackCameraSelector.filter([mockFrontCameraInfo]), - ).thenAnswer((_) async => [mockFrontCameraInfo]); - when( - mockFrontCameraSelector.filter([mockBackCameraInfo]), - ).thenAnswer((_) async => [mockBackCameraInfo]); - when( - mockFrontCameraSelector.filter([mockFrontCameraInfo]), - ).thenAnswer((_) async => [mockFrontCameraInfo]); + // mock functions + when(mockProcessCameraProvider.getAvailableCameraInfos()).thenAnswer( + (_) async => [mockBackCameraInfo, mockFrontCameraInfo], + ); + when( + mockProcessCameraProvider.bindToLifecycle(any, any), + ).thenAnswer((_) async => mockCamera); camera.processCameraProvider = mockProcessCameraProvider; camera.liveCameraState = mockLiveCameraState; @@ -4441,11 +3504,7 @@ void main() { // Simulate video recording being started so startVideoRecording completes. AndroidCameraCameraX.videoRecordingEventStreamController.add( - VideoRecordEventStart.pigeon_detached( - pigeon_instanceManager: PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), - ), + VideoRecordEventStart.pigeon_detached(), ); await camera.availableCameras(); @@ -4478,14 +3537,14 @@ void main() { expect(camera.cameraInfo, equals(mockCameraInfo)); expect(camera.cameraControl, equals(mockCameraControl)); verify(mockLiveCameraState.removeObservers()); - for (final dynamic observer in verify( + for (final Object? observer in verify( newMockLiveCameraState.observe(captureAny), ).captured) { expect( await testCameraClosingObserver( camera, flutterSurfaceTextureId, - observer as Observer, + observer! as Observer, ), isTrue, ); @@ -4507,221 +3566,158 @@ void main() { }); test('setDescriptionWhileRecording does not resume paused preview', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockRecording mockRecording = MockRecording(); - final MockPendingRecording mockPendingRecording = MockPendingRecording(); - final MockRecorder mockRecorder = MockRecorder(); - - const int testSensorOrientation = 90; - const CameraDescription testBackCameraDescription = CameraDescription( - name: 'Camera 0', + final camera = AndroidCameraCameraX(); + final mockRecording = MockRecording(); + final mockPendingRecording = MockPendingRecording(); + final mockRecorder = MockRecorder(); + + const testSensorOrientation = 90; + const testBackCameraDescription = CameraDescription( + name: '0', lensDirection: CameraLensDirection.back, sensorOrientation: testSensorOrientation, ); - const CameraDescription testFrontCameraDescription = CameraDescription( - name: 'Camera 1', + const testFrontCameraDescription = CameraDescription( + name: '1', lensDirection: CameraLensDirection.front, sensorOrientation: testSensorOrientation, ); // Mock/Detached objects for (typically attached) objects created by // createCamera. - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockPreview mockPreview = MockPreview(); - final MockCamera mockCamera = MockCamera(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final MockCameraControl mockCameraControl = MockCameraControl(); - final MockImageCapture mockImageCapture = MockImageCapture(); - final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); - final MockVideoCapture mockVideoCapture = MockVideoCapture(); - final MockCameraSelector mockBackCameraSelector = MockCameraSelector(); - final MockCameraSelector mockFrontCameraSelector = MockCameraSelector(); - final MockCameraInfo mockFrontCameraInfo = MockCameraInfo(); - final MockCameraInfo mockBackCameraInfo = MockCameraInfo(); - final MockCameraCharacteristicsKey mockCameraCharacteristicsKey = + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockPreview = MockPreview(); + final mockCamera = MockCamera(); + final mockCameraInfo = MockCameraInfo(); + final mockCameraControl = MockCameraControl(); + final mockImageCapture = MockImageCapture(); + final mockImageAnalysis = MockImageAnalysis(); + final mockVideoCapture = MockVideoCapture(); + final mockBackCameraSelector = MockCameraSelector(); + final mockFrontCameraSelector = MockCameraSelector(); + final mockFrontCameraInfo = MockCameraInfo(); + final mockBackCameraInfo = MockCameraInfo(); + final mockCameraCharacteristicsKey = MockCameraCharacteristicsKey(); + + const outputPath = 'file/output.mp4'; + + PigeonOverrides.preview_new = + ({ + ResolutionSelector? resolutionSelector, + int? targetRotation, + CameraIntegerRange? targetFpsRange, + }) { + when( + mockPreview.setSurfaceProvider(any), + ).thenAnswer((_) async => 19); + final testResolutionInfo = ResolutionInfo.pigeon_detached( + resolution: MockCameraSize(), + ); + when( + mockPreview.surfaceProducerHandlesCropAndRotation(), + ).thenAnswer((_) async => false); + when(mockPreview.resolutionSelector).thenReturn(resolutionSelector); + when( + mockPreview.getResolutionInfo(), + ).thenAnswer((_) async => testResolutionInfo); + return mockPreview; + }; + PigeonOverrides.imageCapture_new = + ({ + CameraXFlashMode? flashMode, + ResolutionSelector? resolutionSelector, + int? targetRotation, + }) { + return mockImageCapture; + }; + PigeonOverrides.recorder_new = + ({ + int? aspectRatio, + QualitySelector? qualitySelector, + int? targetVideoEncodingBitRate, + }) { + when( + mockRecorder.prepareRecording(outputPath), + ).thenAnswer((_) async => mockPendingRecording); + return mockRecorder; + }; + PigeonOverrides.videoCapture_withOutput = + ({ + required VideoOutput videoOutput, + CameraIntegerRange? targetFpsRange, + }) { + return mockVideoCapture; + }; + PigeonOverrides.imageAnalysis_new = + ({ + int? outputImageFormat, + ResolutionSelector? resolutionSelector, + int? targetRotation, + CameraIntegerRange? targetFpsRange, + }) { + return mockImageAnalysis; + }; + PigeonOverrides.cameraSelector_new = + ({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) { + if (cameraInfoForFilter == mockFrontCameraInfo) { + return mockFrontCameraSelector; + } + return mockBackCameraSelector; + }; + PigeonOverrides.deviceOrientationManager_new = + ({ + required void Function(DeviceOrientationManager, String) + onDeviceOrientationChanged, + }) { + final manager = MockDeviceOrientationManager(); + when(manager.getUiOrientation()).thenAnswer((_) async { + return 'PORTRAIT_UP'; + }); + return manager; + }; + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { + final camera2cameraInfo = MockCamera2CameraInfo(); + var cameraId = ''; + if (cameraInfo == mockBackCameraInfo) { + cameraId = '0'; + } else if (cameraInfo == mockFrontCameraInfo) { + cameraId = '1'; + } + when(camera2cameraInfo.getCameraId()).thenAnswer((_) async => cameraId); + when( + camera2cameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => InfoSupportedHardwareLevel.limited); + return camera2cameraInfo; + }; + PigeonOverrides.cameraCharacteristics_sensorOrientation = + mockCameraCharacteristicsKey; + GenericsPigeonOverrides.observerNew = + ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; + PigeonOverrides.systemServicesManager_new = + ({ + required void Function(SystemServicesManager, String) onCameraError, + }) { + final mockSystemServicesManager = MockSystemServicesManager(); + when( + mockSystemServicesManager.getTempFilePath( + camera.videoPrefix, + '.mp4', + ), + ).thenAnswer((_) async => outputPath); + return mockSystemServicesManager; + }; + PigeonOverrides.videoRecordEventListener_new = + ({ + required void Function(VideoRecordEventListener, VideoRecordEvent) + onEvent, + }) { + return VideoRecordEventListener.pigeon_detached(onEvent: onEvent); + }; + PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel = MockCameraCharacteristicsKey(); - const String outputPath = 'file/output.mp4'; - - camera.proxy = CameraXProxy( - newPreview: - ({ - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - ResolutionSelector? resolutionSelector, - int? targetRotation, - }) { - when( - mockPreview.setSurfaceProvider(any), - ).thenAnswer((_) async => 19); - final ResolutionInfo testResolutionInfo = - ResolutionInfo.pigeon_detached(resolution: MockCameraSize()); - when( - mockPreview.surfaceProducerHandlesCropAndRotation(), - ).thenAnswer((_) async => false); - when( - mockPreview.resolutionSelector, - ).thenReturn(resolutionSelector); - when( - mockPreview.getResolutionInfo(), - ).thenAnswer((_) async => testResolutionInfo); - return mockPreview; - }, - newImageCapture: - ({ - CameraXFlashMode? flashMode, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - ResolutionSelector? resolutionSelector, - int? targetRotation, - }) { - return mockImageCapture; - }, - newRecorder: - ({ - int? aspectRatio, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - QualitySelector? qualitySelector, - int? targetVideoEncodingBitRate, - }) { - when( - mockRecorder.prepareRecording(outputPath), - ).thenAnswer((_) async => mockPendingRecording); - return mockRecorder; - }, - withOutputVideoCapture: - ({ - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - required VideoOutput videoOutput, - }) { - return mockVideoCapture; - }, - newImageAnalysis: - ({ - int? outputImageFormat, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - ResolutionSelector? resolutionSelector, - int? targetRotation, - }) { - return mockImageAnalysis; - }, - newCameraSelector: - ({ - LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - }) { - if (cameraInfoForFilter == mockFrontCameraInfo) { - return mockFrontCameraSelector; - } - return mockBackCameraSelector; - }, - 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; - }, - 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 => InfoSupportedHardwareLevel.limited); - return camera2cameraInfo; - }, - sensorOrientationCameraCharacteristics: () { - return mockCameraCharacteristicsKey; - }, - 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, - }) { - final MockSystemServicesManager mockSystemServicesManager = - MockSystemServicesManager(); - when( - mockSystemServicesManager.getTempFilePath( - camera.videoPrefix, - '.mp4', - ), - ).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(); - }, - ); - // mock functions when(mockProcessCameraProvider.getAvailableCameraInfos()).thenAnswer( (_) async => [mockBackCameraInfo, mockFrontCameraInfo], @@ -4729,18 +3725,6 @@ void main() { when( mockProcessCameraProvider.bindToLifecycle(any, any), ).thenAnswer((_) async => mockCamera); - when( - mockBackCameraSelector.filter([mockBackCameraInfo]), - ).thenAnswer((_) async => [mockBackCameraInfo]); - when( - mockBackCameraSelector.filter([mockFrontCameraInfo]), - ).thenAnswer((_) async => [mockFrontCameraInfo]); - when( - mockFrontCameraSelector.filter([mockBackCameraInfo]), - ).thenAnswer((_) async => [mockBackCameraInfo]); - when( - mockFrontCameraSelector.filter([mockFrontCameraInfo]), - ).thenAnswer((_) async => [mockFrontCameraInfo]); camera.processCameraProvider = mockProcessCameraProvider; camera.enableRecordingAudio = false; @@ -4770,11 +3754,7 @@ void main() { // Simulate video recording being started so startVideoRecording completes. AndroidCameraCameraX.videoRecordingEventStreamController.add( - VideoRecordEventStart.pigeon_detached( - pigeon_instanceManager: PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), - ), + VideoRecordEventStart.pigeon_detached(), ); await camera.availableCameras(); @@ -4808,39 +3788,32 @@ void main() { 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'; + final camera = AndroidCameraCameraX(); + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockCamera = MockCamera(); + final mockCameraInfo = MockCameraInfo(); + final mockImageCapture = MockImageCapture(); + const testPicturePath = 'test/absolute/path/to/picture'; // Set directly for test versus calling createCamera. - camera.imageCapture = MockImageCapture(); + camera.imageCapture = mockImageCapture; camera.processCameraProvider = mockProcessCameraProvider; camera.cameraSelector = MockCameraSelector(); // Ignore setting target rotation for this test; tested seprately. camera.captureOrientationLocked = true; - // 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: (_) {}, - ), - ); - }, - ); + // Tell plugin to create detached camera state observers and mock systemServicesManager. + GenericsPigeonOverrides.observerNew = + ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; + PigeonOverrides.systemServicesManager_new = + ({ + required void Function(SystemServicesManager, String) onCameraError, + }) { + return MockSystemServicesManager(); + }; when( mockProcessCameraProvider.isBound(camera.imageCapture), @@ -4856,7 +3829,7 @@ void main() { mockCameraInfo.getCameraState(), ).thenAnswer((_) async => MockLiveCameraState()); when( - camera.imageCapture!.takePicture(), + mockImageCapture.takePicture(argThat(isA())), ).thenAnswer((_) async => testPicturePath); final XFile imageFile = await camera.takePicture(3); @@ -4868,43 +3841,41 @@ void main() { test( 'takePicture sets ImageCapture target rotation as expected when orientation locked or unlocked', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockImageCapture mockImageCapture = MockImageCapture(); - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); + final camera = AndroidCameraCameraX(); + final mockImageCapture = MockImageCapture(); + final mockProcessCameraProvider = MockProcessCameraProvider(); - const int cameraId = 3; + const cameraId = 3; const int defaultTargetRotation = Surface.rotation180; // Set directly for test versus calling createCamera. camera.imageCapture = mockImageCapture; camera.processCameraProvider = mockProcessCameraProvider; - // 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; - }, - ); + // Tell plugin to mock call to get current photo orientation and systemServicesManager. + PigeonOverrides.deviceOrientationManager_new = + ({ + required void Function(DeviceOrientationManager, String) + onDeviceOrientationChanged, + }) { + final mockDeviceOrientationManager = MockDeviceOrientationManager(); + when( + mockDeviceOrientationManager.getDefaultDisplayRotation(), + ).thenAnswer((_) async => defaultTargetRotation); + return mockDeviceOrientationManager; + }; + PigeonOverrides.systemServicesManager_new = + ({ + required void Function(SystemServicesManager, String) onCameraError, + }) { + return MockSystemServicesManager(); + }; when( mockProcessCameraProvider.isBound(camera.imageCapture), ).thenAnswer((_) async => true); when( - camera.imageCapture!.takePicture(), + mockImageCapture.takePicture(argThat(isA())), ).thenAnswer((_) async => 'test/absolute/path/to/picture'); // Orientation is unlocked and plugin does not need to set default target @@ -4937,10 +3908,9 @@ void main() { 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; + final camera = AndroidCameraCameraX(); + final mockProcessCameraProvider = MockProcessCameraProvider(); + const cameraId = 77; // Set directly for test versus calling createCamera. camera.imageCapture = MockImageCapture(); @@ -4950,6 +3920,14 @@ void main() { // Ignore setting target rotation for this test; tested seprately. camera.captureOrientationLocked = true; + // Tell plugin to mock call to get systemServicesManager. + PigeonOverrides.systemServicesManager_new = + ({ + required void Function(SystemServicesManager, String) onCameraError, + }) { + return MockSystemServicesManager(); + }; + when( mockProcessCameraProvider.isBound(camera.imageCapture), ).thenAnswer((_) async => true); @@ -4963,11 +3941,10 @@ void main() { 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(); + final camera = AndroidCameraCameraX(); + const cameraId = 22; + final mockCameraControl = MockCameraControl(); + final mockProcessCameraProvider = MockProcessCameraProvider(); // Set directly for test versus calling createCamera. camera.imageCapture = MockImageCapture(); @@ -4977,6 +3954,14 @@ void main() { camera.captureOrientationLocked = true; camera.processCameraProvider = mockProcessCameraProvider; + // Tell plugin to mock call to get current photo orientation and systemServicesManager. + PigeonOverrides.systemServicesManager_new = + ({ + required void Function(SystemServicesManager, String) onCameraError, + }) { + return MockSystemServicesManager(); + }; + when( mockProcessCameraProvider.isBound(camera.imageCapture), ).thenAnswer((_) async => true); @@ -5010,9 +3995,9 @@ void main() { ); test('setFlashMode turns on torch mode as expected', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 44; - final MockCameraControl mockCameraControl = MockCameraControl(); + final camera = AndroidCameraCameraX(); + const cameraId = 44; + final mockCameraControl = MockCameraControl(); // Set directly for test versus calling createCamera. camera.cameraControl = mockCameraControl; @@ -5026,9 +4011,9 @@ void main() { 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(); + final camera = AndroidCameraCameraX(); + const cameraId = 33; + final mockCameraControl = MockCameraControl(); // Set directly for test versus calling createCamera. camera.cameraControl = mockCameraControl; @@ -5052,19 +4037,15 @@ void main() { ); test('getMinExposureOffset returns expected exposure offset', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final ExposureState exposureState = ExposureState.pigeon_detached( + final camera = AndroidCameraCameraX(); + final mockCameraInfo = MockCameraInfo(); + + final 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. @@ -5078,19 +4059,15 @@ void main() { }); test('getMaxExposureOffset returns expected exposure offset', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final ExposureState exposureState = ExposureState.pigeon_detached( + final camera = AndroidCameraCameraX(); + final mockCameraInfo = MockCameraInfo(); + + final 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. @@ -5103,19 +4080,15 @@ void main() { }); test('getExposureOffsetStepSize returns expected exposure offset', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final ExposureState exposureState = ExposureState.pigeon_detached( + final camera = AndroidCameraCameraX(); + final mockCameraInfo = MockCameraInfo(); + + final 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. @@ -5129,19 +4102,14 @@ void main() { test( '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( + final camera = AndroidCameraCameraX(); + final mockCameraInfo = MockCameraInfo(); + final 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. @@ -5154,16 +4122,13 @@ void main() { ); test('getMaxZoomLevel returns expected exposure offset', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final camera = AndroidCameraCameraX(); + final mockCameraInfo = MockCameraInfo(); const double maxZoomRatio = 1; final LiveData mockLiveZoomState = MockLiveZoomState(); - final ZoomState zoomState = ZoomState.pigeon_detached( + final zoomState = ZoomState.pigeon_detached( maxZoomRatio: maxZoomRatio, minZoomRatio: 0, - pigeon_instanceManager: PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), ); // Set directly for test versus calling createCamera. @@ -5178,16 +4143,13 @@ void main() { }); test('getMinZoomLevel returns expected exposure offset', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final camera = AndroidCameraCameraX(); + final mockCameraInfo = MockCameraInfo(); const double minZoomRatio = 0; final LiveData mockLiveZoomState = MockLiveZoomState(); - final ZoomState zoomState = ZoomState.pigeon_detached( + final zoomState = ZoomState.pigeon_detached( maxZoomRatio: 1, minZoomRatio: minZoomRatio, - pigeon_instanceManager: PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), ); // Set directly for test versus calling createCamera. @@ -5202,10 +4164,10 @@ void main() { }); test('setZoomLevel sets zoom ratio as expected', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 44; - const double zoomRatio = 0.3; - final MockCameraControl mockCameraControl = MockCameraControl(); + final camera = AndroidCameraCameraX(); + const cameraId = 44; + const zoomRatio = 0.3; + final mockCameraControl = MockCameraControl(); // Set directly for test versus calling createCamera. camera.cameraControl = mockCameraControl; @@ -5215,39 +4177,306 @@ void main() { verify(mockCameraControl.setZoomRatio(zoomRatio)); }); - test('Should report support for image streaming', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - expect(camera.supportsImageStreaming(), true); - }); + test('setVideoStabilizationMode sets mode expected', () async { + final camera = AndroidCameraCameraX(); + const cameraId = 98; + final mockCameraControl = MockCameraControl(); + final mockCamera2CameraControl = MockCamera2CameraControl(); + final mockCameraInfo = MockCameraInfo(); + final mockCamera2CameraInfo = MockCamera2CameraInfo(); + + // Set directly for test versus calling createCamera. + camera.camera = MockCamera(); + camera.cameraControl = mockCameraControl; + camera.cameraInfo = mockCameraInfo; + + // Tell plugin to create detached Camera2CameraControl and + // CaptureRequestOptions instances for testing. + final controlVideoStabilizationModeKey = + CaptureRequestKey.pigeon_detached(); + PigeonOverrides.camera2CameraControl_from = + ({required CameraControl cameraControl}) => + cameraControl == mockCameraControl + ? mockCamera2CameraControl + : Camera2CameraControl.pigeon_detached(); + PigeonOverrides.captureRequestOptions_new = + ({required Map options}) { + final mockCaptureRequestOptions = MockCaptureRequestOptions(); + options.forEach((CaptureRequestKey key, Object? value) { + when( + mockCaptureRequestOptions.getCaptureRequestOption(key), + ).thenAnswer((_) async => value); + }); + return mockCaptureRequestOptions; + }; + PigeonOverrides.captureRequest_controlVideoStabilizationMode = + controlVideoStabilizationModeKey; + + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { + when( + mockCamera2CameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => [0, 1, 2]); + return mockCamera2CameraInfo; + }; + PigeonOverrides + .cameraCharacteristics_controlAvailableVideoStabilizationModes = + MockCameraCharacteristicsKey(); + + // Test off. + await camera.setVideoStabilizationMode( + cameraId, + VideoStabilizationMode.off, + ); + + VerificationResult verificationResult = verify( + mockCamera2CameraControl.addCaptureRequestOptions(captureAny), + ); + var capturedCaptureRequestOptions = + verificationResult.captured.single as CaptureRequestOptions; + expect( + await capturedCaptureRequestOptions.getCaptureRequestOption( + controlVideoStabilizationModeKey, + ), + equals(0), + ); + + clearInteractions(mockCamera2CameraControl); + + // Test level1. + await camera.setVideoStabilizationMode( + cameraId, + VideoStabilizationMode.level1, + ); + + verificationResult = verify( + mockCamera2CameraControl.addCaptureRequestOptions(captureAny), + ); + capturedCaptureRequestOptions = + verificationResult.captured.single as CaptureRequestOptions; + expect( + await capturedCaptureRequestOptions.getCaptureRequestOption( + controlVideoStabilizationModeKey, + ), + equals(1), + ); + }); + + test( + 'setVideoStabilizationMode throws ArgumentError when mode not available', + () async { + final camera = AndroidCameraCameraX(); + const cameraId = 102; + final mockCameraControl = MockCameraControl(); + final mockCamera2CameraControl = MockCamera2CameraControl(); + final mockCameraInfo = MockCameraInfo(); + final mockCamera2CameraInfo = MockCamera2CameraInfo(); + + // Set directly for test versus calling createCamera. + camera.camera = MockCamera(); + camera.cameraControl = mockCameraControl; + camera.cameraInfo = mockCameraInfo; + + // Tell plugin to create detached Camera2CameraControl and + // CaptureRequestOptions instances for testing. + final controlVideoStabilizationModeKey = + CaptureRequestKey.pigeon_detached(); + PigeonOverrides.camera2CameraControl_from = + ({required CameraControl cameraControl}) => + cameraControl == mockCameraControl + ? mockCamera2CameraControl + : Camera2CameraControl.pigeon_detached(); + PigeonOverrides.captureRequestOptions_new = + ({required Map options}) { + final mockCaptureRequestOptions = MockCaptureRequestOptions(); + options.forEach((CaptureRequestKey key, Object? value) { + when( + mockCaptureRequestOptions.getCaptureRequestOption(key), + ).thenAnswer((_) async => value); + }); + return mockCaptureRequestOptions; + }; + PigeonOverrides.captureRequest_controlVideoStabilizationMode = + controlVideoStabilizationModeKey; + + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { + when( + mockCamera2CameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => [0]); + return mockCamera2CameraInfo; + }; + PigeonOverrides + .cameraCharacteristics_controlAvailableVideoStabilizationModes = + MockCameraCharacteristicsKey(); + expect( + () => camera.setVideoStabilizationMode( + cameraId, + VideoStabilizationMode.level1, + ), + throwsA( + isA().having( + (ArgumentError e) => e.name, + 'name', + 'mode', + ), + ), + ); + }, + ); + + test( + 'setVideoStabilizationMode throws ArgumentError when mode not mapped', + () async { + final camera = AndroidCameraCameraX(); + const cameraId = 102; + final mockCameraControl = MockCameraControl(); + final mockCamera2CameraControl = MockCamera2CameraControl(); + final mockCameraInfo = MockCameraInfo(); + final mockCamera2CameraInfo = MockCamera2CameraInfo(); + + // Set directly for test versus calling createCamera. + camera.camera = MockCamera(); + camera.cameraControl = mockCameraControl; + camera.cameraInfo = mockCameraInfo; + + // Tell plugin to create detached Camera2CameraControl and + // CaptureRequestOptions instances for testing. + final controlVideoStabilizationModeKey = + CaptureRequestKey.pigeon_detached(); + PigeonOverrides.camera2CameraControl_from = + ({required CameraControl cameraControl}) => + cameraControl == mockCameraControl + ? mockCamera2CameraControl + : Camera2CameraControl.pigeon_detached(); + PigeonOverrides.captureRequestOptions_new = + ({required Map options}) { + final mockCaptureRequestOptions = MockCaptureRequestOptions(); + options.forEach((CaptureRequestKey key, Object? value) { + when( + mockCaptureRequestOptions.getCaptureRequestOption(key), + ).thenAnswer((_) async => value); + }); + return mockCaptureRequestOptions; + }; + PigeonOverrides.captureRequest_controlVideoStabilizationMode = + controlVideoStabilizationModeKey; + + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { + when( + mockCamera2CameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => [0, 1, 2]); + return mockCamera2CameraInfo; + }; + PigeonOverrides + .cameraCharacteristics_controlAvailableVideoStabilizationModes = + MockCameraCharacteristicsKey(); + + expect( + () => camera.setVideoStabilizationMode( + cameraId, + VideoStabilizationMode.level2, + ), + throwsA( + isA().having( + (ArgumentError e) => e.name, + 'name', + 'mode', + ), + ), + ); + expect( + () => camera.setVideoStabilizationMode( + cameraId, + VideoStabilizationMode.level3, + ), + throwsA( + isA().having( + (ArgumentError e) => e.name, + 'name', + 'mode', + ), + ), + ); + }, + ); + + test('getVideoStabilizationMode returns no available mode', () async { + // Set up mocks and constants. + final camera = AndroidCameraCameraX(); + final mockCameraInfo = MockCameraInfo(); + final mockCamera2cameraInfo = MockCamera2CameraInfo(); + + // Set directly for test versus calling createCamera. + camera.cameraInfo = mockCameraInfo; + + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { + when( + mockCamera2cameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => []); + return mockCamera2cameraInfo; + }; + PigeonOverrides + .cameraCharacteristics_controlAvailableVideoStabilizationModes = + MockCameraCharacteristicsKey(); + + const cameraId = 103; + + final Iterable modes = await camera + .getSupportedVideoStabilizationModes(cameraId); + + expect(modes, orderedEquals([])); + }); + + test('getVideoStabilizationMode returns all available modes', () async { + // Set up mocks and constants. + final camera = AndroidCameraCameraX(); + final mockCameraInfo = MockCameraInfo(); + final mockCamera2CameraInfo = MockCamera2CameraInfo(); + const cameraId = 104; + + // Set directly for test versus calling createCamera. + camera.cameraInfo = mockCameraInfo; + + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { + when( + mockCamera2CameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => [0, 1, 2]); + return mockCamera2CameraInfo; + }; + PigeonOverrides + .cameraCharacteristics_controlAvailableVideoStabilizationModes = + MockCameraCharacteristicsKey(); + + final Iterable modes = await camera + .getSupportedVideoStabilizationModes(cameraId); + + expect( + modes, + orderedEquals([ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + ]), + ); + }); + + test('Should report support for image streaming', () async { + final camera = AndroidCameraCameraX(); + expect(camera.supportsImageStreaming(), true); + }); 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; + final camera = AndroidCameraCameraX(); + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockCamera = MockCamera(); + final mockCameraInfo = MockCameraInfo(); + const cameraId = 22; // 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: (_) {}, - ), - ); - }, - ); + PigeonOverrides.analyzer_new = + ({required void Function(Analyzer, ImageProxy) analyze}) { + return Analyzer.pigeon_detached(analyze: analyze); + }; // Set directly for test versus calling createCamera. camera.processCameraProvider = mockProcessCameraProvider; @@ -5273,8 +4502,7 @@ void main() { final CameraImageData mockCameraImageData = MockCameraImageData(); final Stream imageStream = camera .onStreamedFrameAvailable(cameraId); - final StreamQueue streamQueue = - StreamQueue(imageStream); + final streamQueue = StreamQueue(imageStream); camera.cameraImageDataStreamController!.add(mockCameraImageData); @@ -5286,29 +4514,15 @@ void main() { test( 'onStreamedFrameAvailable emits CameraImageData when listened to after cancelation', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - const int cameraId = 22; + final camera = AndroidCameraCameraX(); + final mockProcessCameraProvider = MockProcessCameraProvider(); + const cameraId = 22; // 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: (_) {}, - ), - ); - }, - ); + PigeonOverrides.analyzer_new = + ({required void Function(Analyzer, ImageProxy) analyze}) { + return Analyzer.pigeon_detached(analyze: analyze); + }; // Set directly for test versus calling createCamera. camera.processCameraProvider = mockProcessCameraProvider; @@ -5336,8 +4550,7 @@ void main() { .onStreamedFrameAvailable(cameraId); // Listen to image stream again. - final StreamQueue streamQueue = - StreamQueue(imageStream2); + final streamQueue = StreamQueue(imageStream2); camera.cameraImageDataStreamController!.add(mockCameraImageData); expect(await streamQueue.next, equals(mockCameraImageData)); @@ -5348,57 +4561,33 @@ void main() { test( 'onStreamedFrameAvailable returns stream that responds expectedly to being listened to', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 33; + final camera = AndroidCameraCameraX(); + const cameraId = 33; final ProcessCameraProvider mockProcessCameraProvider = MockProcessCameraProvider(); final CameraSelector mockCameraSelector = MockCameraSelector(); - final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); + final 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; + final mockImageProxy = MockImageProxy(); + final mockPlane = MockPlaneProxy(); + final mockPlanes = [mockPlane]; + final buffer = Uint8List(0); + const pixelStride = 27; + const rowStride = 58; + const imageFormat = 582; + const imageHeight = 100; + const imageWidth = 200; // 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: (_) {}, - ), - ); - }, - ); + PigeonOverrides.analyzer_new = + ({required void Function(Analyzer, ImageProxy) analyze}) { + return Analyzer.pigeon_detached(analyze: analyze); + }; + GenericsPigeonOverrides.observerNew = + ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; // Set directly for test versus calling createCamera. camera.processCameraProvider = mockProcessCameraProvider; @@ -5430,8 +4619,7 @@ void main() { when(mockImageProxy.height).thenReturn(imageHeight); when(mockImageProxy.width).thenReturn(imageWidth); - final Completer imageDataCompleter = - Completer(); + final imageDataCompleter = Completer(); final StreamSubscription onStreamedFrameAvailableSubscription = camera .onStreamedFrameAvailable(cameraId) @@ -5441,7 +4629,7 @@ void main() { // Test ImageAnalysis use case is bound to ProcessCameraProvider. await untilCalled(mockImageAnalysis.setAnalyzer(any)); - final Analyzer capturedAnalyzer = + final capturedAnalyzer = verify(mockImageAnalysis.setAnalyzer(captureAny)).captured.single as Analyzer; @@ -5464,21 +4652,16 @@ void main() { test( 'onStreamedFrameAvailable emits NV21 CameraImageData with correct format and single plane when initialized with NV21', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 42; - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); - final MockCamera mockCamera = MockCamera(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final MockImageProxy mockImageProxy = MockImageProxy(); - final MockPlaneProxy mockPlane = MockPlaneProxy(); - final List mockPlanes = [ - mockPlane, - mockPlane, - mockPlane, - ]; - final Uint8List testNv21Buffer = Uint8List(10); + final camera = AndroidCameraCameraX(); + const cameraId = 42; + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockImageAnalysis = MockImageAnalysis(); + final mockCamera = MockCamera(); + final mockCameraInfo = MockCameraInfo(); + final mockImageProxy = MockImageProxy(); + final mockPlane = MockPlaneProxy(); + final mockPlanes = [mockPlane, mockPlane, mockPlane]; + final testNv21Buffer = Uint8List(10); // Mock use case bindings and related Camera objects. when( @@ -5490,43 +4673,21 @@ void main() { ).thenAnswer((_) async => MockLiveCameraState()); // Set up CameraXProxy with ImageAnalysis specifics needed for testing its Analyzer. - camera.proxy = getProxyForTestingUseCaseConfiguration( + setUpOverridesForTestingUseCaseConfiguration( mockProcessCameraProvider, - 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: (_) {}, - ), - ); - }, + newAnalyzer: ({required void Function(Analyzer, ImageProxy) analyze}) { + return Analyzer.pigeon_detached(analyze: analyze); + }, newImageAnalysis: ({ int? outputImageFormat, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, ResolutionSelector? resolutionSelector, int? targetRotation, + CameraIntegerRange? targetFpsRange, }) => mockImageAnalysis, getNv21BufferImageProxyUtils: - ( - int imageWidth, - int imageHeight, - List planes, { - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - }) => Future.value(testNv21Buffer), + (int imageWidth, int imageHeight, List planes) => + Future.value(testNv21Buffer), ); // Create and initialize camera with NV21. @@ -5548,8 +4709,7 @@ void main() { when(mockImageProxy.getPlanes()).thenAnswer((_) async => mockPlanes); // Set up listener to receive mock ImageProxy. - final Completer imageDataCompleter = - Completer(); + final imageDataCompleter = Completer(); final StreamSubscription subscription = camera .onStreamedFrameAvailable(cameraId) .listen((CameraImageData imageData) { @@ -5557,7 +4717,7 @@ void main() { }); await untilCalled(mockImageAnalysis.setAnalyzer(any)); - final Analyzer capturedAnalyzer = + final capturedAnalyzer = verify(mockImageAnalysis.setAnalyzer(captureAny)).captured.single as Analyzer; capturedAnalyzer.analyze(MockAnalyzer(), mockImageProxy); @@ -5576,30 +4736,22 @@ void main() { 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(); + final camera = AndroidCameraCameraX(); + const cameraId = 32; + final mockImageAnalysis = MockImageAnalysis(); + final mockProcessCameraProvider = MockProcessCameraProvider(); // Set directly for test versus calling createCamera. camera.imageAnalysis = mockImageAnalysis; camera.processCameraProvider = mockProcessCameraProvider; - // Ignore setting target rotation for this test; tested seprately. + // Ignore setting target rotation for this test; tested separately. 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(), - ); + PigeonOverrides.analyzer_new = + ({required void Function(Analyzer, ImageProxy) analyze}) => + MockAnalyzer(); when( mockProcessCameraProvider.isBound(mockImageAnalysis), @@ -5618,12 +4770,11 @@ void main() { test( 'onStreamedFrameAvailable sets ImageAnalysis target rotation to current photo orientation when orientation unlocked', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 35; + final camera = AndroidCameraCameraX(); + const cameraId = 35; const int defaultTargetRotation = Surface.rotation90; - final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); + final mockImageAnalysis = MockImageAnalysis(); + final mockProcessCameraProvider = MockProcessCameraProvider(); // Set directly for test versus calling createCamera. camera.imageAnalysis = mockImageAnalysis; @@ -5631,32 +4782,20 @@ void main() { // 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; - }, - ); + PigeonOverrides.analyzer_new = + ({required void Function(Analyzer, ImageProxy) analyze}) => + MockAnalyzer(); + PigeonOverrides.deviceOrientationManager_new = + ({ + required void Function(DeviceOrientationManager, String) + onDeviceOrientationChanged, + }) { + final manager = MockDeviceOrientationManager(); + when(manager.getDefaultDisplayRotation()).thenAnswer((_) async { + return defaultTargetRotation; + }); + return manager; + }; when( mockProcessCameraProvider.isBound(mockImageAnalysis), @@ -5709,12 +4848,12 @@ void main() { test( 'lockCaptureOrientation sets capture-related use case target rotations to correct orientation', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 44; + final camera = AndroidCameraCameraX(); + const cameraId = 44; - final MockImageAnalysis mockImageAnalysis = MockImageAnalysis(); - final MockImageCapture mockImageCapture = MockImageCapture(); - final MockVideoCapture mockVideoCapture = MockVideoCapture(); + final mockImageAnalysis = MockImageAnalysis(); + final mockImageCapture = MockImageCapture(); + final mockVideoCapture = MockVideoCapture(); // Set directly for test versus calling createCamera. camera.imageAnalysis = mockImageAnalysis; @@ -5752,8 +4891,8 @@ void main() { test( 'unlockCaptureOrientation sets capture-related use case target rotations to current photo/video orientation', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 57; + final camera = AndroidCameraCameraX(); + const cameraId = 57; camera.captureOrientationLocked = true; await camera.unlockCaptureOrientation(cameraId); @@ -5764,11 +4903,10 @@ void main() { 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(); + final camera = AndroidCameraCameraX(); + const cameraId = 78; + final mockCameraControl = MockCameraControl(); + final mockCamera2CameraControl = MockCamera2CameraControl(); // Set directly for test versus calling createCamera. camera.camera = MockCamera(); @@ -5776,45 +4914,23 @@ void main() { // 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, - ); + final controlAELockKey = CaptureRequestKey.pigeon_detached(); + PigeonOverrides.camera2CameraControl_from = + ({required CameraControl cameraControl}) => + cameraControl == mockCameraControl + ? mockCamera2CameraControl + : Camera2CameraControl.pigeon_detached(); + PigeonOverrides.captureRequestOptions_new = + ({required Map options}) { + final mockCaptureRequestOptions = MockCaptureRequestOptions(); + options.forEach((CaptureRequestKey key, Object? value) { + when( + mockCaptureRequestOptions.getCaptureRequestOption(key), + ).thenAnswer((_) async => value); + }); + return mockCaptureRequestOptions; + }; + PigeonOverrides.captureRequest_controlAELock = controlAELockKey; // Test auto mode. await camera.setExposureMode(cameraId, ExposureMode.auto); @@ -5822,7 +4938,7 @@ void main() { VerificationResult verificationResult = verify( mockCamera2CameraControl.addCaptureRequestOptions(captureAny), ); - CaptureRequestOptions capturedCaptureRequestOptions = + var capturedCaptureRequestOptions = verificationResult.captured.single as CaptureRequestOptions; expect( await capturedCaptureRequestOptions.getCaptureRequestOption( @@ -5852,41 +4968,29 @@ void main() { 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(); + final camera = AndroidCameraCameraX(); + const cameraId = 93; + final mockCameraControl = MockCameraControl(); + final mockCameraInfo = MockCameraInfo(); // Set directly for test versus calling createCamera. camera.cameraControl = mockCameraControl; camera.cameraInfo = mockCameraInfo; - final MockFocusMeteringActionBuilder mockActionBuilder = - MockFocusMeteringActionBuilder(); - final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); + final mockActionBuilder = MockFocusMeteringActionBuilder(); 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( + setUpOverridesForExposureAndFocus( withModeFocusMeteringActionBuilder: - ({ - required MeteringMode mode, - required MeteringPoint point, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - }) { + ({required MeteringMode mode, required MeteringPoint point}) { actionBuilderMeteringMode = mode; actionBuilderMeteringPoint = point; return mockActionBuilder; @@ -5900,22 +5004,12 @@ void main() { 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, - ); + final originalMeteringAction = FocusMeteringAction.pigeon_detached( + meteringPointsAe: [MeteringPoint.pigeon_detached()], + meteringPointsAf: [MeteringPoint.pigeon_detached()], + meteringPointsAwb: const [], + isAutoCancelEnabled: false, + ); camera.currentFocusMeteringAction = originalMeteringAction; await camera.setExposurePoint(cameraId, null); @@ -5931,15 +5025,10 @@ void main() { // 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, - ), - ], + meteringPointsAe: [MeteringPoint.pigeon_detached()], meteringPointsAf: const [], meteringPointsAwb: const [], isAutoCancelEnabled: false, - pigeon_instanceManager: testInstanceManager, ); await camera.setExposurePoint(cameraId, null); @@ -5951,16 +5040,16 @@ void main() { 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); + final camera = AndroidCameraCameraX(); + const cameraId = 23; + final mockCameraControl = MockCameraControl(); + const invalidExposurePoint = Point(3, -1); // Set directly for test versus calling createCamera. camera.cameraControl = mockCameraControl; camera.cameraInfo = MockCameraInfo(); - camera.proxy = getProxyForExposureAndFocus(); + setUpOverridesForExposureAndFocus(); expect( () => camera.setExposurePoint(cameraId, invalidExposurePoint), @@ -5972,63 +5061,44 @@ void main() { 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(); + final camera = AndroidCameraCameraX(); + const cameraId = 9; + final mockCameraControl = MockCameraControl(); + final mockCameraInfo = MockCameraInfo(); // Set directly for test versus calling createCamera. camera.cameraControl = mockCameraControl; camera.cameraInfo = mockCameraInfo; - final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - double exposurePointX = 0.8; - double exposurePointY = 0.1; - final MeteringPoint createdMeteringPoint = MeteringPoint.pigeon_detached( - pigeon_instanceManager: testInstanceManager, - ); + var exposurePointX = 0.8; + var exposurePointY = 0.1; + final createdMeteringPoint = MeteringPoint.pigeon_detached(); MeteringMode? actionBuilderMeteringMode; MeteringPoint? actionBuilderMeteringPoint; - final MockFocusMeteringActionBuilder mockActionBuilder = - MockFocusMeteringActionBuilder(); + final mockActionBuilder = MockFocusMeteringActionBuilder(); when(mockActionBuilder.build()).thenAnswer( (_) async => FocusMeteringAction.pigeon_detached( meteringPointsAe: const [], meteringPointsAf: const [], meteringPointsAwb: const [], isAutoCancelEnabled: false, - pigeon_instanceManager: testInstanceManager, ), ); - camera.proxy = getProxyForExposureAndFocus( + setUpOverridesForExposureAndFocus( newDisplayOrientedMeteringPointFactory: ({ - required CameraInfo cameraInfo, + required dynamic 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(); + final 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, - }) { + ({required MeteringMode mode, required MeteringPoint point}) { actionBuilderMeteringMode = mode; actionBuilderMeteringPoint = point; return mockActionBuilder; @@ -6036,26 +5106,13 @@ void main() { ); // 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, - ); + var exposurePoint = Point(exposurePointX, exposurePointY); + var originalMeteringAction = FocusMeteringAction.pigeon_detached( + meteringPointsAe: [MeteringPoint.pigeon_detached()], + meteringPointsAf: [MeteringPoint.pigeon_detached()], + meteringPointsAwb: const [], + isAutoCancelEnabled: false, + ); camera.currentFocusMeteringAction = originalMeteringAction; await camera.setExposurePoint(cameraId, exposurePoint); @@ -6079,14 +5136,9 @@ void main() { exposurePoint = Point(exposurePointX, exposurePointY); originalMeteringAction = FocusMeteringAction.pigeon_detached( meteringPointsAe: const [], - meteringPointsAf: [ - MeteringPoint.pigeon_detached( - pigeon_instanceManager: testInstanceManager, - ), - ], + meteringPointsAf: [MeteringPoint.pigeon_detached()], meteringPointsAwb: const [], isAutoCancelEnabled: false, - pigeon_instanceManager: testInstanceManager, ); camera.currentFocusMeteringAction = originalMeteringAction; @@ -6109,67 +5161,45 @@ void main() { 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, - ); + final camera = AndroidCameraCameraX(); + const cameraId = 19; + final mockCameraControl = MockCameraControl(); + const exposurePointX = 0.8; + const exposurePointY = 0.1; + const exposurePoint = Point(exposurePointX, exposurePointY); // Set directly for test versus calling createCamera. camera.cameraControl = mockCameraControl; camera.cameraInfo = MockCameraInfo(); camera.currentFocusMeteringAction = null; - final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final MeteringPoint createdMeteringPoint = MeteringPoint.pigeon_detached( - pigeon_instanceManager: testInstanceManager, - ); + final createdMeteringPoint = MeteringPoint.pigeon_detached(); MeteringMode? actionBuilderMeteringMode; MeteringPoint? actionBuilderMeteringPoint; - final MockFocusMeteringActionBuilder mockActionBuilder = - MockFocusMeteringActionBuilder(); + final mockActionBuilder = MockFocusMeteringActionBuilder(); when(mockActionBuilder.build()).thenAnswer( (_) async => FocusMeteringAction.pigeon_detached( meteringPointsAe: const [], meteringPointsAf: const [], meteringPointsAwb: const [], isAutoCancelEnabled: false, - pigeon_instanceManager: testInstanceManager, ), ); - camera.proxy = getProxyForExposureAndFocus( + setUpOverridesForExposureAndFocus( newDisplayOrientedMeteringPointFactory: ({ - required CameraInfo cameraInfo, + required dynamic 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(); + final 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, - }) { + ({required MeteringMode mode, required MeteringPoint point}) { actionBuilderMeteringMode = mode; actionBuilderMeteringPoint = point; return mockActionBuilder; @@ -6186,18 +5216,18 @@ void main() { 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 camera = AndroidCameraCameraX(); + const cameraId = 2; + final mockCameraControl = MockCameraControl(); final FocusMeteringResult mockFocusMeteringResult = MockFocusMeteringResult(); - const Point exposurePoint = Point(0.1, 0.2); + const exposurePoint = Point(0.1, 0.2); // Set directly for test versus calling createCamera. camera.cameraControl = mockCameraControl; camera.cameraInfo = MockCameraInfo(); - camera.proxy = getProxyForSettingFocusandExposurePoints( + setUpOverridesForSettingFocusandExposurePoints( mockCameraControl, MockCamera2CameraControl(), ); @@ -6215,7 +5245,7 @@ void main() { VerificationResult verificationResult = verify( mockCameraControl.startFocusAndMetering(captureAny), ); - FocusMeteringAction capturedAction = + var capturedAction = verificationResult.captured.single as FocusMeteringAction; expect(capturedAction.isAutoCancelEnabled, isTrue); @@ -6237,21 +5267,16 @@ void main() { test( 'setExposureOffset throws exception if exposure compensation not supported', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 6; + final camera = AndroidCameraCameraX(); + const cameraId = 6; const double offset = 2; - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final ExposureState exposureState = ExposureState.pigeon_detached( + final mockCameraInfo = MockCameraInfo(); + final 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. @@ -6269,22 +5294,17 @@ void main() { test( 'setExposureOffset throws exception if exposure compensation could not be set for unknown reason', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 11; + final camera = AndroidCameraCameraX(); + const cameraId = 11; const double offset = 3; - final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final mockCameraInfo = MockCameraInfo(); final CameraControl mockCameraControl = MockCameraControl(); - final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final ExposureState exposureState = ExposureState.pigeon_detached( + final 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. @@ -6310,22 +5330,17 @@ void main() { 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; + final camera = AndroidCameraCameraX(); + const cameraId = 21; const double offset = 5; - final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final mockCameraInfo = MockCameraInfo(); final CameraControl mockCameraControl = MockCameraControl(); - final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final ExposureState exposureState = ExposureState.pigeon_detached( + final 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(); @@ -6351,22 +5366,17 @@ void main() { test( 'setExposureOffset behaves as expected to successful attempt to set exposure compensation index', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 11; + final camera = AndroidCameraCameraX(); + const cameraId = 11; const double offset = 3; - final MockCameraInfo mockCameraInfo = MockCameraInfo(); + final mockCameraInfo = MockCameraInfo(); final CameraControl mockCameraControl = MockCameraControl(); - final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final ExposureState exposureState = ExposureState.pigeon_detached( + final 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(); @@ -6397,41 +5407,29 @@ void main() { 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(); + final camera = AndroidCameraCameraX(); + const cameraId = 93; + final mockCameraControl = MockCameraControl(); + final mockCameraInfo = MockCameraInfo(); // Set directly for test versus calling createCamera. camera.cameraControl = mockCameraControl; camera.cameraInfo = mockCameraInfo; - final MockFocusMeteringActionBuilder mockActionBuilder = - MockFocusMeteringActionBuilder(); - final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); + final mockActionBuilder = MockFocusMeteringActionBuilder(); 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( + setUpOverridesForExposureAndFocus( withModeFocusMeteringActionBuilder: - ({ - required MeteringMode mode, - required MeteringPoint point, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - }) { + ({required MeteringMode mode, required MeteringPoint point}) { actionBuilderMeteringMode = mode; actionBuilderMeteringPoint = point; return mockActionBuilder; @@ -6444,22 +5442,12 @@ void main() { 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, - ); + final originalMeteringAction = FocusMeteringAction.pigeon_detached( + meteringPointsAe: [MeteringPoint.pigeon_detached()], + meteringPointsAf: [MeteringPoint.pigeon_detached()], + meteringPointsAwb: const [], + isAutoCancelEnabled: false, + ); camera.currentFocusMeteringAction = originalMeteringAction; await camera.setFocusPoint(cameraId, null); @@ -6476,14 +5464,9 @@ void main() { // set metering point was for auto-exposure. camera.currentFocusMeteringAction = FocusMeteringAction.pigeon_detached( meteringPointsAe: const [], - meteringPointsAf: [ - MeteringPoint.pigeon_detached( - pigeon_instanceManager: testInstanceManager, - ), - ], + meteringPointsAf: [MeteringPoint.pigeon_detached()], meteringPointsAwb: const [], isAutoCancelEnabled: false, - pigeon_instanceManager: testInstanceManager, ); await camera.setFocusPoint(cameraId, null); @@ -6495,16 +5478,16 @@ void main() { 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); + final camera = AndroidCameraCameraX(); + const cameraId = 23; + final mockCameraControl = MockCameraControl(); + const invalidFocusPoint = Point(-3, 1); // Set directly for test versus calling createCamera. camera.cameraControl = mockCameraControl; camera.cameraInfo = MockCameraInfo(); - camera.proxy = getProxyForExposureAndFocus(); + setUpOverridesForExposureAndFocus(); expect( () => camera.setFocusPoint(cameraId, invalidFocusPoint), @@ -6516,64 +5499,45 @@ void main() { test( '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(); + final camera = AndroidCameraCameraX(); + const cameraId = 9; + final mockCameraControl = MockCameraControl(); + final mockCameraInfo = MockCameraInfo(); // Set directly for test versus calling createCamera. camera.cameraControl = mockCameraControl; camera.cameraInfo = mockCameraInfo; - 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, - ); + var focusPointX = 0.8; + var focusPointY = 0.1; + var focusPoint = Point(focusPointX, focusPointY); + final createdMeteringPoint = MeteringPoint.pigeon_detached(); MeteringMode? actionBuilderMeteringMode; MeteringPoint? actionBuilderMeteringPoint; - final MockFocusMeteringActionBuilder mockActionBuilder = - MockFocusMeteringActionBuilder(); + final mockActionBuilder = MockFocusMeteringActionBuilder(); when(mockActionBuilder.build()).thenAnswer( (_) async => FocusMeteringAction.pigeon_detached( meteringPointsAe: const [], meteringPointsAf: const [], meteringPointsAwb: const [], isAutoCancelEnabled: false, - pigeon_instanceManager: testInstanceManager, ), ); - camera.proxy = getProxyForExposureAndFocus( + setUpOverridesForExposureAndFocus( newDisplayOrientedMeteringPointFactory: ({ - required CameraInfo cameraInfo, + required dynamic 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(); + final 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, - }) { + ({required MeteringMode mode, required MeteringPoint point}) { actionBuilderMeteringMode = mode; actionBuilderMeteringPoint = point; return mockActionBuilder; @@ -6581,22 +5545,12 @@ void main() { ); // 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, - ); + var originalMeteringAction = FocusMeteringAction.pigeon_detached( + meteringPointsAe: [MeteringPoint.pigeon_detached()], + meteringPointsAf: [MeteringPoint.pigeon_detached()], + meteringPointsAwb: const [], + isAutoCancelEnabled: false, + ); camera.currentFocusMeteringAction = originalMeteringAction; await camera.setFocusPoint(cameraId, focusPoint); @@ -6619,15 +5573,10 @@ void main() { focusPointY = 0.9; focusPoint = Point(focusPointX, focusPointY); originalMeteringAction = FocusMeteringAction.pigeon_detached( - meteringPointsAe: [ - MeteringPoint.pigeon_detached( - pigeon_instanceManager: testInstanceManager, - ), - ], + meteringPointsAe: [MeteringPoint.pigeon_detached()], meteringPointsAf: const [], meteringPointsAwb: const [], isAutoCancelEnabled: false, - pigeon_instanceManager: testInstanceManager, ); camera.currentFocusMeteringAction = originalMeteringAction; @@ -6650,64 +5599,45 @@ void main() { test( '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); + final camera = AndroidCameraCameraX(); + const cameraId = 19; + final mockCameraControl = MockCameraControl(); + const focusPointX = 0.8; + const focusPointY = 0.1; + const focusPoint = Point(focusPointX, focusPointY); // Set directly for test versus calling createCamera. camera.cameraControl = mockCameraControl; camera.cameraInfo = MockCameraInfo(); camera.currentFocusMeteringAction = null; - final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final MeteringPoint createdMeteringPoint = MeteringPoint.pigeon_detached( - pigeon_instanceManager: testInstanceManager, - ); + final createdMeteringPoint = MeteringPoint.pigeon_detached(); MeteringMode? actionBuilderMeteringMode; MeteringPoint? actionBuilderMeteringPoint; - final MockFocusMeteringActionBuilder mockActionBuilder = - MockFocusMeteringActionBuilder(); + final mockActionBuilder = MockFocusMeteringActionBuilder(); when(mockActionBuilder.build()).thenAnswer( (_) async => FocusMeteringAction.pigeon_detached( meteringPointsAe: const [], meteringPointsAf: const [], meteringPointsAwb: const [], isAutoCancelEnabled: false, - pigeon_instanceManager: testInstanceManager, ), ); - camera.proxy = getProxyForExposureAndFocus( + setUpOverridesForExposureAndFocus( newDisplayOrientedMeteringPointFactory: ({ - required CameraInfo cameraInfo, + required dynamic 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(); + final 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, - }) { + ({required MeteringMode mode, required MeteringPoint point}) { actionBuilderMeteringMode = mode; actionBuilderMeteringPoint = point; return mockActionBuilder; @@ -6724,18 +5654,17 @@ void main() { 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); + final camera = AndroidCameraCameraX(); + const cameraId = 2; + final mockCameraControl = MockCameraControl(); + final mockFocusMeteringResult = MockFocusMeteringResult(); + const exposurePoint = Point(0.1, 0.2); // Set directly for test versus calling createCamera. camera.cameraControl = mockCameraControl; camera.cameraInfo = MockCameraInfo(); - camera.proxy = getProxyForSettingFocusandExposurePoints( + setUpOverridesForSettingFocusandExposurePoints( mockCameraControl, MockCamera2CameraControl(), ); @@ -6754,7 +5683,7 @@ void main() { VerificationResult verificationResult = verify( mockCameraControl.startFocusAndMetering(captureAny), ); - FocusMeteringAction capturedAction = + var capturedAction = verificationResult.captured.single as FocusMeteringAction; expect(capturedAction.isAutoCancelEnabled, isTrue); @@ -6777,17 +5706,16 @@ void main() { 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(); + final camera = AndroidCameraCameraX(); + const cameraId = 4; + final mockCameraControl = MockCameraControl(); + final mockFocusMeteringResult = MockFocusMeteringResult(); // Set directly for test versus calling createCamera. camera.cameraControl = mockCameraControl; camera.cameraInfo = MockCameraInfo(); - camera.proxy = getProxyForSettingFocusandExposurePoints( + setUpOverridesForSettingFocusandExposurePoints( mockCameraControl, MockCamera2CameraControl(), ); @@ -6810,9 +5738,9 @@ void main() { 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(); + final camera = AndroidCameraCameraX(); + const cameraId = 4; + final mockCameraControl = MockCameraControl(); // Camera uses auto-focus by default, so try setting auto mode again. await camera.setFocusMode(cameraId, FocusMode.auto); @@ -6824,15 +5752,13 @@ void main() { 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; + final camera = AndroidCameraCameraX(); + const cameraId = 5; + final mockCameraControl = MockCameraControl(); + final mockFocusMeteringResult = MockFocusMeteringResult(); + final mockCamera2CameraControl = MockCamera2CameraControl(); + const exposurePointX = 0.2; + const exposurePointY = 0.7; // Set directly for test versus calling createCamera. camera.cameraInfo = MockCameraInfo(); @@ -6842,42 +5768,28 @@ void main() { mockCamera2CameraControl.addCaptureRequestOptions(any), ).thenAnswer((_) async => Future.value()); - final PigeonInstanceManager testInstanceManager = PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ); - final List createdMeteringPoints = []; - camera.proxy = getProxyForSettingFocusandExposurePoints( + final createdMeteringPoints = []; + setUpOverridesForSettingFocusandExposurePoints( mockCameraControl, mockCamera2CameraControl, newDisplayOrientedMeteringPointFactory: ({ - required CameraInfo cameraInfo, + required dynamic 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(); + final mockFactory = MockDisplayOrientedMeteringPointFactory(); when( mockFactory.createPoint(exposurePointX, exposurePointY), ).thenAnswer((_) async { - final MeteringPoint createdMeteringPoint = - MeteringPoint.pigeon_detached( - pigeon_instanceManager: testInstanceManager, - ); + final createdMeteringPoint = MeteringPoint.pigeon_detached(); createdMeteringPoints.add(createdMeteringPoint); return createdMeteringPoint; }); when(mockFactory.createPointWithSize(0.5, 0.5, 1)).thenAnswer(( _, ) async { - final MeteringPoint createdMeteringPoint = - MeteringPoint.pigeon_detached( - pigeon_instanceManager: testInstanceManager, - ); + final createdMeteringPoint = MeteringPoint.pigeon_detached(); createdMeteringPoints.add(createdMeteringPoint); return createdMeteringPoint; }); @@ -6908,7 +5820,7 @@ void main() { final VerificationResult verificationResult = verify( mockCameraControl.startFocusAndMetering(captureAny), ); - final FocusMeteringAction capturedAction = + final capturedAction = verificationResult.captured.single as FocusMeteringAction; expect(capturedAction.isAutoCancelEnabled, isTrue); @@ -6922,13 +5834,12 @@ void main() { 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 camera = AndroidCameraCameraX(); + const cameraId = 5; + final mockCameraControl = MockCameraControl(); final FocusMeteringResult mockFocusMeteringResult = MockFocusMeteringResult(); - final MockCamera2CameraControl mockCamera2CameraControl = - MockCamera2CameraControl(); + final mockCamera2CameraControl = MockCamera2CameraControl(); // Set directly for test versus calling createCamera. camera.cameraInfo = MockCameraInfo(); @@ -6938,7 +5849,7 @@ void main() { mockCamera2CameraControl.addCaptureRequestOptions(any), ).thenAnswer((_) async => Future.value()); - camera.proxy = getProxyForSettingFocusandExposurePoints( + setUpOverridesForSettingFocusandExposurePoints( mockCameraControl, mockCamera2CameraControl, ); @@ -6962,15 +5873,14 @@ void main() { 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 camera = AndroidCameraCameraX(); + const cameraId = 6; + final mockCameraControl = MockCameraControl(); final FocusMeteringResult mockFocusMeteringResult = MockFocusMeteringResult(); - final MockCamera2CameraControl mockCamera2CameraControl = - MockCamera2CameraControl(); - const double focusPointX = 0.1; - const double focusPointY = 0.2; + final mockCamera2CameraControl = MockCamera2CameraControl(); + const focusPointX = 0.1; + const focusPointY = 0.2; // Set directly for test versus calling createCamera. camera.cameraInfo = MockCameraInfo(); @@ -6980,7 +5890,7 @@ void main() { mockCamera2CameraControl.addCaptureRequestOptions(any), ).thenAnswer((_) async => Future.value()); - camera.proxy = getProxyForSettingFocusandExposurePoints( + setUpOverridesForSettingFocusandExposurePoints( mockCameraControl, mockCamera2CameraControl, ); @@ -7006,13 +5916,13 @@ void main() { final VerificationResult verificationResult = verify( mockCameraControl.startFocusAndMetering(captureAny), ); - final FocusMeteringAction capturedAction = + final 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 = + final focusPoint = capturedAction.meteringPointsAf.single as TestMeteringPoint; expect(focusPoint.x, equals(focusPointX)); expect(focusPoint.y, equals(focusPointY)); @@ -7023,13 +5933,12 @@ void main() { 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; + final camera = AndroidCameraCameraX(); + const cameraId = 7; + final mockCameraControl = MockCameraControl(); + final mockCamera2CameraControl = MockCamera2CameraControl(); + const focusPointX = 0.88; + const focusPointY = 0.33; // Set directly for test versus calling createCamera. camera.cameraInfo = MockCameraInfo(); @@ -7039,7 +5948,7 @@ void main() { mockCamera2CameraControl.addCaptureRequestOptions(any), ).thenAnswer((_) async => Future.value()); - camera.proxy = getProxyForSettingFocusandExposurePoints( + setUpOverridesForSettingFocusandExposurePoints( mockCameraControl, mockCamera2CameraControl, ); @@ -7057,7 +5966,7 @@ void main() { final VerificationResult verificationResult = verify( mockCameraControl.startFocusAndMetering(captureAny), ); - final FocusMeteringAction capturedAction = + final capturedAction = verificationResult.captured.single as FocusMeteringAction; expect(capturedAction.isAutoCancelEnabled, isFalse); @@ -7066,7 +5975,7 @@ void main() { expect(capturedAction.meteringPointsAf.length, equals(1)); expect(capturedAction.meteringPointsAwb.length, equals(0)); - final TestMeteringPoint focusPoint = + final focusPoint = capturedAction.meteringPointsAf.single as TestMeteringPoint; expect(focusPoint.x, equals(focusPointX)); expect(focusPoint.y, equals(focusPointY)); @@ -7077,15 +5986,14 @@ void main() { 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; + final camera = AndroidCameraCameraX(); + const cameraId = 8; + final mockCameraControl = MockCameraControl(); + final mockCamera2CameraControl = MockCamera2CameraControl(); + const focusPointX = 0.38; + const focusPointY = 0.38; + const exposurePointX = 0.54; + const exposurePointY = 0.45; // Set directly for test versus calling createCamera. camera.cameraInfo = MockCameraInfo(); @@ -7095,7 +6003,7 @@ void main() { mockCamera2CameraControl.addCaptureRequestOptions(any), ).thenAnswer((_) async => Future.value()); - camera.proxy = getProxyForSettingFocusandExposurePoints( + setUpOverridesForSettingFocusandExposurePoints( mockCameraControl, mockCamera2CameraControl, ); @@ -7117,7 +6025,7 @@ void main() { final VerificationResult verificationResult = verify( mockCameraControl.startFocusAndMetering(captureAny), ); - final FocusMeteringAction capturedAction = + final capturedAction = verificationResult.captured.single as FocusMeteringAction; expect(capturedAction.isAutoCancelEnabled, isFalse); @@ -7127,13 +6035,13 @@ void main() { expect(capturedAction.meteringPointsAf.length, equals(1)); expect(capturedAction.meteringPointsAwb.length, equals(0)); - final TestMeteringPoint focusPoint = + final focusPoint = capturedAction.meteringPointsAf.single as TestMeteringPoint; expect(focusPoint.x, equals(focusPointX)); expect(focusPoint.y, equals(focusPointY)); expect(focusPoint.size, isNull); - final TestMeteringPoint exposurePoint = + final exposurePoint = capturedAction.meteringPointsAe.single as TestMeteringPoint; expect(exposurePoint.x, equals(exposurePointX)); expect(exposurePoint.y, equals(exposurePointY)); @@ -7144,15 +6052,14 @@ void main() { 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; + final camera = AndroidCameraCameraX(); + const cameraId = 9; + final mockCameraControl = MockCameraControl(); + final mockCamera2CameraControl = MockCamera2CameraControl(); + const exposurePointX = 0.8; + const exposurePointY = 0.3; + const defaultFocusPointX = 0.5; + const defaultFocusPointY = 0.5; const double defaultFocusPointSize = 1; // Set directly for test versus calling createCamera. @@ -7163,7 +6070,7 @@ void main() { mockCamera2CameraControl.addCaptureRequestOptions(any), ).thenAnswer((_) async => Future.value()); - camera.proxy = getProxyForSettingFocusandExposurePoints( + setUpOverridesForSettingFocusandExposurePoints( mockCameraControl, mockCamera2CameraControl, ); @@ -7182,7 +6089,7 @@ void main() { final VerificationResult verificationResult = verify( mockCameraControl.startFocusAndMetering(captureAny), ); - final FocusMeteringAction capturedAction = + final capturedAction = verificationResult.captured.single as FocusMeteringAction; expect(capturedAction.isAutoCancelEnabled, isFalse); @@ -7192,13 +6099,13 @@ void main() { expect(capturedAction.meteringPointsAf.length, equals(1)); expect(capturedAction.meteringPointsAwb.length, equals(0)); - final TestMeteringPoint focusPoint = + final focusPoint = capturedAction.meteringPointsAf.single as TestMeteringPoint; expect(focusPoint.x, equals(defaultFocusPointX)); expect(focusPoint.y, equals(defaultFocusPointY)); expect(focusPoint.size, equals(defaultFocusPointSize)); - final TestMeteringPoint exposurePoint = + final exposurePoint = capturedAction.meteringPointsAe.single as TestMeteringPoint; expect(exposurePoint.x, equals(exposurePointX)); expect(exposurePoint.y, equals(exposurePointY)); @@ -7209,13 +6116,12 @@ void main() { 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; + final camera = AndroidCameraCameraX(); + const cameraId = 10; + final mockCameraControl = MockCameraControl(); + final mockCamera2CameraControl = MockCamera2CameraControl(); + const defaultFocusPointX = 0.5; + const defaultFocusPointY = 0.5; const double defaultFocusPointSize = 1; // Set directly for test versus calling createCamera. @@ -7226,7 +6132,7 @@ void main() { mockCamera2CameraControl.addCaptureRequestOptions(any), ).thenAnswer((_) async => Future.value()); - camera.proxy = getProxyForSettingFocusandExposurePoints( + setUpOverridesForSettingFocusandExposurePoints( mockCameraControl, mockCamera2CameraControl, ); @@ -7237,7 +6143,7 @@ void main() { final VerificationResult verificationResult = verify( mockCameraControl.startFocusAndMetering(captureAny), ); - final FocusMeteringAction capturedAction = + final capturedAction = verificationResult.captured.single as FocusMeteringAction; expect(capturedAction.isAutoCancelEnabled, isFalse); @@ -7246,7 +6152,7 @@ void main() { expect(capturedAction.meteringPointsAf.length, equals(1)); expect(capturedAction.meteringPointsAwb.length, equals(0)); - final TestMeteringPoint focusPoint = + final focusPoint = capturedAction.meteringPointsAf.single as TestMeteringPoint; expect(focusPoint.x, equals(defaultFocusPointX)); expect(focusPoint.y, equals(defaultFocusPointY)); @@ -7257,13 +6163,12 @@ void main() { 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 camera = AndroidCameraCameraX(); + const cameraId = 11; + final mockCameraControl = MockCameraControl(); final FocusMeteringResult mockFocusMeteringResult = MockFocusMeteringResult(); - final MockCamera2CameraControl mockCamera2CameraControl = - MockCamera2CameraControl(); + final mockCamera2CameraControl = MockCamera2CameraControl(); // Set directly for test versus calling createCamera. camera.cameraInfo = MockCameraInfo(); @@ -7273,7 +6178,7 @@ void main() { mockCamera2CameraControl.addCaptureRequestOptions(any), ).thenAnswer((_) async => Future.value()); - camera.proxy = getProxyForSettingFocusandExposurePoints( + setUpOverridesForSettingFocusandExposurePoints( mockCameraControl, mockCamera2CameraControl, ); @@ -7294,11 +6199,11 @@ void main() { final VerificationResult verificationResult = verify( mockCamera2CameraControl.addCaptureRequestOptions(captureAny), ); - final CaptureRequestOptions capturedCaptureRequestOptions = + final capturedCaptureRequestOptions = verificationResult.captured.single as CaptureRequestOptions; expect( await capturedCaptureRequestOptions.getCaptureRequestOption( - camera.proxy.controlAELockCaptureRequest(), + CaptureRequest.controlAELock, ), isFalse, ); @@ -7308,18 +6213,17 @@ void main() { 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); + final camera = AndroidCameraCameraX(); + const cameraId = 22; + final mockCameraControl = MockCameraControl(); + final mockFocusMeteringResult = MockFocusMeteringResult(); + const focusPoint = Point(0.21, 0.21); // Set directly for test versus calling createCamera. camera.cameraControl = mockCameraControl; camera.cameraInfo = MockCameraInfo(); - camera.proxy = getProxyForSettingFocusandExposurePoints( + setUpOverridesForSettingFocusandExposurePoints( mockCameraControl, MockCamera2CameraControl(), ); @@ -7354,7 +6258,7 @@ void main() { final VerificationResult verificationResult = verify( mockCameraControl.startFocusAndMetering(captureAny), ); - final FocusMeteringAction capturedAction = + final capturedAction = verificationResult.captured.single as FocusMeteringAction; expect(capturedAction.isAutoCancelEnabled, isFalse); }, @@ -7363,18 +6267,17 @@ void main() { 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); + final camera = AndroidCameraCameraX(); + const cameraId = 342; + final mockCameraControl = MockCameraControl(); + final mockFocusMeteringResult = MockFocusMeteringResult(); + const exposurePoint = Point(0.23, 0.32); // Set directly for test versus calling createCamera. camera.cameraControl = mockCameraControl; camera.cameraInfo = MockCameraInfo(); - camera.proxy = getProxyForSettingFocusandExposurePoints( + setUpOverridesForSettingFocusandExposurePoints( mockCameraControl, MockCamera2CameraControl(), ); @@ -7408,7 +6311,7 @@ void main() { final VerificationResult verificationResult = verify( mockCameraControl.startFocusAndMetering(captureAny), ); - final FocusMeteringAction capturedAction = + final capturedAction = verificationResult.captured.single as FocusMeteringAction; expect(capturedAction.isAutoCancelEnabled, isFalse); }, @@ -7417,18 +6320,17 @@ void main() { 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); + final camera = AndroidCameraCameraX(); + const cameraId = 232; + final mockCameraControl = MockCameraControl(); + final mockFocusMeteringResult = MockFocusMeteringResult(); + const focusPoint = Point(0.221, 0.211); // Set directly for test versus calling createCamera. camera.cameraControl = mockCameraControl; camera.cameraInfo = MockCameraInfo(); - camera.proxy = getProxyForSettingFocusandExposurePoints( + setUpOverridesForSettingFocusandExposurePoints( mockCameraControl, MockCamera2CameraControl(), ); @@ -7451,7 +6353,7 @@ void main() { final VerificationResult verificationResult = verify( mockCameraControl.startFocusAndMetering(captureAny), ); - final FocusMeteringAction capturedAction = + final capturedAction = verificationResult.captured.single as FocusMeteringAction; expect(capturedAction.isAutoCancelEnabled, isTrue); }, @@ -7460,18 +6362,17 @@ void main() { 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); + final camera = AndroidCameraCameraX(); + const cameraId = 323; + final mockCameraControl = MockCameraControl(); + final mockFocusMeteringResult = MockFocusMeteringResult(); + const exposurePoint = Point(0.223, 0.332); // Set directly for test versus calling createCamera. camera.cameraControl = mockCameraControl; camera.cameraInfo = MockCameraInfo(); - camera.proxy = getProxyForSettingFocusandExposurePoints( + setUpOverridesForSettingFocusandExposurePoints( mockCameraControl, MockCamera2CameraControl(), ); @@ -7494,7 +6395,7 @@ void main() { final VerificationResult verificationResult = verify( mockCameraControl.startFocusAndMetering(captureAny), ); - final FocusMeteringAction capturedAction = + final capturedAction = verificationResult.captured.single as FocusMeteringAction; expect(capturedAction.isAutoCancelEnabled, isTrue); }, @@ -7503,13 +6404,12 @@ void main() { 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(); + final camera = AndroidCameraCameraX(); + const cameraId = 22; + final mockImageAnalysis = MockImageAnalysis(); + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockCamera = MockCamera(); + final mockCameraInfo = MockCameraInfo(); // Set directly for test versus calling createCamera. camera.imageAnalysis = mockImageAnalysis; @@ -7520,31 +6420,13 @@ void main() { 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: (_) {}, - ), - ); - }, - ); + PigeonOverrides.analyzer_new = + ({required void Function(Analyzer, ImageProxy) analyze}) => + MockAnalyzer(); + GenericsPigeonOverrides.observerNew = + ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; when( mockProcessCameraProvider.isBound(mockImageAnalysis), @@ -7576,16 +6458,15 @@ void main() { ); 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', + 'startVideoCapturing unbinds ImageAnalysis use case when image streaming callback not specified', () 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 camera = AndroidCameraCameraX(); + final mockPendingRecording = MockPendingRecording(); + final mockRecording = MockRecording(); + final mockCamera = MockCamera(); + final mockCameraInfo = MockCameraInfo(); + final mockCamera2CameraInfo = MockCamera2CameraInfo(); // Set directly for test versus calling createCamera. camera.processCameraProvider = MockProcessCameraProvider(); @@ -7594,530 +6475,43 @@ void main() { camera.cameraSelector = MockCameraSelector(); camera.cameraInfo = MockCameraInfo(); camera.imageAnalysis = MockImageAnalysis(); - camera.enableRecordingAudio = false; + camera.enableRecordingAudio = true; // 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.mp4'; - 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, - '.mp4', - ), - ).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.withAudioEnabled(!camera.enableRecordingAudio), - ).thenAnswer((_) async => mockPendingRecording); - when( - mockPendingRecording.asPersistentRecording(), - ).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(); - camera.enableRecordingAudio = true; - - // 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.mp4'; - 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, - '.mp4', - ), - ).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.withAudioEnabled(!camera.enableRecordingAudio), - ).thenAnswer((_) async => mockPendingRecording); - when( - mockPendingRecording.asPersistentRecording(), - ).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(); - camera.enableRecordingAudio = false; - - // 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.mp4'; - 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, - '.mp4', - ), - ).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.withAudioEnabled(!camera.enableRecordingAudio), - ).thenAnswer((_) async => mockPendingRecording); - when( - mockPendingRecording.asPersistentRecording(), - ).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(); - camera.enableRecordingAudio = true; - - // 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.mp4'; - 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, - '.mp4', - ), - ).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 outputPath = '/temp/REC123.mp4'; + GenericsPigeonOverrides.observerNew = + ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; + PigeonOverrides.camera2CameraInfo_from = + ({required dynamic cameraInfo}) => mockCamera2CameraInfo; + PigeonOverrides.systemServicesManager_new = + ({ + required void Function(SystemServicesManager, String) onCameraError, + }) { + final mockSystemServicesManager = MockSystemServicesManager(); + when( + mockSystemServicesManager.getTempFilePath( + camera.videoPrefix, + '.mp4', + ), + ).thenAnswer((_) async => outputPath); + return mockSystemServicesManager; + }; + PigeonOverrides.videoRecordEventListener_new = + ({ + required void Function(VideoRecordEventListener, VideoRecordEvent) + onEvent, + }) { + return VideoRecordEventListener.pigeon_detached(onEvent: onEvent); + }; + PigeonOverrides.cameraCharacteristics_infoSupportedHardwareLevel = + MockCameraCharacteristicsKey(); - const int cameraId = 107; + const cameraId = 77; // Mock method calls. when( @@ -8135,9 +6529,6 @@ void main() { 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); @@ -8159,346 +6550,11 @@ void main() { // 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(); - camera.enableRecordingAudio = false; - - // 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.mp4'; - 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, - '.mp4', - ), - ).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.withAudioEnabled(!camera.enableRecordingAudio), - ).thenAnswer((_) async => mockPendingRecording); - when( - mockPendingRecording.asPersistentRecording(), - ).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(); - camera.enableRecordingAudio = true; - - // 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.mp4'; - 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, - '.mp4', - ), - ).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.withAudioEnabled(!camera.enableRecordingAudio), - ).thenAnswer((_) async => mockPendingRecording); - when( - mockPendingRecording.asPersistentRecording(), - ).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: (_) {}, - ), - ), + VideoRecordEventStart.pigeon_detached(), ); await camera.startVideoCapturing(const VideoCaptureOptions(cameraId)); - verify( - camera.processCameraProvider!.unbind([camera.imageCapture!]), - ); verify( camera.processCameraProvider!.unbind([camera.imageAnalysis!]), ); @@ -8508,7 +6564,7 @@ void main() { test( 'prepareForVideoRecording does not make any calls involving starting video recording', () async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); + final camera = AndroidCameraCameraX(); // Set directly for test versus calling createCamera. camera.processCameraProvider = MockProcessCameraProvider(); @@ -8527,11 +6583,7 @@ void main() { class TestMeteringPoint extends MeteringPoint { TestMeteringPoint.detached({required this.x, required this.y, this.size}) - : super.pigeon_detached( - pigeon_instanceManager: PigeonInstanceManager( - onWeakReferenceRemoved: (_) {}, - ), - ); + : super.pigeon_detached(); final double x; final double y; 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 1af9e9207f74..aa997efe8d05 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 @@ -4,14 +4,12 @@ // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i5; -import 'dart:typed_data' as _i9; +import 'dart:typed_data' as _i7; 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 _i4; -import 'package:flutter/services.dart' as _i8; import 'package:mockito/mockito.dart' as _i1; import 'package:mockito/src/dummies.dart' as _i6; @@ -28,6 +26,7 @@ import 'package:mockito/src/dummies.dart' as _i6; // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member class _FakePigeonInstanceManager_0 extends _i1.SmartFake implements _i2.PigeonInstanceManager { @@ -111,167 +110,155 @@ class _FakeCameraSelector_14 extends _i1.SmartFake : super(parent, parentInvocation); } -class _FakeCameraIntegerRange_15 extends _i1.SmartFake - implements _i2.CameraIntegerRange { - _FakeCameraIntegerRange_15(Object parent, Invocation parentInvocation) +class _FakeCaptureRequestOptions_15 extends _i1.SmartFake + implements _i2.CaptureRequestOptions { + _FakeCaptureRequestOptions_15(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeObserver_16 extends _i1.SmartFake implements _i3.Observer { - _FakeObserver_16(Object parent, Invocation parentInvocation) +class _FakeDeviceOrientationManager_16 extends _i1.SmartFake + implements _i2.DeviceOrientationManager { + _FakeDeviceOrientationManager_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 _FakeDisplayOrientedMeteringPointFactory_17 extends _i1.SmartFake + implements _i2.DisplayOrientedMeteringPointFactory { + _FakeDisplayOrientedMeteringPointFactory_17( + Object parent, + Invocation parentInvocation, + ) : super(parent, parentInvocation); } -class _FakeDeviceOrientationManager_18 extends _i1.SmartFake - implements _i2.DeviceOrientationManager { - _FakeDeviceOrientationManager_18(Object parent, Invocation parentInvocation) +class _FakeMeteringPoint_18 extends _i1.SmartFake implements _i2.MeteringPoint { + _FakeMeteringPoint_18(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakePreview_19 extends _i1.SmartFake implements _i2.Preview { - _FakePreview_19(Object parent, Invocation parentInvocation) +class _FakeCameraIntegerRange_19 extends _i1.SmartFake + implements _i2.CameraIntegerRange { + _FakeCameraIntegerRange_19(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeVideoCapture_20 extends _i1.SmartFake implements _i2.VideoCapture { - _FakeVideoCapture_20(Object parent, Invocation parentInvocation) +class _FakeFallbackStrategy_20 extends _i1.SmartFake + implements _i2.FallbackStrategy { + _FakeFallbackStrategy_20(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeRecorder_21 extends _i1.SmartFake implements _i2.Recorder { - _FakeRecorder_21(Object parent, Invocation parentInvocation) +class _FakeFocusMeteringAction_21 extends _i1.SmartFake + implements _i2.FocusMeteringAction { + _FakeFocusMeteringAction_21(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeVideoRecordEventListener_22 extends _i1.SmartFake - implements _i2.VideoRecordEventListener { - _FakeVideoRecordEventListener_22(Object parent, Invocation parentInvocation) +class _FakeFocusMeteringActionBuilder_22 extends _i1.SmartFake + implements _i2.FocusMeteringActionBuilder { + _FakeFocusMeteringActionBuilder_22(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeImageCapture_23 extends _i1.SmartFake implements _i2.ImageCapture { - _FakeImageCapture_23(Object parent, Invocation parentInvocation) +class _FakeFocusMeteringResult_23 extends _i1.SmartFake + implements _i2.FocusMeteringResult { + _FakeFocusMeteringResult_23(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeResolutionStrategy_24 extends _i1.SmartFake - implements _i2.ResolutionStrategy { - _FakeResolutionStrategy_24(Object parent, Invocation parentInvocation) +class _FakeImageAnalysis_24 extends _i1.SmartFake implements _i2.ImageAnalysis { + _FakeImageAnalysis_24(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeResolutionSelector_25 extends _i1.SmartFake - implements _i2.ResolutionSelector { - _FakeResolutionSelector_25(Object parent, Invocation parentInvocation) +class _FakeImageCapture_25 extends _i1.SmartFake implements _i2.ImageCapture { + _FakeImageCapture_25(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeImageAnalysis_26 extends _i1.SmartFake implements _i2.ImageAnalysis { - _FakeImageAnalysis_26(Object parent, Invocation parentInvocation) +class _FakeImageProxy_26 extends _i1.SmartFake implements _i2.ImageProxy { + _FakeImageProxy_26(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeQualitySelector_27 extends _i1.SmartFake - implements _i2.QualitySelector { - _FakeQualitySelector_27(Object parent, Invocation parentInvocation) +class _FakeObserver_27 extends _i1.SmartFake implements _i3.Observer { + _FakeObserver_27(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeFallbackStrategy_28 extends _i1.SmartFake - implements _i2.FallbackStrategy { - _FakeFallbackStrategy_28(Object parent, Invocation parentInvocation) +class _FakePendingRecording_28 extends _i1.SmartFake + implements _i2.PendingRecording { + _FakePendingRecording_28(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeFocusMeteringActionBuilder_29 extends _i1.SmartFake - implements _i2.FocusMeteringActionBuilder { - _FakeFocusMeteringActionBuilder_29(Object parent, Invocation parentInvocation) +class _FakeRecording_29 extends _i1.SmartFake implements _i2.Recording { + _FakeRecording_29(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeCaptureRequestOptions_30 extends _i1.SmartFake - implements _i2.CaptureRequestOptions { - _FakeCaptureRequestOptions_30(Object parent, Invocation parentInvocation) +class _FakePlaneProxy_30 extends _i1.SmartFake implements _i2.PlaneProxy { + _FakePlaneProxy_30(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeResolutionFilter_31 extends _i1.SmartFake - implements _i2.ResolutionFilter { - _FakeResolutionFilter_31(Object parent, Invocation parentInvocation) +class _FakePreview_31 extends _i1.SmartFake implements _i2.Preview { + _FakePreview_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); -} - -class _FakeProcessCameraProvider_33 extends _i1.SmartFake +class _FakeProcessCameraProvider_32 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) + _FakeProcessCameraProvider_32(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeMeteringPoint_35 extends _i1.SmartFake implements _i2.MeteringPoint { - _FakeMeteringPoint_35(Object parent, Invocation parentInvocation) +class _FakeQualitySelector_33 extends _i1.SmartFake + implements _i2.QualitySelector { + _FakeQualitySelector_33(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeFocusMeteringAction_36 extends _i1.SmartFake - implements _i2.FocusMeteringAction { - _FakeFocusMeteringAction_36(Object parent, Invocation parentInvocation) +class _FakeRecorder_34 extends _i1.SmartFake implements _i2.Recorder { + _FakeRecorder_34(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeFocusMeteringResult_37 extends _i1.SmartFake - implements _i2.FocusMeteringResult { - _FakeFocusMeteringResult_37(Object parent, Invocation parentInvocation) +class _FakeResolutionFilter_35 extends _i1.SmartFake + implements _i2.ResolutionFilter { + _FakeResolutionFilter_35(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeImageProxy_38 extends _i1.SmartFake implements _i2.ImageProxy { - _FakeImageProxy_38(Object parent, Invocation parentInvocation) +class _FakeResolutionSelector_36 extends _i1.SmartFake + implements _i2.ResolutionSelector { + _FakeResolutionSelector_36(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakePendingRecording_39 extends _i1.SmartFake - implements _i2.PendingRecording { - _FakePendingRecording_39(Object parent, Invocation parentInvocation) +class _FakeResolutionStrategy_37 extends _i1.SmartFake + implements _i2.ResolutionStrategy { + _FakeResolutionStrategy_37(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeRecording_40 extends _i1.SmartFake implements _i2.Recording { - _FakeRecording_40(Object parent, Invocation parentInvocation) +class _FakeSystemServicesManager_38 extends _i1.SmartFake + implements _i2.SystemServicesManager { + _FakeSystemServicesManager_38(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakePlaneProxy_41 extends _i1.SmartFake implements _i2.PlaneProxy { - _FakePlaneProxy_41(Object parent, Invocation parentInvocation) +class _FakeVideoOutput_39 extends _i1.SmartFake implements _i2.VideoOutput { + _FakeVideoOutput_39(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeVideoOutput_42 extends _i1.SmartFake implements _i2.VideoOutput { - _FakeVideoOutput_42(Object parent, Invocation parentInvocation) +class _FakeVideoCapture_40 extends _i1.SmartFake implements _i2.VideoCapture { + _FakeVideoCapture_40(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } -class _FakeZoomState_43 extends _i1.SmartFake implements _i2.ZoomState { - _FakeZoomState_43(Object parent, Invocation parentInvocation) +class _FakeZoomState_41 extends _i1.SmartFake implements _i2.ZoomState { + _FakeZoomState_41(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); } @@ -460,6 +447,15 @@ class MockCameraInfo extends _i1.Mock implements _i3.CameraInfo { ) as int); + @override + _i2.LensFacing get lensFacing => + (super.noSuchMethod( + Invocation.getter(#lensFacing), + returnValue: _i2.LensFacing.front, + returnValueForMissingStub: _i2.LensFacing.front, + ) + as _i2.LensFacing); + @override _i2.ExposureState get exposureState => (super.noSuchMethod( @@ -920,1374 +916,6 @@ class MockCameraSelector extends _i1.Mock implements _i2.CameraSelector { 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({ - _i3.CameraInfo? cameraInfoForFilter, - _i8.BinaryMessenger? pigeon_binaryMessenger, - _i2.PigeonInstanceManager? pigeon_instanceManager, - _i2.LensFacing? requireLensFacing, - }) - get newCameraSelector => - (super.noSuchMethod( - Invocation.getter(#newCameraSelector), - returnValue: - ({ - _i3.CameraInfo? cameraInfoForFilter, - _i8.BinaryMessenger? pigeon_binaryMessenger, - _i2.PigeonInstanceManager? pigeon_instanceManager, - _i2.LensFacing? requireLensFacing, - }) => _FakeCameraSelector_14( - this, - Invocation.getter(#newCameraSelector), - ), - returnValueForMissingStub: - ({ - _i3.CameraInfo? cameraInfoForFilter, - _i8.BinaryMessenger? pigeon_binaryMessenger, - _i2.PigeonInstanceManager? pigeon_instanceManager, - _i2.LensFacing? requireLensFacing, - }) => _FakeCameraSelector_14( - this, - Invocation.getter(#newCameraSelector), - ), - ) - as _i2.CameraSelector Function({ - _i3.CameraInfo? cameraInfoForFilter, - _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({ - int? outputImageFormat, - _i8.BinaryMessenger? pigeon_binaryMessenger, - _i2.PigeonInstanceManager? pigeon_instanceManager, - _i2.ResolutionSelector? resolutionSelector, - int? targetRotation, - }) - get newImageAnalysis => - (super.noSuchMethod( - Invocation.getter(#newImageAnalysis), - returnValue: - ({ - int? outputImageFormat, - _i8.BinaryMessenger? pigeon_binaryMessenger, - _i2.PigeonInstanceManager? pigeon_instanceManager, - _i2.ResolutionSelector? resolutionSelector, - int? targetRotation, - }) => _FakeImageAnalysis_26( - this, - Invocation.getter(#newImageAnalysis), - ), - returnValueForMissingStub: - ({ - int? outputImageFormat, - _i8.BinaryMessenger? pigeon_binaryMessenger, - _i2.PigeonInstanceManager? pigeon_instanceManager, - _i2.ResolutionSelector? resolutionSelector, - int? targetRotation, - }) => _FakeImageAnalysis_26( - this, - Invocation.getter(#newImageAnalysis), - ), - ) - as _i2.ImageAnalysis Function({ - int? outputImageFormat, - _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 - _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 - _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 - _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 - _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(#defaultBackCameraCameraSelector), - ), - returnValueForMissingStub: () => _FakeCameraSelector_14( - this, - Invocation.getter(#defaultBackCameraCameraSelector), - ), - ) - as _i2.CameraSelector Function()); - - @override - _i2.CameraSelector Function() get defaultFrontCameraCameraSelector => - (super.noSuchMethod( - Invocation.getter(#defaultFrontCameraCameraSelector), - returnValue: () => _FakeCameraSelector_14( - this, - Invocation.getter(#defaultFrontCameraCameraSelector), - ), - returnValueForMissingStub: () => _FakeCameraSelector_14( - this, - 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: () => _FakeCaptureRequestKey_34( - this, - Invocation.getter(#controlAELockCaptureRequest), - ), - ) - as _i2.CaptureRequestKey Function()); - - @override - _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()); - - @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 - 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 - 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 - 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 - set controlAELockCaptureRequest( - _i2.CaptureRequestKey Function()? _controlAELockCaptureRequest, - ) => super.noSuchMethod( - Invocation.setter( - #controlAELockCaptureRequest, - _controlAELockCaptureRequest, - ), - returnValueForMissingStub: null, - ); -} - /// A class which mocks [CaptureRequestOptions]. /// /// See the documentation for Mockito's code generation for more information. @@ -2321,11 +949,11 @@ class MockCaptureRequestOptions extends _i1.Mock _i2.CaptureRequestOptions pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakeCaptureRequestOptions_30( + returnValue: _FakeCaptureRequestOptions_15( this, Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakeCaptureRequestOptions_30( + returnValueForMissingStub: _FakeCaptureRequestOptions_15( this, Invocation.method(#pigeon_copy, []), ), @@ -2421,11 +1049,11 @@ class MockDeviceOrientationManager extends _i1.Mock _i2.DeviceOrientationManager pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakeDeviceOrientationManager_18( + returnValue: _FakeDeviceOrientationManager_16( this, Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakeDeviceOrientationManager_18( + returnValueForMissingStub: _FakeDeviceOrientationManager_16( this, Invocation.method(#pigeon_copy, []), ), @@ -2457,12 +1085,12 @@ class MockDisplayOrientedMeteringPointFactory extends _i1.Mock _i2.DisplayOrientedMeteringPointFactory pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakeDisplayOrientedMeteringPointFactory_32( + returnValue: _FakeDisplayOrientedMeteringPointFactory_17( this, Invocation.method(#pigeon_copy, []), ), returnValueForMissingStub: - _FakeDisplayOrientedMeteringPointFactory_32( + _FakeDisplayOrientedMeteringPointFactory_17( this, Invocation.method(#pigeon_copy, []), ), @@ -2474,13 +1102,13 @@ class MockDisplayOrientedMeteringPointFactory extends _i1.Mock (super.noSuchMethod( Invocation.method(#createPoint, [x, y]), returnValue: _i5.Future<_i2.MeteringPoint>.value( - _FakeMeteringPoint_35( + _FakeMeteringPoint_18( this, Invocation.method(#createPoint, [x, y]), ), ), returnValueForMissingStub: _i5.Future<_i2.MeteringPoint>.value( - _FakeMeteringPoint_35( + _FakeMeteringPoint_18( this, Invocation.method(#createPoint, [x, y]), ), @@ -2497,13 +1125,13 @@ class MockDisplayOrientedMeteringPointFactory extends _i1.Mock (super.noSuchMethod( Invocation.method(#createPointWithSize, [x, y, size]), returnValue: _i5.Future<_i2.MeteringPoint>.value( - _FakeMeteringPoint_35( + _FakeMeteringPoint_18( this, Invocation.method(#createPointWithSize, [x, y, size]), ), ), returnValueForMissingStub: _i5.Future<_i2.MeteringPoint>.value( - _FakeMeteringPoint_35( + _FakeMeteringPoint_18( this, Invocation.method(#createPointWithSize, [x, y, size]), ), @@ -2520,11 +1148,11 @@ class MockExposureState extends _i1.Mock implements _i2.ExposureState { _i2.CameraIntegerRange get exposureCompensationRange => (super.noSuchMethod( Invocation.getter(#exposureCompensationRange), - returnValue: _FakeCameraIntegerRange_15( + returnValue: _FakeCameraIntegerRange_19( this, Invocation.getter(#exposureCompensationRange), ), - returnValueForMissingStub: _FakeCameraIntegerRange_15( + returnValueForMissingStub: _FakeCameraIntegerRange_19( this, Invocation.getter(#exposureCompensationRange), ), @@ -2594,11 +1222,11 @@ class MockFallbackStrategy extends _i1.Mock implements _i2.FallbackStrategy { _i2.FallbackStrategy pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakeFallbackStrategy_28( + returnValue: _FakeFallbackStrategy_20( this, Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakeFallbackStrategy_28( + returnValueForMissingStub: _FakeFallbackStrategy_20( this, Invocation.method(#pigeon_copy, []), ), @@ -2661,11 +1289,11 @@ class MockFocusMeteringActionBuilder extends _i1.Mock (super.noSuchMethod( Invocation.method(#build, []), returnValue: _i5.Future<_i2.FocusMeteringAction>.value( - _FakeFocusMeteringAction_36(this, Invocation.method(#build, [])), + _FakeFocusMeteringAction_21(this, Invocation.method(#build, [])), ), returnValueForMissingStub: _i5.Future<_i2.FocusMeteringAction>.value( - _FakeFocusMeteringAction_36( + _FakeFocusMeteringAction_21( this, Invocation.method(#build, []), ), @@ -2677,11 +1305,11 @@ class MockFocusMeteringActionBuilder extends _i1.Mock _i2.FocusMeteringActionBuilder pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakeFocusMeteringActionBuilder_29( + returnValue: _FakeFocusMeteringActionBuilder_22( this, Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakeFocusMeteringActionBuilder_29( + returnValueForMissingStub: _FakeFocusMeteringActionBuilder_22( this, Invocation.method(#pigeon_copy, []), ), @@ -2722,11 +1350,11 @@ class MockFocusMeteringResult extends _i1.Mock _i2.FocusMeteringResult pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakeFocusMeteringResult_37( + returnValue: _FakeFocusMeteringResult_23( this, Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakeFocusMeteringResult_37( + returnValueForMissingStub: _FakeFocusMeteringResult_23( this, Invocation.method(#pigeon_copy, []), ), @@ -2784,11 +1412,11 @@ class MockImageAnalysis extends _i1.Mock implements _i2.ImageAnalysis { _i2.ImageAnalysis pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakeImageAnalysis_26( + returnValue: _FakeImageAnalysis_24( this, Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakeImageAnalysis_26( + returnValueForMissingStub: _FakeImageAnalysis_24( this, Invocation.method(#pigeon_copy, []), ), @@ -2825,14 +1453,22 @@ class MockImageCapture extends _i1.Mock implements _i2.ImageCapture { as _i5.Future); @override - _i5.Future takePicture() => + _i5.Future takePicture( + _i2.SystemServicesManager? systemServicesManager, + ) => (super.noSuchMethod( - Invocation.method(#takePicture, []), + Invocation.method(#takePicture, [systemServicesManager]), returnValue: _i5.Future.value( - _i6.dummyValue(this, Invocation.method(#takePicture, [])), + _i6.dummyValue( + this, + Invocation.method(#takePicture, [systemServicesManager]), + ), ), returnValueForMissingStub: _i5.Future.value( - _i6.dummyValue(this, Invocation.method(#takePicture, [])), + _i6.dummyValue( + this, + Invocation.method(#takePicture, [systemServicesManager]), + ), ), ) as _i5.Future); @@ -2850,11 +1486,11 @@ class MockImageCapture extends _i1.Mock implements _i2.ImageCapture { _i2.ImageCapture pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakeImageCapture_23( + returnValue: _FakeImageCapture_25( this, Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakeImageCapture_23( + returnValueForMissingStub: _FakeImageCapture_25( this, Invocation.method(#pigeon_copy, []), ), @@ -2934,11 +1570,11 @@ class MockImageProxy extends _i1.Mock implements _i2.ImageProxy { _i2.ImageProxy pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakeImageProxy_38( + returnValue: _FakeImageProxy_26( this, Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakeImageProxy_38( + returnValueForMissingStub: _FakeImageProxy_26( this, Invocation.method(#pigeon_copy, []), ), @@ -2979,11 +1615,11 @@ class MockObserver extends _i1.Mock implements _i3.Observer<_i2.CameraState> { _i3.Observer<_i2.CameraState> pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakeObserver_16<_i2.CameraState>( + returnValue: _FakeObserver_27<_i2.CameraState>( this, Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakeObserver_16<_i2.CameraState>( + returnValueForMissingStub: _FakeObserver_27<_i2.CameraState>( this, Invocation.method(#pigeon_copy, []), ), @@ -3015,13 +1651,13 @@ class MockPendingRecording extends _i1.Mock implements _i2.PendingRecording { (super.noSuchMethod( Invocation.method(#withAudioEnabled, [initialMuted]), returnValue: _i5.Future<_i2.PendingRecording>.value( - _FakePendingRecording_39( + _FakePendingRecording_28( this, Invocation.method(#withAudioEnabled, [initialMuted]), ), ), returnValueForMissingStub: _i5.Future<_i2.PendingRecording>.value( - _FakePendingRecording_39( + _FakePendingRecording_28( this, Invocation.method(#withAudioEnabled, [initialMuted]), ), @@ -3034,13 +1670,13 @@ class MockPendingRecording extends _i1.Mock implements _i2.PendingRecording { (super.noSuchMethod( Invocation.method(#asPersistentRecording, []), returnValue: _i5.Future<_i2.PendingRecording>.value( - _FakePendingRecording_39( + _FakePendingRecording_28( this, Invocation.method(#asPersistentRecording, []), ), ), returnValueForMissingStub: _i5.Future<_i2.PendingRecording>.value( - _FakePendingRecording_39( + _FakePendingRecording_28( this, Invocation.method(#asPersistentRecording, []), ), @@ -3053,10 +1689,10 @@ class MockPendingRecording extends _i1.Mock implements _i2.PendingRecording { (super.noSuchMethod( Invocation.method(#start, [listener]), returnValue: _i5.Future<_i2.Recording>.value( - _FakeRecording_40(this, Invocation.method(#start, [listener])), + _FakeRecording_29(this, Invocation.method(#start, [listener])), ), returnValueForMissingStub: _i5.Future<_i2.Recording>.value( - _FakeRecording_40(this, Invocation.method(#start, [listener])), + _FakeRecording_29(this, Invocation.method(#start, [listener])), ), ) as _i5.Future<_i2.Recording>); @@ -3065,11 +1701,11 @@ class MockPendingRecording extends _i1.Mock implements _i2.PendingRecording { _i2.PendingRecording pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakePendingRecording_39( + returnValue: _FakePendingRecording_28( this, Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakePendingRecording_39( + returnValueForMissingStub: _FakePendingRecording_28( this, Invocation.method(#pigeon_copy, []), ), @@ -3082,13 +1718,13 @@ class MockPendingRecording extends _i1.Mock implements _i2.PendingRecording { /// See the documentation for Mockito's code generation for more information. class MockPlaneProxy extends _i1.Mock implements _i2.PlaneProxy { @override - _i9.Uint8List get buffer => + _i7.Uint8List get buffer => (super.noSuchMethod( Invocation.getter(#buffer), - returnValue: _i9.Uint8List(0), - returnValueForMissingStub: _i9.Uint8List(0), + returnValue: _i7.Uint8List(0), + returnValueForMissingStub: _i7.Uint8List(0), ) - as _i9.Uint8List); + as _i7.Uint8List); @override int get pixelStride => @@ -3127,11 +1763,11 @@ class MockPlaneProxy extends _i1.Mock implements _i2.PlaneProxy { _i2.PlaneProxy pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakePlaneProxy_41( + returnValue: _FakePlaneProxy_30( this, Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakePlaneProxy_41( + returnValueForMissingStub: _FakePlaneProxy_30( this, Invocation.method(#pigeon_copy, []), ), @@ -3209,11 +1845,11 @@ class MockPreview extends _i1.Mock implements _i2.Preview { _i2.Preview pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakePreview_19( + returnValue: _FakePreview_31( this, Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakePreview_19( + returnValueForMissingStub: _FakePreview_31( this, Invocation.method(#pigeon_copy, []), ), @@ -3307,11 +1943,11 @@ class MockProcessCameraProvider extends _i1.Mock _i2.ProcessCameraProvider pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakeProcessCameraProvider_33( + returnValue: _FakeProcessCameraProvider_32( this, Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakeProcessCameraProvider_33( + returnValueForMissingStub: _FakeProcessCameraProvider_32( this, Invocation.method(#pigeon_copy, []), ), @@ -3342,11 +1978,11 @@ class MockQualitySelector extends _i1.Mock implements _i2.QualitySelector { _i2.QualitySelector pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakeQualitySelector_27( + returnValue: _FakeQualitySelector_33( this, Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakeQualitySelector_27( + returnValueForMissingStub: _FakeQualitySelector_33( this, Invocation.method(#pigeon_copy, []), ), @@ -3396,13 +2032,13 @@ class MockRecorder extends _i1.Mock implements _i2.Recorder { (super.noSuchMethod( Invocation.method(#getQualitySelector, []), returnValue: _i5.Future<_i2.QualitySelector>.value( - _FakeQualitySelector_27( + _FakeQualitySelector_33( this, Invocation.method(#getQualitySelector, []), ), ), returnValueForMissingStub: _i5.Future<_i2.QualitySelector>.value( - _FakeQualitySelector_27( + _FakeQualitySelector_33( this, Invocation.method(#getQualitySelector, []), ), @@ -3415,13 +2051,13 @@ class MockRecorder extends _i1.Mock implements _i2.Recorder { (super.noSuchMethod( Invocation.method(#prepareRecording, [path]), returnValue: _i5.Future<_i2.PendingRecording>.value( - _FakePendingRecording_39( + _FakePendingRecording_28( this, Invocation.method(#prepareRecording, [path]), ), ), returnValueForMissingStub: _i5.Future<_i2.PendingRecording>.value( - _FakePendingRecording_39( + _FakePendingRecording_28( this, Invocation.method(#prepareRecording, [path]), ), @@ -3433,11 +2069,11 @@ class MockRecorder extends _i1.Mock implements _i2.Recorder { _i2.Recorder pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakeRecorder_21( + returnValue: _FakeRecorder_34( this, Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakeRecorder_21( + returnValueForMissingStub: _FakeRecorder_34( this, Invocation.method(#pigeon_copy, []), ), @@ -3468,11 +2104,11 @@ class MockResolutionFilter extends _i1.Mock implements _i2.ResolutionFilter { _i2.ResolutionFilter pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakeResolutionFilter_31( + returnValue: _FakeResolutionFilter_35( this, Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakeResolutionFilter_31( + returnValueForMissingStub: _FakeResolutionFilter_35( this, Invocation.method(#pigeon_copy, []), ), @@ -3524,11 +2160,11 @@ class MockResolutionSelector extends _i1.Mock _i2.ResolutionSelector pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakeResolutionSelector_25( + returnValue: _FakeResolutionSelector_36( this, Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakeResolutionSelector_25( + returnValueForMissingStub: _FakeResolutionSelector_36( this, Invocation.method(#pigeon_copy, []), ), @@ -3583,11 +2219,11 @@ class MockResolutionStrategy extends _i1.Mock _i2.ResolutionStrategy pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakeResolutionStrategy_24( + returnValue: _FakeResolutionStrategy_37( this, Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakeResolutionStrategy_24( + returnValueForMissingStub: _FakeResolutionStrategy_37( this, Invocation.method(#pigeon_copy, []), ), @@ -3654,11 +2290,11 @@ class MockRecording extends _i1.Mock implements _i2.Recording { _i2.Recording pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakeRecording_40( + returnValue: _FakeRecording_29( this, Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakeRecording_40( + returnValueForMissingStub: _FakeRecording_29( this, Invocation.method(#pigeon_copy, []), ), @@ -3738,11 +2374,11 @@ class MockSystemServicesManager extends _i1.Mock _i2.SystemServicesManager pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakeSystemServicesManager_17( + returnValue: _FakeSystemServicesManager_38( this, Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakeSystemServicesManager_17( + returnValueForMissingStub: _FakeSystemServicesManager_38( this, Invocation.method(#pigeon_copy, []), ), @@ -3774,10 +2410,10 @@ class MockVideoCapture extends _i1.Mock implements _i2.VideoCapture { (super.noSuchMethod( Invocation.method(#getOutput, []), returnValue: _i5.Future<_i2.VideoOutput>.value( - _FakeVideoOutput_42(this, Invocation.method(#getOutput, [])), + _FakeVideoOutput_39(this, Invocation.method(#getOutput, [])), ), returnValueForMissingStub: _i5.Future<_i2.VideoOutput>.value( - _FakeVideoOutput_42(this, Invocation.method(#getOutput, [])), + _FakeVideoOutput_39(this, Invocation.method(#getOutput, [])), ), ) as _i5.Future<_i2.VideoOutput>); @@ -3795,11 +2431,11 @@ class MockVideoCapture extends _i1.Mock implements _i2.VideoCapture { _i2.VideoCapture pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakeVideoCapture_20( + returnValue: _FakeVideoCapture_40( this, Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakeVideoCapture_20( + returnValueForMissingStub: _FakeVideoCapture_40( this, Invocation.method(#pigeon_copy, []), ), @@ -3848,11 +2484,11 @@ class MockZoomState extends _i1.Mock implements _i2.ZoomState { _i2.ZoomState pigeon_copy() => (super.noSuchMethod( Invocation.method(#pigeon_copy, []), - returnValue: _FakeZoomState_43( + returnValue: _FakeZoomState_41( this, Invocation.method(#pigeon_copy, []), ), - returnValueForMissingStub: _FakeZoomState_43( + returnValueForMissingStub: _FakeZoomState_41( this, Invocation.method(#pigeon_copy, []), ), 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 28177122de5b..cfc6b2db103b 100644 --- a/packages/camera/camera_android_camerax/test/preview_rotation_test.dart +++ b/packages/camera/camera_android_camerax/test/preview_rotation_test.dart @@ -4,7 +4,6 @@ import 'package:camera_android_camerax/camera_android_camerax.dart'; import 'package:camera_android_camerax/src/camerax_library.dart'; -import 'package:camera_android_camerax/src/camerax_proxy.dart'; import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart' @@ -39,6 +38,11 @@ void main() { AndroidCameraCameraX.deviceOrientationChangedStreamController.close(); }); + setUp(() { + PigeonOverrides.pigeon_reset(); + GenericsPigeonOverrides.reset(); + }); + /// Sets up mock CameraSelector and mock ProcessCameraProvider used to /// select test camera when `availableCameras` is called. /// @@ -50,11 +54,11 @@ void main() { setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera({ required MockCameraSelector mockCameraSelector, required int sensorRotationDegrees, + required bool isCameraFrontFacing, }) { - final MockProcessCameraProvider mockProcessCameraProvider = - MockProcessCameraProvider(); - final MockCameraInfo mockCameraInfo = MockCameraInfo(); - final MockCamera mockCamera = MockCamera(); + final mockProcessCameraProvider = MockProcessCameraProvider(); + final mockCameraInfo = MockCameraInfo(); + final mockCamera = MockCamera(); // Mock retrieving available test camera. when( @@ -65,8 +69,8 @@ void main() { mockProcessCameraProvider.getAvailableCameraInfos(), ).thenAnswer((_) async => [mockCameraInfo]); when( - mockCameraSelector.filter([mockCameraInfo]), - ).thenAnswer((_) async => [mockCameraInfo]); + mockCameraInfo.lensFacing, + ).thenReturn(isCameraFrontFacing ? LensFacing.front : LensFacing.back); when( mockCameraInfo.sensorRotationDegrees, ).thenReturn(sensorRotationDegrees); @@ -80,43 +84,31 @@ void main() { return mockProcessCameraProvider; } - /// Returns CameraXProxy used to mock all calls to native Android in + /// Set up overrides used to mock all calls to native Android in /// the `availableCameras` and `createCameraWithSettings` methods, with /// a DeviceORientationManager specified. /// /// Useful for tests that need a reference to a DeviceOrientationManager. - CameraXProxy getProxyForCreatingTestCameraWithDeviceOrientationManager( + void setUpOverridesForCreatingTestCameraWithDeviceOrientationManager( DeviceOrientationManager deviceOrientationManager, { required MockProcessCameraProvider mockProcessCameraProvider, required CameraSelector Function({ LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, + dynamic cameraInfoForFilter, }) createCameraSelector, required bool handlesCropAndRotation, - }) => CameraXProxy( - getInstanceProcessCameraProvider: - ({ - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - }) async => mockProcessCameraProvider, - newCameraSelector: createCameraSelector, - newPreview: + }) { + PigeonOverrides.processCameraProvider_getInstance = () async => + mockProcessCameraProvider; + PigeonOverrides.cameraSelector_new = createCameraSelector; + PigeonOverrides.preview_new = ({ int? targetRotation, + CameraIntegerRange? targetFpsRange, ResolutionSelector? resolutionSelector, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, }) { - final MockPreview preview = MockPreview(); + final preview = MockPreview(); when( preview.surfaceProducerHandlesCropAndRotation(), ).thenAnswer((_) async => handlesCropAndRotation); @@ -125,163 +117,90 @@ void main() { ResolutionInfo.pigeon_detached(resolution: MockCameraSize()), ); return preview; - }, - newImageCapture: + }; + PigeonOverrides.imageCapture_new = ({ int? targetRotation, CameraXFlashMode? flashMode, ResolutionSelector? resolutionSelector, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - }) => MockImageCapture(), - newRecorder: + }) => MockImageCapture(); + PigeonOverrides.recorder_new = ({ int? aspectRatio, int? targetVideoEncodingBitRate, QualitySelector? qualitySelector, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - }) => MockRecorder(), - withOutputVideoCapture: + }) => MockRecorder(); + PigeonOverrides.videoCapture_withOutput = ({ required VideoOutput videoOutput, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, + CameraIntegerRange? targetFpsRange, }) { return MockVideoCapture(); - }, - newImageAnalysis: + }; + PigeonOverrides.imageAnalysis_new = ({ int? targetRotation, + CameraIntegerRange? targetFpsRange, ResolutionSelector? resolutionSelector, int? outputImageFormat, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, }) { return MockImageAnalysis(); - }, - newResolutionStrategy: + }; + PigeonOverrides.resolutionStrategy_new = ({ 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: + }; + PigeonOverrides.resolutionSelector_new = ({ 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, - }) { + }; + PigeonOverrides.fallbackStrategy_lowerQualityOrHigherThan = + ({required VideoQuality quality}) { return MockFallbackStrategy(); - }, - lowerQualityThanFallbackStrategy: - ({ - required VideoQuality quality, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - }) { + }; + PigeonOverrides.fallbackStrategy_lowerQualityThan = + ({required VideoQuality quality}) { 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, - }) { + }; + PigeonOverrides.camera2CameraInfo_from = ({required dynamic cameraInfo}) { + final camera2cameraInfo = MockCamera2CameraInfo(); + when( + camera2cameraInfo.getCameraCharacteristic(any), + ).thenAnswer((_) async => 90); + return camera2cameraInfo; + }; + PigeonOverrides.qualitySelector_from = + ({required VideoQuality quality, FallbackStrategy? fallbackStrategy}) { 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: + }; + GenericsPigeonOverrides.observerNew = + ({required void Function(Observer, T) onChanged}) { + return Observer.detached(onChanged: onChanged); + }; + PigeonOverrides.systemServicesManager_new = ({ 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: + }; + PigeonOverrides.deviceOrientationManager_new = ({ required void Function(DeviceOrientationManager, String) onDeviceOrientationChanged, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - }) => deviceOrientationManager, - newAspectRatioStrategy: + }) => deviceOrientationManager; + PigeonOverrides.aspectRatioStrategy_new = ({ 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(); + final mockAspectRatioStrategy = MockAspectRatioStrategy(); when( mockAspectRatioStrategy.getFallbackRule(), ).thenAnswer((_) async => fallbackRule); @@ -289,49 +208,38 @@ void main() { 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, - }) { + }; + PigeonOverrides.resolutionFilter_createWithOnePreferredSize = + ({required CameraSize preferredSize}) { return MockResolutionFilter(); - }, - ); + }; + } - /// Returns CameraXProxy used to mock all calls to native Android in + /// Set up overrides used to mock all calls to native Android in /// the `availableCameras` and `createCameraWithSettings` methods, with /// functions `getUiOrientation` and `getDefaultDisplayRotation` specified /// to create a mock DeviceOrientationManager. /// /// Useful for tests that do not need a reference to a DeviceOrientationManager. - CameraXProxy getProxyForCreatingTestCamera({ + void setUpOverridesForCreatingTestCamera({ required MockProcessCameraProvider mockProcessCameraProvider, required CameraSelector Function({ LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, + dynamic cameraInfoForFilter, }) createCameraSelector, required bool handlesCropAndRotation, required Future Function() getUiOrientation, required Future Function() getDefaultDisplayRotation, }) { - final MockDeviceOrientationManager deviceOrientationManager = - MockDeviceOrientationManager(); + final deviceOrientationManager = MockDeviceOrientationManager(); when( deviceOrientationManager.getUiOrientation(), ).thenAnswer((_) => getUiOrientation()); when( deviceOrientationManager.getDefaultDisplayRotation(), ).thenAnswer((_) => getDefaultDisplayRotation()); - return getProxyForCreatingTestCameraWithDeviceOrientationManager( + setUpOverridesForCreatingTestCameraWithDeviceOrientationManager( deviceOrientationManager, mockProcessCameraProvider: mockProcessCameraProvider, createCameraSelector: createCameraSelector, @@ -342,21 +250,10 @@ void main() { /// Returns function that a CameraXProxy can use to select the front camera. MockCameraSelector Function({ LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, + dynamic cameraInfoForFilter, }) createCameraSelectorForFrontCamera(MockCameraSelector mockCameraSelector) { - return ({ - LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - }) { + return ({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) { switch (requireLensFacing) { case LensFacing.front: return mockCameraSelector; @@ -372,21 +269,10 @@ void main() { /// Returns function that a CameraXProxy can use to select the back camera. MockCameraSelector Function({ LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, + dynamic cameraInfoForFilter, }) createCameraSelectorForBackCamera(MockCameraSelector mockCameraSelector) { - return ({ - LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, - }) { + return ({LensFacing? requireLensFacing, dynamic cameraInfoForFilter}) { switch (requireLensFacing) { case LensFacing.back: return mockCameraSelector; @@ -413,7 +299,7 @@ void main() { /// [ 0.0, 0.0, 1.0, 0.0], /// [ 0.0, 0.0, 0.0, 1.0]] void checkXAxisIsMirrored(Matrix4 transformationMatrix) { - final Matrix4 mirrorAcrossXMatrix = Matrix4( + final mirrorAcrossXMatrix = Matrix4( -1.0, 0.0, 0.0, @@ -445,7 +331,7 @@ void main() { /// [ 0.0, 0.0, 1.0, 0.0], /// [ 0.0, 0.0, 0.0, 1.0]] void checkYAxisIsMirrored(Matrix4 transformationMatrix) { - final Matrix4 mirrorAcrossYMatrix = Matrix4( + final mirrorAcrossYMatrix = Matrix4( 1.0, 0.0, 0.0, @@ -473,18 +359,14 @@ void main() { group('when handlesCropAndRotation is true', () { // Test that preview rotation responds to initial default display rotation: group('initial device orientation is landscapeRight,', () { - final MockCameraSelector mockCameraSelector = MockCameraSelector(); + final mockCameraSelector = MockCameraSelector(); late AndroidCameraCameraX camera; late int cameraId; late DeviceOrientation testInitialDeviceOrientation; late MockProcessCameraProvider mockProcessCameraProvider; late MockCameraSelector Function({ - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, + dynamic cameraInfoForFilter, }) fakeCreateCameraSelector; late MediaSettings testMediaSettings; @@ -501,6 +383,7 @@ void main() { setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( mockCameraSelector: mockCameraSelector, sensorRotationDegrees: /* irrelevant for test */ 90, + isCameraFrontFacing: false, ); fakeCreateCameraSelector = createCameraSelectorForBackCamera( mockCameraSelector, @@ -515,7 +398,7 @@ void main() { (WidgetTester tester) async { // Mock calls to CameraXProxy. Most importantly, tell camera that handlesCropAndRotation is true, set initial device // orientation to landscape right, and set initial default display rotation to 0 degrees clockwise. - camera.proxy = getProxyForCreatingTestCamera( + setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProvider, createCameraSelector: fakeCreateCameraSelector, handlesCropAndRotation: true, @@ -570,7 +453,7 @@ void main() { (WidgetTester tester) async { // Mock calls to CameraXProxy. Most importantly, tell camera that handlesCropAndRotation is true, set initial device // orientation to landscape right, and set initial default display rotation to 90 degrees clockwise. - camera.proxy = getProxyForCreatingTestCamera( + setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProvider, createCameraSelector: fakeCreateCameraSelector, handlesCropAndRotation: true, @@ -623,7 +506,7 @@ void main() { (WidgetTester tester) async { // Mock calls to CameraXProxy. Most importantly, tell camera that handlesCropAndRotation is true, set initial device // orientation to landscape right, and set initial default display rotation to 180 degrees clockwise. - camera.proxy = getProxyForCreatingTestCamera( + setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProvider, createCameraSelector: fakeCreateCameraSelector, handlesCropAndRotation: true, @@ -676,7 +559,7 @@ void main() { (WidgetTester tester) async { // Mock calls to CameraXProxy. Most importantly, tell camera that handlesCropAndRotation is true, set initial device // orientation to landscape right, and set initial default display rotation to 270 degrees clockwise. - camera.proxy = getProxyForCreatingTestCamera( + setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProvider, createCameraSelector: fakeCreateCameraSelector, handlesCropAndRotation: true, @@ -728,18 +611,14 @@ void main() { // Test that preview rotation responds to initial device orientation: group('initial default display rotation is 90,', () { - final MockCameraSelector mockCameraSelector = MockCameraSelector(); + final mockCameraSelector = MockCameraSelector(); late AndroidCameraCameraX camera; late int cameraId; late int testInitialDefaultDisplayRotation; late MockProcessCameraProvider mockProcessCameraProvider; late MockCameraSelector Function({ - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, + dynamic cameraInfoForFilter, }) fakeCreateCameraSelector; late MediaSettings testMediaSettings; @@ -756,6 +635,7 @@ void main() { setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( mockCameraSelector: mockCameraSelector, sensorRotationDegrees: /* irrelevant for test */ 90, + isCameraFrontFacing: false, ); fakeCreateCameraSelector = createCameraSelectorForBackCamera( mockCameraSelector, @@ -770,7 +650,7 @@ void main() { (WidgetTester tester) async { // Mock calls to CameraXProxy. Most importantly, tell camera that handlesCropAndRotation is true, set initial device // orientation to portrait up, and set initial default display rotation to 90 degrees clockwise. - camera.proxy = getProxyForCreatingTestCamera( + setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProvider, createCameraSelector: fakeCreateCameraSelector, handlesCropAndRotation: true, @@ -823,7 +703,7 @@ void main() { (WidgetTester tester) async { // Mock calls to CameraXProxy. Most importantly, tell camera that handlesCropAndRotation is true, set initial device // orientation to landscape left, and set initial default display rotation to 90 degrees clockwise. - camera.proxy = getProxyForCreatingTestCamera( + setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProvider, createCameraSelector: fakeCreateCameraSelector, handlesCropAndRotation: true, @@ -876,7 +756,7 @@ void main() { (WidgetTester tester) async { // Mock calls to CameraXProxy. Most importantly, tell camera that handlesCropAndRotation is true, set initial device // orientation to portrait down, and set initial default display rotation to 90 degrees clockwise. - camera.proxy = getProxyForCreatingTestCamera( + setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProvider, createCameraSelector: fakeCreateCameraSelector, handlesCropAndRotation: true, @@ -929,7 +809,7 @@ void main() { (WidgetTester tester) async { // Mock calls to CameraXProxy. Most importantly, tell camera that handlesCropAndRotation is true, set initial device // orientation to landscape right, and set initial default display rotation to 90 degrees clockwise. - camera.proxy = getProxyForCreatingTestCamera( + setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProvider, createCameraSelector: fakeCreateCameraSelector, handlesCropAndRotation: true, @@ -983,21 +863,17 @@ void main() { testWidgets( 'device orientation is portraitDown, then the preview Texture rotates correctly as the default display rotation changes', (WidgetTester tester) async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 11; + final camera = AndroidCameraCameraX(); + const cameraId = 11; const DeviceOrientation testDeviceOrientation = DeviceOrientation.portraitDown; // Create and set up mock CameraSelector, mock ProcessCameraProvider, and media settings for test front camera. // These settings do not matter for this test. - final MockCameraSelector mockFrontCameraSelector = MockCameraSelector(); + final mockFrontCameraSelector = MockCameraSelector(); final MockCameraSelector Function({ - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, + dynamic cameraInfoForFilter, }) proxyCreateCameraSelectorForFrontCamera = createCameraSelectorForFrontCamera(mockFrontCameraSelector); @@ -1006,13 +882,13 @@ void main() { setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( mockCameraSelector: mockFrontCameraSelector, sensorRotationDegrees: 270, + isCameraFrontFacing: false, ); - const MediaSettings testMediaSettings = MediaSettings(); + const testMediaSettings = MediaSettings(); // Tell camera that handlesCropAndRotation is true, set camera initial device orientation // to portrait down, set initial default display rotation to 0 degrees clockwise. - final MockDeviceOrientationManager mockDeviceOrientationManager = - MockDeviceOrientationManager(); + final mockDeviceOrientationManager = MockDeviceOrientationManager(); when(mockDeviceOrientationManager.getUiOrientation()).thenAnswer( (_) => Future.value( _serializeDeviceOrientation(testDeviceOrientation), @@ -1022,8 +898,7 @@ void main() { mockDeviceOrientationManager.getDefaultDisplayRotation(), ).thenAnswer((_) => Future.value(Surface.rotation0)); - camera - .proxy = getProxyForCreatingTestCameraWithDeviceOrientationManager( + setUpOverridesForCreatingTestCameraWithDeviceOrientationManager( mockDeviceOrientationManager, mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, @@ -1044,13 +919,12 @@ void main() { // Calculated according to: counterClockwiseCurrentDefaultDisplayRotation - cameraPreviewPreAppliedRotation, // where the cameraPreviewPreAppliedRotation is the clockwise rotation applied by the CameraPreview widget // according to the current device orientation (fixed to portraitDown for this test, so it is 180). - final Map expectedRotationPerDefaultDisplayRotation = - { - Surface.rotation0: _180DegreesClockwise, - Surface.rotation90: _90DegreesClockwise, - Surface.rotation180: _0DegreesClockwise, - Surface.rotation270: _270DegreesClockwise, - }; + final expectedRotationPerDefaultDisplayRotation = { + Surface.rotation0: _180DegreesClockwise, + Surface.rotation90: _90DegreesClockwise, + Surface.rotation180: _0DegreesClockwise, + Surface.rotation270: _270DegreesClockwise, + }; // Put camera preview in widget tree. await tester.pumpWidget(camera.buildPreview(cameraId)); @@ -1062,8 +936,9 @@ void main() { mockDeviceOrientationManager.getDefaultDisplayRotation(), ).thenAnswer((_) => Future.value(currentDefaultDisplayRotation)); - const DeviceOrientationChangedEvent testEvent = - DeviceOrientationChangedEvent(testDeviceOrientation); + const testEvent = DeviceOrientationChangedEvent( + testDeviceOrientation, + ); AndroidCameraCameraX.deviceOrientationChangedStreamController.add( testEvent, ); @@ -1095,20 +970,16 @@ void main() { testWidgets( 'initial default display rotation is 270 degrees clockwise, then the preview Texture rotates correctly as the device orientation changes', (WidgetTester tester) async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 11; + final camera = AndroidCameraCameraX(); + const cameraId = 11; const int testInitialDefaultDisplayRotation = Surface.rotation270; // Create and set up mock CameraSelector, mock ProcessCameraProvider, and media settings for test front camera. // These settings do not matter for this test. - final MockCameraSelector mockFrontCameraSelector = MockCameraSelector(); + final mockFrontCameraSelector = MockCameraSelector(); final MockCameraSelector Function({ - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, + dynamic cameraInfoForFilter, }) proxyCreateCameraSelectorForFrontCamera = createCameraSelectorForFrontCamera(mockFrontCameraSelector); @@ -1117,12 +988,13 @@ void main() { setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( mockCameraSelector: mockFrontCameraSelector, sensorRotationDegrees: 270, + isCameraFrontFacing: true, ); - const MediaSettings testMediaSettings = MediaSettings(); + const testMediaSettings = MediaSettings(); // Tell camera that handlesCropAndRotation is true, set camera initial device orientation // to portrait up, set initial default display rotation to 270 degrees clockwise. - camera.proxy = getProxyForCreatingTestCamera( + setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, handlesCropAndRotation: true, @@ -1148,21 +1020,21 @@ void main() { // where the cameraPreviewPreAppliedRotation is the clockwise rotation applied by the CameraPreview widget // according to the current device orientation. counterClockwiseCurrentDefaultDisplayRotation is fixed to 90 for // this test (the counter-clockwise rotation of the clockwise 270 degree default display rotation). - final Map expectedRotationPerDeviceOrientation = - { - DeviceOrientation.portraitUp: _90DegreesClockwise, - DeviceOrientation.landscapeRight: _0DegreesClockwise, - DeviceOrientation.portraitDown: _270DegreesClockwise, - DeviceOrientation.landscapeLeft: _180DegreesClockwise, - }; + final expectedRotationPerDeviceOrientation = { + DeviceOrientation.portraitUp: _90DegreesClockwise, + DeviceOrientation.landscapeRight: _0DegreesClockwise, + DeviceOrientation.portraitDown: _270DegreesClockwise, + DeviceOrientation.landscapeLeft: _180DegreesClockwise, + }; // Put camera preview in widget tree. await tester.pumpWidget(camera.buildPreview(cameraId)); for (final DeviceOrientation currentDeviceOrientation in expectedRotationPerDeviceOrientation.keys) { - final DeviceOrientationChangedEvent testEvent = - DeviceOrientationChangedEvent(currentDeviceOrientation); + final testEvent = DeviceOrientationChangedEvent( + currentDeviceOrientation, + ); AndroidCameraCameraX.deviceOrientationChangedStreamController.add( testEvent, ); @@ -1201,11 +1073,7 @@ void main() { late MockCameraSelector mockFrontCameraSelector; late MockCameraSelector Function({ LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, + dynamic cameraInfoForFilter, }) proxyCreateCameraSelectorForFrontCamera; late MockProcessCameraProvider mockProcessCameraProviderForFrontCamera; @@ -1226,6 +1094,7 @@ void main() { setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( mockCameraSelector: mockFrontCameraSelector, sensorRotationDegrees: 270, + isCameraFrontFacing: true, ); proxyGetDefaultDisplayRotation = () => Future.value(Surface.rotation0); @@ -1239,7 +1108,7 @@ void main() { (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( + setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, @@ -1276,7 +1145,7 @@ void main() { // used. expect(rotatedBox.child, isA()); - final Transform transformedPreview = rotatedBox.child! as Transform; + final transformedPreview = rotatedBox.child! as Transform; final Matrix4 transformedPreviewMatrix = transformedPreview.transform; @@ -1300,7 +1169,7 @@ void main() { (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( + setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, @@ -1337,7 +1206,7 @@ void main() { // used. expect(rotatedBox.child, isA()); - final Transform transformedPreview = rotatedBox.child! as Transform; + final transformedPreview = rotatedBox.child! as Transform; final Matrix4 transformedPreviewMatrix = transformedPreview.transform; @@ -1361,7 +1230,7 @@ void main() { (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( + setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, @@ -1398,7 +1267,7 @@ void main() { // used. expect(rotatedBox.child, isA()); - final Transform transformedPreview = rotatedBox.child! as Transform; + final transformedPreview = rotatedBox.child! as Transform; final Matrix4 transformedPreviewMatrix = transformedPreview.transform; @@ -1422,7 +1291,7 @@ void main() { (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( + setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, @@ -1459,7 +1328,7 @@ void main() { // used. expect(rotatedBox.child, isA()); - final Transform transformedPreview = rotatedBox.child! as Transform; + final transformedPreview = rotatedBox.child! as Transform; final Matrix4 transformedPreviewMatrix = transformedPreview.transform; @@ -1489,12 +1358,8 @@ void main() { late MockCameraSelector mockFrontCameraSelector; late MockProcessCameraProvider mockProcessCameraProviderForFrontCamera; late MockCameraSelector Function({ - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, + dynamic cameraInfoForFilter, }) proxyCreateCameraSelectorForFrontCamera; late Future Function() proxyGetUiOrientation; @@ -1514,6 +1379,7 @@ void main() { setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( mockCameraSelector: mockFrontCameraSelector, sensorRotationDegrees: 270, + isCameraFrontFacing: true, ); proxyGetUiOrientation = () async => _serializeDeviceOrientation(DeviceOrientation.landscapeLeft); @@ -1527,7 +1393,7 @@ void main() { (WidgetTester tester) async { // Set up test to use front camera, tell camera that handlesCropAndRotation is false, // set camera initial default display rotation to 0 degrees. - camera.proxy = getProxyForCreatingTestCamera( + setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, @@ -1564,7 +1430,7 @@ void main() { // used. expect(rotatedBox.child, isA()); - final Transform transformedPreview = rotatedBox.child! as Transform; + final transformedPreview = rotatedBox.child! as Transform; final Matrix4 transformedPreviewMatrix = transformedPreview.transform; @@ -1588,7 +1454,7 @@ void main() { (WidgetTester tester) async { // Set up test to use front camera, tell camera that handlesCropAndRotation is false, // set camera initial default display rotation to 0 degrees. - camera.proxy = getProxyForCreatingTestCamera( + setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, @@ -1627,7 +1493,7 @@ void main() { // used. expect(rotatedBox.child, isA()); - final Transform transformedPreview = rotatedBox.child! as Transform; + final transformedPreview = rotatedBox.child! as Transform; final Matrix4 transformedPreviewMatrix = transformedPreview.transform; @@ -1653,7 +1519,7 @@ void main() { (WidgetTester tester) async { // Set up test to use front camera, tell camera that handlesCropAndRotation is false, // set camera initial default display rotation to 0 degrees. - camera.proxy = getProxyForCreatingTestCamera( + setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, @@ -1690,7 +1556,7 @@ void main() { // used. expect(rotatedBox.child, isA()); - final Transform transformedPreview = rotatedBox.child! as Transform; + final transformedPreview = rotatedBox.child! as Transform; final Matrix4 transformedPreviewMatrix = transformedPreview.transform; @@ -1716,7 +1582,7 @@ void main() { (WidgetTester tester) async { // Set up test to use front camera, tell camera that handlesCropAndRotation is false, // set camera initial default display rotation to 0 degrees. - camera.proxy = getProxyForCreatingTestCamera( + setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, @@ -1755,7 +1621,7 @@ void main() { // used. expect(rotatedBox.child, isA()); - final Transform transformedPreview = rotatedBox.child! as Transform; + final transformedPreview = rotatedBox.child! as Transform; final Matrix4 transformedPreviewMatrix = transformedPreview.transform; @@ -1782,21 +1648,17 @@ void main() { testWidgets( 'device orientation is landscapeRight, sensor orientation degrees is 270, camera is front facing, then the preview Texture rotates correctly as the default display rotation changes', (WidgetTester tester) async { - final AndroidCameraCameraX camera = AndroidCameraCameraX(); - const int cameraId = 11; + final camera = AndroidCameraCameraX(); + const cameraId = 11; const DeviceOrientation testDeviceOrientation = DeviceOrientation.landscapeRight; // Create and set up mock front camera CameraSelector, mock ProcessCameraProvider, 270 degree sensor orientation, // media settings for test front camera. - final MockCameraSelector mockFrontCameraSelector = MockCameraSelector(); + final mockFrontCameraSelector = MockCameraSelector(); final MockCameraSelector Function({ - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, + dynamic cameraInfoForFilter, }) proxyCreateCameraSelectorForFrontCamera = createCameraSelectorForFrontCamera(mockFrontCameraSelector); @@ -1805,13 +1667,13 @@ void main() { setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( mockCameraSelector: mockFrontCameraSelector, sensorRotationDegrees: 270, + isCameraFrontFacing: true, ); - const MediaSettings testMediaSettings = MediaSettings(); + const testMediaSettings = MediaSettings(); // Tell camera that handlesCropAndRotation is true, set camera initial device orientation // to portrait down, set initial default display rotation to 0 degrees clockwise. - final MockDeviceOrientationManager mockDeviceOrientationManager = - MockDeviceOrientationManager(); + final mockDeviceOrientationManager = MockDeviceOrientationManager(); when(mockDeviceOrientationManager.getUiOrientation()).thenAnswer( (_) => Future.value( _serializeDeviceOrientation(testDeviceOrientation), @@ -1820,8 +1682,7 @@ void main() { when( mockDeviceOrientationManager.getDefaultDisplayRotation(), ).thenAnswer((_) => Future.value(Surface.rotation0)); - camera - .proxy = getProxyForCreatingTestCameraWithDeviceOrientationManager( + setUpOverridesForCreatingTestCameraWithDeviceOrientationManager( mockDeviceOrientationManager, mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, @@ -1842,13 +1703,12 @@ void main() { // Calculated according to: ((270 - counterClockwiseDefaultDisplayRotation * 1 + 360) % 360) - 90. // 90 is used in this calculation for the CameraPreview pre-applied rotation because it is the // rotation that the CameraPreview widget aapplies based on the landscape right device orientation. - final Map expectedRotationPerDefaultDisplayRotation = - { - Surface.rotation0: _180DegreesClockwise, - Surface.rotation90: _270DegreesClockwise, - Surface.rotation180: _0DegreesClockwise, - Surface.rotation270: _90DegreesClockwise, - }; + final expectedRotationPerDefaultDisplayRotation = { + Surface.rotation0: _180DegreesClockwise, + Surface.rotation90: _270DegreesClockwise, + Surface.rotation180: _0DegreesClockwise, + Surface.rotation270: _90DegreesClockwise, + }; // Put camera preview in widget tree. await tester.pumpWidget(camera.buildPreview(cameraId)); @@ -1860,8 +1720,9 @@ void main() { mockDeviceOrientationManager.getDefaultDisplayRotation(), ).thenAnswer((_) async => currentDefaultDisplayRotation); - const DeviceOrientationChangedEvent testEvent = - DeviceOrientationChangedEvent(testDeviceOrientation); + const testEvent = DeviceOrientationChangedEvent( + testDeviceOrientation, + ); AndroidCameraCameraX.deviceOrientationChangedStreamController.add( testEvent, ); @@ -1880,7 +1741,7 @@ void main() { // used. expect(rotatedBox.child, isA()); - final Transform transformedPreview = rotatedBox.child! as Transform; + final transformedPreview = rotatedBox.child! as Transform; final Matrix4 transformedPreviewMatrix = transformedPreview.transform; // Since the front camera is in landscape mode, we expect the camera @@ -1905,19 +1766,15 @@ void main() { testWidgets( 'default display rotation is 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; + final camera = AndroidCameraCameraX(); + const 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 mockFrontCameraSelector = MockCameraSelector(); final MockCameraSelector Function({ LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, + dynamic cameraInfoForFilter, }) proxyCreateCameraSelectorForFrontCamera = createCameraSelectorForFrontCamera(mockFrontCameraSelector); @@ -1926,15 +1783,16 @@ void main() { setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( mockCameraSelector: mockFrontCameraSelector, sensorRotationDegrees: 90, + isCameraFrontFacing: true, ); // Media settings to create camera; irrelevant for test. - const MediaSettings testMediaSettings = MediaSettings(); + const testMediaSettings = MediaSettings(); // Set up test to use front camera and tell camera that handlesCropAndRotation is false, // set camera initial device orientation to landscape left, set initial default display // rotation to 90 degrees clockwise. - camera.proxy = getProxyForCreatingTestCamera( + setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProviderForFrontCamera, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, handlesCropAndRotation: false, @@ -1959,21 +1817,21 @@ void main() { // Calculated according to: ((90 - 270 * 1 + 360) % 360) - cameraPreviewPreAppliedRotation. // 270 is used in this calculation for the device orientation because it is the // counter-clockwise degrees of the default display rotation. - final Map expectedRotationPerDeviceOrientation = - { - DeviceOrientation.portraitUp: _180DegreesClockwise, - DeviceOrientation.landscapeRight: _90DegreesClockwise, - DeviceOrientation.portraitDown: _0DegreesClockwise, - DeviceOrientation.landscapeLeft: _270DegreesClockwise, - }; + final expectedRotationPerDeviceOrientation = { + DeviceOrientation.portraitUp: _180DegreesClockwise, + DeviceOrientation.landscapeRight: _90DegreesClockwise, + DeviceOrientation.portraitDown: _0DegreesClockwise, + DeviceOrientation.landscapeLeft: _270DegreesClockwise, + }; // Put camera preview in widget tree. await tester.pumpWidget(camera.buildPreview(cameraId)); for (final DeviceOrientation currentDeviceOrientation in expectedRotationPerDeviceOrientation.keys) { - final DeviceOrientationChangedEvent testEvent = - DeviceOrientationChangedEvent(currentDeviceOrientation); + final testEvent = DeviceOrientationChangedEvent( + currentDeviceOrientation, + ); AndroidCameraCameraX.deviceOrientationChangedStreamController.add( testEvent, ); @@ -1992,7 +1850,7 @@ void main() { // used. expect(rotatedBox.child, isA()); - final Transform transformedPreview = rotatedBox.child! as Transform; + final transformedPreview = rotatedBox.child! as Transform; final Matrix4 transformedPreviewMatrix = transformedPreview.transform; // When the front camera is in landscape mode, we expect the camera @@ -2028,12 +1886,8 @@ void main() { late int cameraId; late MockCameraSelector mockBackCameraSelector; late MockCameraSelector Function({ - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, + dynamic cameraInfoForFilter, }) proxyCreateCameraSelectorForBackCamera; late Future Function() proxyGetDefaultDisplayRotation; @@ -2068,11 +1922,12 @@ void main() { setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( mockCameraSelector: mockBackCameraSelector, sensorRotationDegrees: 90, + isCameraFrontFacing: false, ); // Set up test to use back camera, tell camera that handlesCropAndRotation is false, // set camera initial device orientation to landscape left. - camera.proxy = getProxyForCreatingTestCamera( + setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProviderForBackCamera, createCameraSelector: proxyCreateCameraSelectorForBackCamera, getDefaultDisplayRotation: proxyGetDefaultDisplayRotation, @@ -2128,11 +1983,12 @@ void main() { setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( mockCameraSelector: mockBackCameraSelector, sensorRotationDegrees: 270, + isCameraFrontFacing: false, ); // Set up test to use back camera, tell camera that handlesCropAndRotation is false, // set camera initial device orientation to landscape left. - camera.proxy = getProxyForCreatingTestCamera( + setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProviderForBackCamera, createCameraSelector: proxyCreateCameraSelectorForBackCamera, getDefaultDisplayRotation: proxyGetDefaultDisplayRotation, @@ -2211,25 +2067,21 @@ void main() { 'camera is front 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 mockFrontCameraSelector = - MockCameraSelector(); + final mockFrontCameraSelector = MockCameraSelector(); final MockProcessCameraProvider mockProcessCameraProvider = setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( mockCameraSelector: mockFrontCameraSelector, sensorRotationDegrees: testSensorOrientation, + isCameraFrontFacing: true, ); // Set up front camera selection and initial device orientation as landscape right. final MockCameraSelector Function({ - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, + dynamic cameraInfoForFilter, }) proxyCreateCameraSelectorForFrontCamera = createCameraSelectorForFrontCamera(mockFrontCameraSelector); - camera.proxy = getProxyForCreatingTestCamera( + setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProvider, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, getDefaultDisplayRotation: proxyGetDefaultDisplayRotation, @@ -2267,7 +2119,7 @@ void main() { // used. expect(rotatedBox.child, isA()); - final Transform transformedPreview = rotatedBox.child! as Transform; + final transformedPreview = rotatedBox.child! as Transform; final Matrix4 transformedPreviewMatrix = transformedPreview.transform; @@ -2290,26 +2142,22 @@ void main() { 'camera is back 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 mockBackCameraSelector = - MockCameraSelector(); + final mockBackCameraSelector = MockCameraSelector(); final MockProcessCameraProvider mockProcessCameraProvider = setUpMockCameraSelectorAndMockProcessCameraProviderForSelectingTestCamera( mockCameraSelector: mockBackCameraSelector, sensorRotationDegrees: testSensorOrientation, + isCameraFrontFacing: false, ); // Set up front camera selection and initial device orientation as landscape right. final MockCameraSelector Function({ - // ignore: non_constant_identifier_names - BinaryMessenger? pigeon_binaryMessenger, - // ignore: non_constant_identifier_names - PigeonInstanceManager? pigeon_instanceManager, LensFacing? requireLensFacing, - CameraInfo? cameraInfoForFilter, + dynamic cameraInfoForFilter, }) proxyCreateCameraSelectorForFrontCamera = createCameraSelectorForBackCamera(mockBackCameraSelector); - camera.proxy = getProxyForCreatingTestCamera( + setUpOverridesForCreatingTestCamera( mockProcessCameraProvider: mockProcessCameraProvider, createCameraSelector: proxyCreateCameraSelectorForFrontCamera, getDefaultDisplayRotation: proxyGetDefaultDisplayRotation, diff --git a/packages/camera/camera_avfoundation/AUTHORS b/packages/camera/camera_avfoundation/AUTHORS index 493a0b4ef9c2..605414ab7dcf 100644 --- a/packages/camera/camera_avfoundation/AUTHORS +++ b/packages/camera/camera_avfoundation/AUTHORS @@ -64,3 +64,4 @@ Aleksandr Yurkovskiy Anton Borries Alex Li Rahul Raj <64.rahulraj@gmail.com> +Rui Craveiro diff --git a/packages/camera/camera_avfoundation/CHANGELOG.md b/packages/camera/camera_avfoundation/CHANGELOG.md index 25cda6a520c3..ca97b101df8b 100644 --- a/packages/camera/camera_avfoundation/CHANGELOG.md +++ b/packages/camera/camera_avfoundation/CHANGELOG.md @@ -1,3 +1,55 @@ +## 0.10.1 + +* Fixes fatal crash on iPhone 17 when using `ResolutionPreset.max`. + +## 0.10.0+3 + +* Switches to type-safe Pigeon code for image streaming. + +## 0.10.0+2 + +* Updates example to demonstrate correct exception handling for async return statements, ensuring exceptions thrown during return within try blocks are properly caught as per [dart-lang/sdk#44395](https://github.com/dart-lang/sdk/issues/44395). + +## 0.10.0+1 + +* Migrates to Swift-based pigeon interface. + +## 0.10.0 + +* Adds video stabilization. + - Adds getSupportedVideoStabilizationModes method. + - Adds setVideoStabilizationMode method. + +## 0.9.23+2 + +* Code refactor related to Swift pigeon's generated struct MediaSettings being immutable. + +## 0.9.23+1 + +* Fixes error handling in `startWriting`. + +## 0.9.23 + +* Changes the default storage path for camera pictures and videos on iOS from the application's Documents directory to the system's temporaryDirectory. + +## 0.9.22+10 + +* Handles video and audio interruptions and errors by "pausing" and reporting errors. +* Uses a single time offset for both video and audio to avoid desync. + +## 0.9.22+9 + +* Migrates `FLTSavePhotoDelegate`, `FLTWritableData`, and `FLTImageStreamHandler` classes to Swift. +* Migrates `CameraProperties` and `QueueUtils` helpers to Swift. + +## 0.9.22+8 + +* Migrates `FLTPermissionServicing` and `FLTCameraPermissionManager` classes to Swift. + +## 0.9.22+7 + +* Migrates `FLTCaptureConnection`, `FLTCaptureDeviceFormat` and `FLTAssetWriter` classes to Swift. + ## 0.9.22+6 * Updates to Pigeon 26. diff --git a/packages/camera/camera_avfoundation/example/.gitignore b/packages/camera/camera_avfoundation/example/.gitignore new file mode 100644 index 000000000000..3820a95c65c3 --- /dev/null +++ b/packages/camera/camera_avfoundation/example/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/packages/camera/camera_avfoundation/example/.metadata b/packages/camera/camera_avfoundation/example/.metadata new file mode 100644 index 000000000000..3e79a8d8a334 --- /dev/null +++ b/packages/camera/camera_avfoundation/example/.metadata @@ -0,0 +1,30 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "ff37bef603469fb030f2b72995ab929ccfc227f0" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + base_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + - platform: ios + create_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + base_revision: ff37bef603469fb030f2b72995ab929ccfc227f0 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/packages/camera/camera_avfoundation/example/integration_test/camera_test.dart b/packages/camera/camera_avfoundation/example/integration_test/camera_test.dart index 40d47fe293ea..bb48c3a01ca1 100644 --- a/packages/camera/camera_avfoundation/example/integration_test/camera_test.dart +++ b/packages/camera/camera_avfoundation/example/integration_test/camera_test.dart @@ -30,15 +30,14 @@ void main() { await testDir.delete(recursive: true); }); - final Map presetExpectedSizes = - { - ResolutionPreset.low: const Size(288, 352), - ResolutionPreset.medium: const Size(480, 640), - ResolutionPreset.high: const Size(720, 1280), - ResolutionPreset.veryHigh: const Size(1080, 1920), - ResolutionPreset.ultraHigh: const Size(2160, 3840), - // Don't bother checking for max here since it could be anything. - }; + final presetExpectedSizes = { + ResolutionPreset.low: const Size(288, 352), + ResolutionPreset.medium: const Size(480, 640), + ResolutionPreset.high: const Size(720, 1280), + ResolutionPreset.veryHigh: const Size(1080, 1920), + ResolutionPreset.ultraHigh: const Size(2160, 3840), + // Don't bother checking for max here since it could be anything. + }; /// Verify that [actual] has dimensions that are at least as large as /// [expectedSize]. Allows for a mismatch in portrait vs landscape. Returns @@ -63,7 +62,7 @@ void main() { final XFile file = await controller.takePicture(); // Load picture - final File fileImage = File(file.path); + final fileImage = File(file.path); final Image image = await decodeImageFromList(fileImage.readAsBytesSync()); // Verify image dimensions are as expected @@ -82,14 +81,11 @@ void main() { if (cameras.isEmpty) { return; } - for (final CameraDescription cameraDescription in cameras) { - bool previousPresetExactlySupported = true; + for (final cameraDescription in cameras) { + var previousPresetExactlySupported = true; for (final MapEntry preset in presetExpectedSizes.entries) { - final CameraController controller = CameraController( - cameraDescription, - preset.key, - ); + final controller = CameraController(cameraDescription, preset.key); await controller.initialize(); final bool presetExactlySupported = await testCaptureImageResolution( controller, @@ -120,10 +116,8 @@ void main() { final XFile file = await controller.stopVideoRecording(); // Load video metadata - final File videoFile = File(file.path); - final VideoPlayerController videoController = VideoPlayerController.file( - videoFile, - ); + final videoFile = File(file.path); + final videoController = VideoPlayerController.file(videoFile); await videoController.initialize(); final Size video = videoController.value.size; @@ -143,14 +137,11 @@ void main() { if (cameras.isEmpty) { return; } - for (final CameraDescription cameraDescription in cameras) { - bool previousPresetExactlySupported = true; + for (final cameraDescription in cameras) { + var previousPresetExactlySupported = true; for (final MapEntry preset in presetExpectedSizes.entries) { - final CameraController controller = CameraController( - cameraDescription, - preset.key, - ); + final controller = CameraController(cameraDescription, preset.key); await controller.initialize(); await controller.prepareForVideoRecording(); final bool presetExactlySupported = await testCaptureVideoResolution( @@ -174,7 +165,7 @@ void main() { return; } - final CameraController controller = CameraController( + final controller = CameraController( cameras[0], ResolutionPreset.low, enableAudio: false, @@ -184,7 +175,7 @@ void main() { await controller.prepareForVideoRecording(); int startPause; - int timePaused = 0; + var timePaused = 0; await controller.startVideoRecording(); final int recordingStart = DateTime.now().millisecondsSinceEpoch; @@ -210,10 +201,8 @@ void main() { final int recordingTime = DateTime.now().millisecondsSinceEpoch - recordingStart; - final File videoFile = File(file.path); - final VideoPlayerController videoController = VideoPlayerController.file( - videoFile, - ); + final videoFile = File(file.path); + final videoController = VideoPlayerController.file(videoFile); await videoController.initialize(); final int duration = videoController.value.duration.inMilliseconds; await videoController.dispose(); @@ -228,7 +217,7 @@ void main() { return; } - final CameraController controller = CameraController( + final controller = CameraController( cameras[0], ResolutionPreset.low, enableAudio: false, @@ -250,7 +239,7 @@ void main() { return; } - final CameraController controller = CameraController( + final controller = CameraController( cameras[0], ResolutionPreset.low, enableAudio: false, @@ -267,7 +256,7 @@ void main() { List cameras, ImageFormatGroup? imageFormatGroup, ) async { - final CameraController controller = CameraController( + final controller = CameraController( cameras.first, ResolutionPreset.low, enableAudio: false, @@ -275,7 +264,7 @@ void main() { ); await controller.initialize(); - final Completer completer = Completer(); + final completer = Completer(); await controller.startImageStream((CameraImageData image) { if (!completer.isCompleted) { @@ -322,7 +311,7 @@ void main() { return; } - final CameraController controller = CameraController( + final controller = CameraController( cameras[0], ResolutionPreset.low, enableAudio: false, @@ -330,7 +319,7 @@ void main() { await controller.initialize(); await controller.prepareForVideoRecording(); - final Completer completer = Completer(); + final completer = Completer(); await controller.startVideoRecording( streamCallback: (CameraImageData image) { if (!completer.isCompleted) { @@ -354,9 +343,9 @@ void main() { if (cameras.isEmpty) { return; } - for (final CameraDescription cameraDescription in cameras) { + for (final cameraDescription in cameras) { for (final ImageFileFormat fileFormat in ImageFileFormat.values) { - final CameraController controller = CameraController( + final controller = CameraController( cameraDescription, ResolutionPreset.low, ); @@ -377,9 +366,9 @@ void main() { return; } - final List lengths = []; - for (final int fps in [10, 30]) { - final CameraController controller = CameraController.withSettings( + final lengths = []; + for (final fps in [10, 30]) { + final controller = CameraController.withSettings( cameras.first, mediaSettings: MediaSettings( resolutionPreset: ResolutionPreset.medium, @@ -395,14 +384,14 @@ void main() { final XFile file = await controller.stopVideoRecording(); // Load video size - final File videoFile = File(file.path); + final videoFile = File(file.path); lengths.add(await videoFile.length()); await controller.dispose(); } - for (int n = 0; n < lengths.length - 1; n++) { + for (var n = 0; n < lengths.length - 1; n++) { expect( lengths[n], lessThan(lengths[n + 1]), @@ -418,10 +407,10 @@ void main() { return; } - const int kiloBits = 1024; - final List lengths = []; - for (final int videoBitrate in [100 * kiloBits, 1000 * kiloBits]) { - final CameraController controller = CameraController.withSettings( + const kiloBits = 1024; + final lengths = []; + for (final videoBitrate in [100 * kiloBits, 1000 * kiloBits]) { + final controller = CameraController.withSettings( cameras.first, mediaSettings: MediaSettings( resolutionPreset: ResolutionPreset.medium, @@ -437,14 +426,14 @@ void main() { final XFile file = await controller.stopVideoRecording(); // Load video size - final File videoFile = File(file.path); + final videoFile = File(file.path); lengths.add(await videoFile.length()); await controller.dispose(); } - for (int n = 0; n < lengths.length - 1; n++) { + for (var n = 0; n < lengths.length - 1; n++) { expect( lengths[n], lessThan(lengths[n + 1]), @@ -460,11 +449,11 @@ void main() { return; } - final List lengths = []; + final lengths = []; - const int kiloBits = 1024; - for (final int audioBitrate in [32 * kiloBits, 64 * kiloBits]) { - final CameraController controller = CameraController.withSettings( + const kiloBits = 1024; + for (final audioBitrate in [32 * kiloBits, 64 * kiloBits]) { + final controller = CameraController.withSettings( cameras.first, mediaSettings: MediaSettings( resolutionPreset: ResolutionPreset.low, @@ -483,7 +472,7 @@ void main() { final XFile file = await controller.stopVideoRecording(); // Load video metadata - final File videoFile = File(file.path); + final videoFile = File(file.path); final int length = await videoFile.length(); @@ -492,7 +481,7 @@ void main() { await controller.dispose(); } - for (int n = 0; n < lengths.length - 1; n++) { + for (var n = 0; n < lengths.length - 1; n++) { expect( lengths[n], lessThan(lengths[n + 1]), diff --git a/packages/camera/camera_avfoundation/example/ios/.gitignore b/packages/camera/camera_avfoundation/example/ios/.gitignore new file mode 100644 index 000000000000..7a7f9873ad7d --- /dev/null +++ b/packages/camera/camera_avfoundation/example/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/packages/camera/camera_avfoundation/example/ios/Flutter/AppFrameworkInfo.plist b/packages/camera/camera_avfoundation/example/ios/Flutter/AppFrameworkInfo.plist index 1f6b98f117b2..391a902b2beb 100644 --- a/packages/camera/camera_avfoundation/example/ios/Flutter/AppFrameworkInfo.plist +++ b/packages/camera/camera_avfoundation/example/ios/Flutter/AppFrameworkInfo.plist @@ -20,11 +20,5 @@ ???? CFBundleVersion 1.0 - UIRequiredDeviceCapabilities - - arm64 - - MinimumOSVersion - 13.0 diff --git a/packages/camera/camera_avfoundation/example/ios/Flutter/Debug.xcconfig b/packages/camera/camera_avfoundation/example/ios/Flutter/Debug.xcconfig index b2f5fae9c254..592ceee85b89 100644 --- a/packages/camera/camera_avfoundation/example/ios/Flutter/Debug.xcconfig +++ b/packages/camera/camera_avfoundation/example/ios/Flutter/Debug.xcconfig @@ -1,3 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" diff --git a/packages/camera/camera_avfoundation/example/ios/Flutter/Release.xcconfig b/packages/camera/camera_avfoundation/example/ios/Flutter/Release.xcconfig index 88c29144c836..592ceee85b89 100644 --- a/packages/camera/camera_avfoundation/example/ios/Flutter/Release.xcconfig +++ b/packages/camera/camera_avfoundation/example/ios/Flutter/Release.xcconfig @@ -1,3 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" diff --git a/packages/camera/camera_avfoundation/example/ios/Podfile b/packages/camera/camera_avfoundation/example/ios/Podfile deleted file mode 100644 index f64f36010b70..000000000000 --- a/packages/camera/camera_avfoundation/example/ios/Podfile +++ /dev/null @@ -1,42 +0,0 @@ -# Uncomment this line to define a global platform for your project -# platform :ios, '13.0' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_ios_podfile_setup - -target 'Runner' do - flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) - - target 'RunnerTests' do - inherit! :search_paths - end -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_ios_build_settings(target) - end -end diff --git a/packages/camera/camera_avfoundation/example/ios/Runner.xcodeproj/project.pbxproj b/packages/camera/camera_avfoundation/example/ios/Runner.xcodeproj/project.pbxproj index 8cf022f6ce07..94bbaa417925 100644 --- a/packages/camera/camera_avfoundation/example/ios/Runner.xcodeproj/project.pbxproj +++ b/packages/camera/camera_avfoundation/example/ios/Runner.xcodeproj/project.pbxproj @@ -7,66 +7,61 @@ objects = { /* Begin PBXBuildFile section */ - 1000364CB781922C6D6AAA4A /* libPods-RunnerTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 9DDC4CE84A8B378AE4A8CD9C /* libPods-RunnerTests.a */; }; 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 335A7B032F6B061D005902FE /* CameraZoomTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AE82F6B061D005902FE /* CameraZoomTests.swift */; }; + 335A7B042F6B061D005902FE /* AvailableCamerasTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AD72F6B061D005902FE /* AvailableCamerasTests.swift */; }; + 335A7B052F6B061D005902FE /* PhotoCaptureTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AFE2F6B061D005902FE /* PhotoCaptureTests.swift */; }; + 335A7B062F6B061D005902FE /* SavePhotoDelegateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7B012F6B061D005902FE /* SavePhotoDelegateTests.swift */; }; + 335A7B072F6B061D005902FE /* MockCameraDeviceDiscoverer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AED2F6B061D005902FE /* MockCameraDeviceDiscoverer.swift */; }; + 335A7B082F6B061D005902FE /* MockFlutterTextureRegistry.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AF92F6B061D005902FE /* MockFlutterTextureRegistry.swift */; }; + 335A7B092F6B061D005902FE /* QueueUtilsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AFF2F6B061D005902FE /* QueueUtilsTests.swift */; }; + 335A7B0A2F6B061D005902FE /* CameraPreviewPauseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7ADF2F6B061D005902FE /* CameraPreviewPauseTests.swift */; }; + 335A7B0B2F6B061D005902FE /* CameraPluginCreateCameraTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7ADC2F6B061D005902FE /* CameraPluginCreateCameraTests.swift */; }; + 335A7B0C2F6B061D005902FE /* MockCaptureDevice.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AEF2F6B061D005902FE /* MockCaptureDevice.swift */; }; + 335A7B0D2F6B061D005902FE /* MockWritableData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AFC2F6B061D005902FE /* MockWritableData.swift */; }; + 335A7B0E2F6B061D005902FE /* CameraOrientationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7ADA2F6B061D005902FE /* CameraOrientationTests.swift */; }; + 335A7B0F2F6B061D005902FE /* CameraSetFlashModeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AE72F6B061D005902FE /* CameraSetFlashModeTests.swift */; }; + 335A7B102F6B061D005902FE /* CameraSettingsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AE22F6B061D005902FE /* CameraSettingsTests.swift */; }; + 335A7B112F6B061D005902FE /* CameraExposureTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AE42F6B061D005902FE /* CameraExposureTests.swift */; }; + 335A7B122F6B061D005902FE /* CameraMethodChannelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AD92F6B061D005902FE /* CameraMethodChannelTests.swift */; }; + 335A7B132F6B061D005902FE /* MockGlobalEventApi.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AFB2F6B061D005902FE /* MockGlobalEventApi.swift */; }; + 335A7B142F6B061D005902FE /* MockAssetWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AE92F6B061D005902FE /* MockAssetWriter.swift */; }; + 335A7B152F6B061D005902FE /* MockCapturePhotoOutput.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AF32F6B061D005902FE /* MockCapturePhotoOutput.swift */; }; + 335A7B162F6B061D005902FE /* CameraSetFocusModeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AE52F6B061D005902FE /* CameraSetFocusModeTests.swift */; }; + 335A7B172F6B061D005902FE /* CameraPluginInitializeCameraTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7ADE2F6B061D005902FE /* CameraPluginInitializeCameraTests.swift */; }; + 335A7B182F6B061D005902FE /* CameraPluginDelegatingMethodTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7ADD2F6B061D005902FE /* CameraPluginDelegatingMethodTests.swift */; }; + 335A7B192F6B061D005902FE /* MockAssetWriterInput.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AEA2F6B061D005902FE /* MockAssetWriterInput.swift */; }; + 335A7B1A2F6B061D005902FE /* CameraTestUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AE32F6B061D005902FE /* CameraTestUtils.swift */; }; + 335A7B1B2F6B061D005902FE /* MockAssetWriterInputPixelBufferAdaptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AEB2F6B061D005902FE /* MockAssetWriterInputPixelBufferAdaptor.swift */; }; + 335A7B1C2F6B061D005902FE /* MockFrameRateRange.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AFA2F6B061D005902FE /* MockFrameRateRange.swift */; }; + 335A7B1D2F6B061D005902FE /* MockDeviceOrientationProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AF62F6B061D005902FE /* MockDeviceOrientationProvider.swift */; }; + 335A7B1E2F6B061D005902FE /* MockCaptureSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AF42F6B061D005902FE /* MockCaptureSession.swift */; }; + 335A7B1F2F6B061D005902FE /* CameraPermissionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7ADB2F6B061D005902FE /* CameraPermissionTests.swift */; }; + 335A7B202F6B061D005902FE /* MockCaptureDeviceInputFactory.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AF12F6B061D005902FE /* MockCaptureDeviceInputFactory.swift */; }; + 335A7B212F6B061D005902FE /* SampleBufferTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7B002F6B061D005902FE /* SampleBufferTests.swift */; }; + 335A7B222F6B061D005902FE /* MockCaptureInput.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AF22F6B061D005902FE /* MockCaptureInput.swift */; }; + 335A7B232F6B061D005902FE /* CameraSetDeviceOrientationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AE62F6B061D005902FE /* CameraSetDeviceOrientationTests.swift */; }; + 335A7B242F6B061D005902FE /* MockCamera.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AEC2F6B061D005902FE /* MockCamera.swift */; }; + 335A7B252F6B061D005902FE /* MockCaptureDeviceFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AF02F6B061D005902FE /* MockCaptureDeviceFormat.swift */; }; + 335A7B262F6B061D005902FE /* MockFLTCameraPermissionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AF72F6B061D005902FE /* MockFLTCameraPermissionManager.swift */; }; + 335A7B272F6B061D005902FE /* CameraPropertiesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AE02F6B061D005902FE /* CameraPropertiesTests.swift */; }; + 335A7B282F6B061D005902FE /* CameraSessionPresetsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AE12F6B061D005902FE /* CameraSessionPresetsTests.swift */; }; + 335A7B292F6B061D005902FE /* MockFlutterBinaryMessenger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AF82F6B061D005902FE /* MockFlutterBinaryMessenger.swift */; }; + 335A7B2A2F6B061D005902FE /* CameraInitRaceConditionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AD82F6B061D005902FE /* CameraInitRaceConditionsTests.swift */; }; + 335A7B2B2F6B061D005902FE /* MockCaptureConnection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AEE2F6B061D005902FE /* MockCaptureConnection.swift */; }; + 335A7B2C2F6B061D005902FE /* StreamingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7B022F6B061D005902FE /* StreamingTests.swift */; }; + 335A7B2D2F6B061D005902FE /* MockCaptureVideoDataOutput.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335A7AF52F6B061D005902FE /* MockCaptureVideoDataOutput.swift */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; - 54D650172516862D30686934 /* libPods-Runner.a in Frameworks */ = {isa = PBXBuildFile; fileRef = ECAF63F924EFA2D68883BA85 /* libPods-Runner.a */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; }; 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; - 970ADABE2D6740A900EFDCD9 /* MockWritableData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 970ADABD2D6740A900EFDCD9 /* MockWritableData.swift */; }; - 970ADAC02D6764CC00EFDCD9 /* MockEventChannel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 970ADABF2D6764CC00EFDCD9 /* MockEventChannel.swift */; }; - 972CA92B2D5A1D8C004B846F /* CameraPropertiesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 972CA92A2D5A1D8C004B846F /* CameraPropertiesTests.swift */; }; - 972CA92D2D5A28C4004B846F /* QueueUtilsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 972CA92C2D5A28C4004B846F /* QueueUtilsTests.swift */; }; - 977A25202D5A439300931E34 /* AvailableCamerasTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 977A251F2D5A439300931E34 /* AvailableCamerasTests.swift */; }; - 977A25222D5A49EC00931E34 /* FLTCamFocusTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 977A25212D5A49EC00931E34 /* FLTCamFocusTests.swift */; }; - 977A25242D5A511600931E34 /* CameraPermissionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 977A25232D5A511600931E34 /* CameraPermissionTests.swift */; }; - 977CAC9F2D5E5180001E5DC3 /* ThreadSafeEventChannelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 977CAC9E2D5E5180001E5DC3 /* ThreadSafeEventChannelTests.swift */; }; - 978296CF2D5F744B0009BDD3 /* PhotoCaptureTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 978296CE2D5F744B0009BDD3 /* PhotoCaptureTests.swift */; }; - 978B8F6F1D3862AE00F588F7 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */; }; - 978D90B42D5F630300CD817E /* StreamingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 978D90B32D5F630300CD817E /* StreamingTests.swift */; }; - 97922B0D2D6380C300A9B4CF /* SampleBufferTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 97922B0C2D6380C300A9B4CF /* SampleBufferTests.swift */; }; - 979B3DFB2D5B6BC7009BDE1A /* ExceptionCatcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 979B3DFA2D5B6BC7009BDE1A /* ExceptionCatcher.m */; }; - 979B3DFE2D5B985B009BDE1A /* CameraInitRaceConditionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 979B3DFD2D5B985B009BDE1A /* CameraInitRaceConditionsTests.swift */; }; - 979B3E002D5B9E6C009BDE1A /* CameraMethodChannelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 979B3DFF2D5B9E6C009BDE1A /* CameraMethodChannelTests.swift */; }; - 979B3E022D5BA48F009BDE1A /* CameraOrientationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 979B3E012D5BA48F009BDE1A /* CameraOrientationTests.swift */; }; - 97BD4A0E2D5CC5AE00F857D5 /* CameraSettingsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 97BD4A0D2D5CC5AE00F857D5 /* CameraSettingsTests.swift */; }; - 97BD4A102D5CE13500F857D5 /* CameraSessionPresetsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 97BD4A0F2D5CE13500F857D5 /* CameraSessionPresetsTests.swift */; }; - 97C0FFAE2D5E023200A36284 /* SavePhotoDelegateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 97C0FFAD2D5E023200A36284 /* SavePhotoDelegateTests.swift */; }; - 97C146F31CF9000F007C117D /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 97C146F21CF9000F007C117D /* main.m */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; - 97DB234D2D566D0700CEFE66 /* CameraPreviewPauseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 97DB234C2D566D0700CEFE66 /* CameraPreviewPauseTests.swift */; }; - E11D6A8F2D81B81D0031E6C5 /* MockCaptureVideoDataOutput.swift in Sources */ = {isa = PBXBuildFile; fileRef = E11D6A8E2D81B81D0031E6C5 /* MockCaptureVideoDataOutput.swift */; }; - E11D6A912D82C7740031E6C5 /* FLTCamExposureTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E11D6A902D82C7740031E6C5 /* FLTCamExposureTests.swift */; }; - E12C4FF62D68C69000515E70 /* CameraPluginDelegatingMethodTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E12C4FF52D68C69000515E70 /* CameraPluginDelegatingMethodTests.swift */; }; - E12C4FF82D68E85500515E70 /* MockFLTCameraPermissionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = E12C4FF72D68E85500515E70 /* MockFLTCameraPermissionManager.swift */; }; - E142681D2D8483FD0046CBBC /* MockCaptureSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = E142681C2D8483FD0046CBBC /* MockCaptureSession.swift */; }; - E142681F2D8566230046CBBC /* CameraTestUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = E142681E2D8566230046CBBC /* CameraTestUtils.swift */; }; - E142F1362D8587F900824824 /* MockCameraDeviceDiscoverer.swift in Sources */ = {isa = PBXBuildFile; fileRef = E142F1352D8587F900824824 /* MockCameraDeviceDiscoverer.swift */; }; - E142F1382D85919700824824 /* MockDeviceOrientationProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = E142F1372D85919700824824 /* MockDeviceOrientationProvider.swift */; }; - E142F13A2D85940600824824 /* MockCapturePhotoOutput.swift in Sources */ = {isa = PBXBuildFile; fileRef = E142F1392D85940600824824 /* MockCapturePhotoOutput.swift */; }; - E142F13C2D8596F100824824 /* MockCaptureDeviceFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = E142F13B2D8596F100824824 /* MockCaptureDeviceFormat.swift */; }; - E142F13E2D859ADC00824824 /* MockFrameRateRange.swift in Sources */ = {isa = PBXBuildFile; fileRef = E142F13D2D859ADC00824824 /* MockFrameRateRange.swift */; }; - E142F1402D85AD7900824824 /* MockCaptureConnection.swift in Sources */ = {isa = PBXBuildFile; fileRef = E142F13F2D85AD7900824824 /* MockCaptureConnection.swift */; }; - E142F1422D85AFA400824824 /* MockGlobalEventApi.swift in Sources */ = {isa = PBXBuildFile; fileRef = E142F1412D85AFA400824824 /* MockGlobalEventApi.swift */; }; - E15139182D80980900FEE47B /* FLTCamSetDeviceOrientationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E15139172D80980900FEE47B /* FLTCamSetDeviceOrientationTests.swift */; }; - E15BC7E42D86D08700F66474 /* MockFlutterTextureRegistry.swift in Sources */ = {isa = PBXBuildFile; fileRef = E15BC7E32D86D08700F66474 /* MockFlutterTextureRegistry.swift */; }; - E15BC7E62D86D17D00F66474 /* MockFlutterBinaryMessenger.swift in Sources */ = {isa = PBXBuildFile; fileRef = E15BC7E52D86D17D00F66474 /* MockFlutterBinaryMessenger.swift */; }; - E16602952D8471C0003CFE12 /* FLTCamZoomTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E16602942D8471C0003CFE12 /* FLTCamZoomTests.swift */; }; - E1A5F4E32D80259C0005BA64 /* FLTCamSetFlashModeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1A5F4E22D80259C0005BA64 /* FLTCamSetFlashModeTests.swift */; }; - E1ABED6C2D94392500AED9CC /* MockAssetWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = E15BC7E72D86D29F00F66474 /* MockAssetWriter.swift */; }; - E1ABED6D2D94392700AED9CC /* MockAssetWriterInput.swift in Sources */ = {isa = PBXBuildFile; fileRef = E15BC7E92D86D41F00F66474 /* MockAssetWriterInput.swift */; }; - E1ABED6E2D94392900AED9CC /* MockAssetWriterInputPixelBufferAdaptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = E15BC7EB2D86D50200F66474 /* MockAssetWriterInputPixelBufferAdaptor.swift */; }; - E1ABED6F2D943B2500AED9CC /* MockCaptureDevice.swift in Sources */ = {isa = PBXBuildFile; fileRef = E15BC7ED2D86D85500F66474 /* MockCaptureDevice.swift */; }; - E1ABED722D943DC700AED9CC /* MockCaptureDeviceInputFactory.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1ABED702D943DC700AED9CC /* MockCaptureDeviceInputFactory.swift */; }; - E1ABED732D943DC700AED9CC /* MockCaptureInput.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1ABED712D943DC700AED9CC /* MockCaptureInput.swift */; }; - E1FFEAAD2D6C8DD700B14107 /* MockCamera.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1FFEAAC2D6C8DD700B14107 /* MockCamera.swift */; }; - E1FFEAAF2D6CDA8C00B14107 /* CameraPluginCreateCameraTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1FFEAAE2D6CDA8C00B14107 /* CameraPluginCreateCameraTests.swift */; }; - E1FFEAB12D6CDE5B00B14107 /* CameraPluginInitializeCameraTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1FFEAB02D6CDE5B00B14107 /* CameraPluginInitializeCameraTests.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ - 03BB766D2665316900CE5A93 /* PBXContainerItemProxy */ = { + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 97C146E61CF9000F007C117D /* Project object */; proxyType = 1; @@ -89,168 +84,133 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 03BB76682665316900CE5A93 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 03BB766C2665316900CE5A93 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 335A7AD72F6B061D005902FE /* AvailableCamerasTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AvailableCamerasTests.swift; sourceTree = ""; }; + 335A7AD82F6B061D005902FE /* CameraInitRaceConditionsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraInitRaceConditionsTests.swift; sourceTree = ""; }; + 335A7AD92F6B061D005902FE /* CameraMethodChannelTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraMethodChannelTests.swift; sourceTree = ""; }; + 335A7ADA2F6B061D005902FE /* CameraOrientationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraOrientationTests.swift; sourceTree = ""; }; + 335A7ADB2F6B061D005902FE /* CameraPermissionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraPermissionTests.swift; sourceTree = ""; }; + 335A7ADC2F6B061D005902FE /* CameraPluginCreateCameraTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraPluginCreateCameraTests.swift; sourceTree = ""; }; + 335A7ADD2F6B061D005902FE /* CameraPluginDelegatingMethodTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraPluginDelegatingMethodTests.swift; sourceTree = ""; }; + 335A7ADE2F6B061D005902FE /* CameraPluginInitializeCameraTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraPluginInitializeCameraTests.swift; sourceTree = ""; }; + 335A7ADF2F6B061D005902FE /* CameraPreviewPauseTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraPreviewPauseTests.swift; sourceTree = ""; }; + 335A7AE02F6B061D005902FE /* CameraPropertiesTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraPropertiesTests.swift; sourceTree = ""; }; + 335A7AE12F6B061D005902FE /* CameraSessionPresetsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraSessionPresetsTests.swift; sourceTree = ""; }; + 335A7AE22F6B061D005902FE /* CameraSettingsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraSettingsTests.swift; sourceTree = ""; }; + 335A7AE32F6B061D005902FE /* CameraTestUtils.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraTestUtils.swift; sourceTree = ""; }; + 335A7AE42F6B061D005902FE /* CameraExposureTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraExposureTests.swift; sourceTree = ""; }; + 335A7AE52F6B061D005902FE /* CameraSetFocusModeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraSetFocusModeTests.swift; sourceTree = ""; }; + 335A7AE62F6B061D005902FE /* CameraSetDeviceOrientationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraSetDeviceOrientationTests.swift; sourceTree = ""; }; + 335A7AE72F6B061D005902FE /* CameraSetFlashModeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraSetFlashModeTests.swift; sourceTree = ""; }; + 335A7AE82F6B061D005902FE /* CameraZoomTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraZoomTests.swift; sourceTree = ""; }; + 335A7AE92F6B061D005902FE /* MockAssetWriter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockAssetWriter.swift; sourceTree = ""; }; + 335A7AEA2F6B061D005902FE /* MockAssetWriterInput.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockAssetWriterInput.swift; sourceTree = ""; }; + 335A7AEB2F6B061D005902FE /* MockAssetWriterInputPixelBufferAdaptor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockAssetWriterInputPixelBufferAdaptor.swift; sourceTree = ""; }; + 335A7AEC2F6B061D005902FE /* MockCamera.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockCamera.swift; sourceTree = ""; }; + 335A7AED2F6B061D005902FE /* MockCameraDeviceDiscoverer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockCameraDeviceDiscoverer.swift; sourceTree = ""; }; + 335A7AEE2F6B061D005902FE /* MockCaptureConnection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockCaptureConnection.swift; sourceTree = ""; }; + 335A7AEF2F6B061D005902FE /* MockCaptureDevice.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockCaptureDevice.swift; sourceTree = ""; }; + 335A7AF02F6B061D005902FE /* MockCaptureDeviceFormat.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockCaptureDeviceFormat.swift; sourceTree = ""; }; + 335A7AF12F6B061D005902FE /* MockCaptureDeviceInputFactory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockCaptureDeviceInputFactory.swift; sourceTree = ""; }; + 335A7AF22F6B061D005902FE /* MockCaptureInput.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockCaptureInput.swift; sourceTree = ""; }; + 335A7AF32F6B061D005902FE /* MockCapturePhotoOutput.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockCapturePhotoOutput.swift; sourceTree = ""; }; + 335A7AF42F6B061D005902FE /* MockCaptureSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockCaptureSession.swift; sourceTree = ""; }; + 335A7AF52F6B061D005902FE /* MockCaptureVideoDataOutput.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockCaptureVideoDataOutput.swift; sourceTree = ""; }; + 335A7AF62F6B061D005902FE /* MockDeviceOrientationProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockDeviceOrientationProvider.swift; sourceTree = ""; }; + 335A7AF72F6B061D005902FE /* MockFLTCameraPermissionManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockFLTCameraPermissionManager.swift; sourceTree = ""; }; + 335A7AF82F6B061D005902FE /* MockFlutterBinaryMessenger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockFlutterBinaryMessenger.swift; sourceTree = ""; }; + 335A7AF92F6B061D005902FE /* MockFlutterTextureRegistry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockFlutterTextureRegistry.swift; sourceTree = ""; }; + 335A7AFA2F6B061D005902FE /* MockFrameRateRange.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockFrameRateRange.swift; sourceTree = ""; }; + 335A7AFB2F6B061D005902FE /* MockGlobalEventApi.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockGlobalEventApi.swift; sourceTree = ""; }; + 335A7AFC2F6B061D005902FE /* MockWritableData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockWritableData.swift; sourceTree = ""; }; + 335A7AFE2F6B061D005902FE /* PhotoCaptureTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PhotoCaptureTests.swift; sourceTree = ""; }; + 335A7AFF2F6B061D005902FE /* QueueUtilsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QueueUtilsTests.swift; sourceTree = ""; }; + 335A7B002F6B061D005902FE /* SampleBufferTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SampleBufferTests.swift; sourceTree = ""; }; + 335A7B012F6B061D005902FE /* SavePhotoDelegateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SavePhotoDelegateTests.swift; sourceTree = ""; }; + 335A7B022F6B061D005902FE /* StreamingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StreamingTests.swift; sourceTree = ""; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; - 4A191381C3593DF1AC4E7559 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; - 7AFFD8ED1D35381100E5BB4D /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; - 7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; - 970ADABD2D6740A900EFDCD9 /* MockWritableData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockWritableData.swift; sourceTree = ""; }; - 970ADABF2D6764CC00EFDCD9 /* MockEventChannel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockEventChannel.swift; sourceTree = ""; }; - 972CA92A2D5A1D8C004B846F /* CameraPropertiesTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraPropertiesTests.swift; sourceTree = ""; }; - 972CA92C2D5A28C4004B846F /* QueueUtilsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QueueUtilsTests.swift; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; - 977A251F2D5A439300931E34 /* AvailableCamerasTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AvailableCamerasTests.swift; sourceTree = ""; }; - 977A25212D5A49EC00931E34 /* FLTCamFocusTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FLTCamFocusTests.swift; sourceTree = ""; }; - 977A25232D5A511600931E34 /* CameraPermissionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraPermissionTests.swift; sourceTree = ""; }; - 977CAC9E2D5E5180001E5DC3 /* ThreadSafeEventChannelTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ThreadSafeEventChannelTests.swift; sourceTree = ""; }; - 978296CE2D5F744B0009BDD3 /* PhotoCaptureTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PhotoCaptureTests.swift; sourceTree = ""; }; - 978D90B32D5F630300CD817E /* StreamingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StreamingTests.swift; sourceTree = ""; }; - 97922B0C2D6380C300A9B4CF /* SampleBufferTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SampleBufferTests.swift; sourceTree = ""; }; - 979B3DF92D5B6BA2009BDE1A /* ExceptionCatcher.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ExceptionCatcher.h; sourceTree = ""; }; - 979B3DFA2D5B6BC7009BDE1A /* ExceptionCatcher.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ExceptionCatcher.m; sourceTree = ""; }; - 979B3DFC2D5B985B009BDE1A /* RunnerTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "RunnerTests-Bridging-Header.h"; sourceTree = ""; }; - 979B3DFD2D5B985B009BDE1A /* CameraInitRaceConditionsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraInitRaceConditionsTests.swift; sourceTree = ""; }; - 979B3DFF2D5B9E6C009BDE1A /* CameraMethodChannelTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraMethodChannelTests.swift; sourceTree = ""; }; - 979B3E012D5BA48F009BDE1A /* CameraOrientationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraOrientationTests.swift; sourceTree = ""; }; - 97BD4A0D2D5CC5AE00F857D5 /* CameraSettingsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraSettingsTests.swift; sourceTree = ""; }; - 97BD4A0F2D5CE13500F857D5 /* CameraSessionPresetsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraSessionPresetsTests.swift; sourceTree = ""; }; - 97C0FFAD2D5E023200A36284 /* SavePhotoDelegateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SavePhotoDelegateTests.swift; sourceTree = ""; }; 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 97C146F21CF9000F007C117D /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 97DB234C2D566D0700CEFE66 /* CameraPreviewPauseTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraPreviewPauseTests.swift; sourceTree = ""; }; - 9DDC4CE84A8B378AE4A8CD9C /* libPods-RunnerTests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-RunnerTests.a"; sourceTree = BUILT_PRODUCTS_DIR; }; - A8F314CD1C64E9257EBC811D /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; - B61D98BBC8FB276D1C4A7BB2 /* 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 = ""; }; - E11D6A8E2D81B81D0031E6C5 /* MockCaptureVideoDataOutput.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockCaptureVideoDataOutput.swift; sourceTree = ""; }; - E11D6A902D82C7740031E6C5 /* FLTCamExposureTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FLTCamExposureTests.swift; sourceTree = ""; }; - E12C4FF52D68C69000515E70 /* CameraPluginDelegatingMethodTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraPluginDelegatingMethodTests.swift; sourceTree = ""; }; - E12C4FF72D68E85500515E70 /* MockFLTCameraPermissionManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockFLTCameraPermissionManager.swift; sourceTree = ""; }; - E142681C2D8483FD0046CBBC /* MockCaptureSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockCaptureSession.swift; sourceTree = ""; }; - E142681E2D8566230046CBBC /* CameraTestUtils.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraTestUtils.swift; sourceTree = ""; }; - E142F1352D8587F900824824 /* MockCameraDeviceDiscoverer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockCameraDeviceDiscoverer.swift; sourceTree = ""; }; - E142F1372D85919700824824 /* MockDeviceOrientationProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockDeviceOrientationProvider.swift; sourceTree = ""; }; - E142F1392D85940600824824 /* MockCapturePhotoOutput.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockCapturePhotoOutput.swift; sourceTree = ""; }; - E142F13B2D8596F100824824 /* MockCaptureDeviceFormat.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockCaptureDeviceFormat.swift; sourceTree = ""; }; - E142F13D2D859ADC00824824 /* MockFrameRateRange.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockFrameRateRange.swift; sourceTree = ""; }; - E142F13F2D85AD7900824824 /* MockCaptureConnection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockCaptureConnection.swift; sourceTree = ""; }; - E142F1412D85AFA400824824 /* MockGlobalEventApi.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockGlobalEventApi.swift; sourceTree = ""; }; - E15139172D80980900FEE47B /* FLTCamSetDeviceOrientationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FLTCamSetDeviceOrientationTests.swift; sourceTree = ""; }; - E15BC7E32D86D08700F66474 /* MockFlutterTextureRegistry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockFlutterTextureRegistry.swift; sourceTree = ""; }; - E15BC7E52D86D17D00F66474 /* MockFlutterBinaryMessenger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockFlutterBinaryMessenger.swift; sourceTree = ""; }; - E15BC7E72D86D29F00F66474 /* MockAssetWriter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockAssetWriter.swift; sourceTree = ""; }; - E15BC7E92D86D41F00F66474 /* MockAssetWriterInput.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockAssetWriterInput.swift; sourceTree = ""; }; - E15BC7EB2D86D50200F66474 /* MockAssetWriterInputPixelBufferAdaptor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockAssetWriterInputPixelBufferAdaptor.swift; sourceTree = ""; }; - E15BC7ED2D86D85500F66474 /* MockCaptureDevice.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockCaptureDevice.swift; sourceTree = ""; }; - E16602942D8471C0003CFE12 /* FLTCamZoomTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FLTCamZoomTests.swift; sourceTree = ""; }; - E1A5F4E22D80259C0005BA64 /* FLTCamSetFlashModeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FLTCamSetFlashModeTests.swift; sourceTree = ""; }; - E1ABED702D943DC700AED9CC /* MockCaptureDeviceInputFactory.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MockCaptureDeviceInputFactory.swift; sourceTree = ""; }; - E1ABED712D943DC700AED9CC /* MockCaptureInput.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MockCaptureInput.swift; sourceTree = ""; }; - E1FFEAAC2D6C8DD700B14107 /* MockCamera.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockCamera.swift; sourceTree = ""; }; - E1FFEAAE2D6CDA8C00B14107 /* CameraPluginCreateCameraTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraPluginCreateCameraTests.swift; sourceTree = ""; }; - E1FFEAB02D6CDE5B00B14107 /* CameraPluginInitializeCameraTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CameraPluginInitializeCameraTests.swift; sourceTree = ""; }; - E67C6DBF6478BE708993169F /* 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 = ""; }; - ECAF63F924EFA2D68883BA85 /* libPods-Runner.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-Runner.a"; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ - 03BB76652665316900CE5A93 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 1000364CB781922C6D6AAA4A /* libPods-RunnerTests.a in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; 97C146EB1CF9000F007C117D /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, - 54D650172516862D30686934 /* libPods-Runner.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 03BB76692665316900CE5A93 /* RunnerTests */ = { + 331C8082294A63A400263BE5 /* RunnerTests */ = { isa = PBXGroup; children = ( - 7F29EB3F2D281C6D00740257 /* Mocks */, - 03BB766C2665316900CE5A93 /* Info.plist */, - E142681E2D8566230046CBBC /* CameraTestUtils.swift */, - 979B3DF92D5B6BA2009BDE1A /* ExceptionCatcher.h */, - 979B3DFA2D5B6BC7009BDE1A /* ExceptionCatcher.m */, - 979B3DFC2D5B985B009BDE1A /* RunnerTests-Bridging-Header.h */, - 979B3DFD2D5B985B009BDE1A /* CameraInitRaceConditionsTests.swift */, - 979B3DFF2D5B9E6C009BDE1A /* CameraMethodChannelTests.swift */, - 979B3E012D5BA48F009BDE1A /* CameraOrientationTests.swift */, - 97BD4A0D2D5CC5AE00F857D5 /* CameraSettingsTests.swift */, - 97BD4A0F2D5CE13500F857D5 /* CameraSessionPresetsTests.swift */, - 97DB234C2D566D0700CEFE66 /* CameraPreviewPauseTests.swift */, - 972CA92A2D5A1D8C004B846F /* CameraPropertiesTests.swift */, - 972CA92C2D5A28C4004B846F /* QueueUtilsTests.swift */, - 977A251F2D5A439300931E34 /* AvailableCamerasTests.swift */, - 977A25232D5A511600931E34 /* CameraPermissionTests.swift */, - 97C0FFAD2D5E023200A36284 /* SavePhotoDelegateTests.swift */, - 977CAC9E2D5E5180001E5DC3 /* ThreadSafeEventChannelTests.swift */, - 978D90B32D5F630300CD817E /* StreamingTests.swift */, - 97922B0C2D6380C300A9B4CF /* SampleBufferTests.swift */, - 978296CE2D5F744B0009BDD3 /* PhotoCaptureTests.swift */, - E12C4FF52D68C69000515E70 /* CameraPluginDelegatingMethodTests.swift */, - E1FFEAAE2D6CDA8C00B14107 /* CameraPluginCreateCameraTests.swift */, - E1FFEAB02D6CDE5B00B14107 /* CameraPluginInitializeCameraTests.swift */, - E11D6A902D82C7740031E6C5 /* FLTCamExposureTests.swift */, - 977A25212D5A49EC00931E34 /* FLTCamFocusTests.swift */, - E1A5F4E22D80259C0005BA64 /* FLTCamSetFlashModeTests.swift */, - E16602942D8471C0003CFE12 /* FLTCamZoomTests.swift */, - E15139172D80980900FEE47B /* FLTCamSetDeviceOrientationTests.swift */, + 335A7AD72F6B061D005902FE /* AvailableCamerasTests.swift */, + 335A7AE42F6B061D005902FE /* CameraExposureTests.swift */, + 335A7AD82F6B061D005902FE /* CameraInitRaceConditionsTests.swift */, + 335A7AE52F6B061D005902FE /* CameraSetFocusModeTests.swift */, + 335A7AD92F6B061D005902FE /* CameraMethodChannelTests.swift */, + 335A7ADA2F6B061D005902FE /* CameraOrientationTests.swift */, + 335A7ADB2F6B061D005902FE /* CameraPermissionTests.swift */, + 335A7ADC2F6B061D005902FE /* CameraPluginCreateCameraTests.swift */, + 335A7ADD2F6B061D005902FE /* CameraPluginDelegatingMethodTests.swift */, + 335A7ADE2F6B061D005902FE /* CameraPluginInitializeCameraTests.swift */, + 335A7ADF2F6B061D005902FE /* CameraPreviewPauseTests.swift */, + 335A7AE02F6B061D005902FE /* CameraPropertiesTests.swift */, + 335A7AE12F6B061D005902FE /* CameraSessionPresetsTests.swift */, + 335A7AE62F6B061D005902FE /* CameraSetDeviceOrientationTests.swift */, + 335A7AE72F6B061D005902FE /* CameraSetFlashModeTests.swift */, + 335A7AE22F6B061D005902FE /* CameraSettingsTests.swift */, + 335A7AE32F6B061D005902FE /* CameraTestUtils.swift */, + 335A7AE82F6B061D005902FE /* CameraZoomTests.swift */, + 335A7AFE2F6B061D005902FE /* PhotoCaptureTests.swift */, + 335A7AFF2F6B061D005902FE /* QueueUtilsTests.swift */, + 335A7B002F6B061D005902FE /* SampleBufferTests.swift */, + 335A7B012F6B061D005902FE /* SavePhotoDelegateTests.swift */, + 335A7B022F6B061D005902FE /* StreamingTests.swift */, + 335A7AFD2F6B061D005902FE /* Mocks */, ); path = RunnerTests; sourceTree = ""; }; - 3242FD2B467C15C62200632F /* Frameworks */ = { + 335A7AFD2F6B061D005902FE /* Mocks */ = { isa = PBXGroup; children = ( - ECAF63F924EFA2D68883BA85 /* libPods-Runner.a */, - 9DDC4CE84A8B378AE4A8CD9C /* libPods-RunnerTests.a */, - ); - name = Frameworks; - sourceTree = ""; - }; - 7F29EB3F2D281C6D00740257 /* Mocks */ = { - isa = PBXGroup; - children = ( - E15BC7E72D86D29F00F66474 /* MockAssetWriter.swift */, - E15BC7E92D86D41F00F66474 /* MockAssetWriterInput.swift */, - E15BC7EB2D86D50200F66474 /* MockAssetWriterInputPixelBufferAdaptor.swift */, - E15BC7E52D86D17D00F66474 /* MockFlutterBinaryMessenger.swift */, - E15BC7E32D86D08700F66474 /* MockFlutterTextureRegistry.swift */, - E142F1412D85AFA400824824 /* MockGlobalEventApi.swift */, - E15BC7ED2D86D85500F66474 /* MockCaptureDevice.swift */, - E1ABED702D943DC700AED9CC /* MockCaptureDeviceInputFactory.swift */, - E1ABED712D943DC700AED9CC /* MockCaptureInput.swift */, - E142F13F2D85AD7900824824 /* MockCaptureConnection.swift */, - E142F13B2D8596F100824824 /* MockCaptureDeviceFormat.swift */, - E142F13D2D859ADC00824824 /* MockFrameRateRange.swift */, - E142F1392D85940600824824 /* MockCapturePhotoOutput.swift */, - E142F1372D85919700824824 /* MockDeviceOrientationProvider.swift */, - E142F1352D8587F900824824 /* MockCameraDeviceDiscoverer.swift */, - E1FFEAAC2D6C8DD700B14107 /* MockCamera.swift */, - 970ADABF2D6764CC00EFDCD9 /* MockEventChannel.swift */, - E12C4FF72D68E85500515E70 /* MockFLTCameraPermissionManager.swift */, - 970ADABD2D6740A900EFDCD9 /* MockWritableData.swift */, - E11D6A8E2D81B81D0031E6C5 /* MockCaptureVideoDataOutput.swift */, - E142681C2D8483FD0046CBBC /* MockCaptureSession.swift */, + 335A7AE92F6B061D005902FE /* MockAssetWriter.swift */, + 335A7AEA2F6B061D005902FE /* MockAssetWriterInput.swift */, + 335A7AEB2F6B061D005902FE /* MockAssetWriterInputPixelBufferAdaptor.swift */, + 335A7AEC2F6B061D005902FE /* MockCamera.swift */, + 335A7AED2F6B061D005902FE /* MockCameraDeviceDiscoverer.swift */, + 335A7AEE2F6B061D005902FE /* MockCaptureConnection.swift */, + 335A7AEF2F6B061D005902FE /* MockCaptureDevice.swift */, + 335A7AF02F6B061D005902FE /* MockCaptureDeviceFormat.swift */, + 335A7AF12F6B061D005902FE /* MockCaptureDeviceInputFactory.swift */, + 335A7AF22F6B061D005902FE /* MockCaptureInput.swift */, + 335A7AF32F6B061D005902FE /* MockCapturePhotoOutput.swift */, + 335A7AF42F6B061D005902FE /* MockCaptureSession.swift */, + 335A7AF52F6B061D005902FE /* MockCaptureVideoDataOutput.swift */, + 335A7AF62F6B061D005902FE /* MockDeviceOrientationProvider.swift */, + 335A7AF72F6B061D005902FE /* MockFLTCameraPermissionManager.swift */, + 335A7AF82F6B061D005902FE /* MockFlutterBinaryMessenger.swift */, + 335A7AF92F6B061D005902FE /* MockFlutterTextureRegistry.swift */, + 335A7AFA2F6B061D005902FE /* MockFrameRateRange.swift */, + 335A7AFB2F6B061D005902FE /* MockGlobalEventApi.swift */, + 335A7AFC2F6B061D005902FE /* MockWritableData.swift */, ); path = Mocks; sourceTree = ""; @@ -258,6 +218,7 @@ 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, 9740EEB21CF90195004384FC /* Debug.xcconfig */, 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, @@ -271,10 +232,8 @@ children = ( 9740EEB11CF90186004384FC /* Flutter */, 97C146F01CF9000F007C117D /* Runner */, - 03BB76692665316900CE5A93 /* RunnerTests */, 97C146EF1CF9000F007C117D /* Products */, - FD386F00E98D73419C929072 /* Pods */, - 3242FD2B467C15C62200632F /* Frameworks */, + 331C8082294A63A400263BE5 /* RunnerTests */, ); sourceTree = ""; }; @@ -282,7 +241,7 @@ isa = PBXGroup; children = ( 97C146EE1CF9000F007C117D /* Runner.app */, - 03BB76682665316900CE5A93 /* RunnerTests.xctest */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, ); name = Products; sourceTree = ""; @@ -290,74 +249,49 @@ 97C146F01CF9000F007C117D /* Runner */ = { isa = PBXGroup; children = ( - 7AFFD8ED1D35381100E5BB4D /* AppDelegate.h */, - 7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */, 97C146FA1CF9000F007C117D /* Main.storyboard */, 97C146FD1CF9000F007C117D /* Assets.xcassets */, 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, 97C147021CF9000F007C117D /* Info.plist */, - 97C146F11CF9000F007C117D /* Supporting Files */, 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, ); path = Runner; sourceTree = ""; }; - 97C146F11CF9000F007C117D /* Supporting Files */ = { - isa = PBXGroup; - children = ( - 97C146F21CF9000F007C117D /* main.m */, - ); - name = "Supporting Files"; - sourceTree = ""; - }; - FD386F00E98D73419C929072 /* Pods */ = { - isa = PBXGroup; - children = ( - A8F314CD1C64E9257EBC811D /* Pods-Runner.debug.xcconfig */, - 4A191381C3593DF1AC4E7559 /* Pods-Runner.release.xcconfig */, - B61D98BBC8FB276D1C4A7BB2 /* Pods-RunnerTests.debug.xcconfig */, - E67C6DBF6478BE708993169F /* Pods-RunnerTests.release.xcconfig */, - ); - path = Pods; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ - 03BB76672665316900CE5A93 /* RunnerTests */ = { + 331C8080294A63A400263BE5 /* RunnerTests */ = { isa = PBXNativeTarget; - buildConfigurationList = 03BB76712665316900CE5A93 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; buildPhases = ( - 422786A96136AA9087A2041B /* [CP] Check Pods Manifest.lock */, - 03BB76642665316900CE5A93 /* Sources */, - 03BB76652665316900CE5A93 /* Frameworks */, - 03BB76662665316900CE5A93 /* Resources */, + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, ); buildRules = ( ); dependencies = ( - 03BB766E2665316900CE5A93 /* PBXTargetDependency */, + 331C8086294A63A400263BE5 /* PBXTargetDependency */, ); name = RunnerTests; - packageProductDependencies = ( - ); - productName = camera_exampleTests; - productReference = 03BB76682665316900CE5A93 /* RunnerTests.xctest */; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; productType = "com.apple.product-type.bundle.unit-test"; }; 97C146ED1CF9000F007C117D /* Runner */ = { isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - 9872F2A25E8A171A111468CD /* [CP] Check Pods Manifest.lock */, 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, 97C146EC1CF9000F007C117D /* Resources */, 9705A1C41CF9048500538489 /* Embed Frameworks */, 3B06AD1E1E4923F5004D2608 /* Thin Binary */, - 2B62C73988DE02487EF557D4 /* [CP] Copy Pods Resources */, ); buildRules = ( ); @@ -377,22 +311,22 @@ 97C146E61CF9000F007C117D /* Project object */ = { isa = PBXProject; attributes = { + BuildIndependentTargetsInParallel = YES; LastUpgradeCheck = 1510; - ORGANIZATIONNAME = "The Flutter Authors"; + ORGANIZATIONNAME = ""; TargetAttributes = { - 03BB76672665316900CE5A93 = { - CreatedOnToolsVersion = 12.5; - LastSwiftMigration = 1540; - ProvisioningStyle = Automatic; + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; TestTargetID = 97C146ED1CF9000F007C117D; }; 97C146ED1CF9000F007C117D = { CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; }; }; }; buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; - compatibilityVersion = "Xcode 3.2"; + compatibilityVersion = "Xcode 9.3"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( @@ -408,13 +342,13 @@ projectRoot = ""; targets = ( 97C146ED1CF9000F007C117D /* Runner */, - 03BB76672665316900CE5A93 /* RunnerTests */, + 331C8080294A63A400263BE5 /* RunnerTests */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ - 03BB76662665316900CE5A93 /* Resources */ = { + 331C807F294A63A400263BE5 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( @@ -435,28 +369,6 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 2B62C73988DE02487EF557D4 /* [CP] Copy Pods Resources */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources.sh", - "${PODS_CONFIGURATION_BUILD_DIR}/camera_avfoundation/camera_avfoundation_privacy.bundle", - "${PODS_CONFIGURATION_BUILD_DIR}/path_provider_foundation/path_provider_foundation_privacy.bundle", - "${PODS_CONFIGURATION_BUILD_DIR}/video_player_avfoundation/video_player_avfoundation_privacy.bundle", - ); - name = "[CP] Copy Pods Resources"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/camera_avfoundation_privacy.bundle", - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/path_provider_foundation_privacy.bundle", - "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/video_player_avfoundation_privacy.bundle", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-resources.sh\"\n"; - showEnvVarsInLog = 0; - }; 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; @@ -473,28 +385,6 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; }; - 422786A96136AA9087A2041B /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; 9740EEB61CF901F6004384FC /* Run Script */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; @@ -510,81 +400,56 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; }; - 9872F2A25E8A171A111468CD /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ - 03BB76642665316900CE5A93 /* Sources */ = { + 331C807D294A63A400263BE5 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - E11D6A912D82C7740031E6C5 /* FLTCamExposureTests.swift in Sources */, - 97BD4A0E2D5CC5AE00F857D5 /* CameraSettingsTests.swift in Sources */, - E142F1422D85AFA400824824 /* MockGlobalEventApi.swift in Sources */, - 972CA92D2D5A28C4004B846F /* QueueUtilsTests.swift in Sources */, - E1FFEAB12D6CDE5B00B14107 /* CameraPluginInitializeCameraTests.swift in Sources */, - E142F1362D8587F900824824 /* MockCameraDeviceDiscoverer.swift in Sources */, - 979B3DFB2D5B6BC7009BDE1A /* ExceptionCatcher.m in Sources */, - E1ABED6E2D94392900AED9CC /* MockAssetWriterInputPixelBufferAdaptor.swift in Sources */, - E1ABED6C2D94392500AED9CC /* MockAssetWriter.swift in Sources */, - E1A5F4E32D80259C0005BA64 /* FLTCamSetFlashModeTests.swift in Sources */, - E1ABED6D2D94392700AED9CC /* MockAssetWriterInput.swift in Sources */, - 977A25242D5A511600931E34 /* CameraPermissionTests.swift in Sources */, - 970ADABE2D6740A900EFDCD9 /* MockWritableData.swift in Sources */, - 979B3DFE2D5B985B009BDE1A /* CameraInitRaceConditionsTests.swift in Sources */, - E142F13A2D85940600824824 /* MockCapturePhotoOutput.swift in Sources */, - E12C4FF82D68E85500515E70 /* MockFLTCameraPermissionManager.swift in Sources */, - 97922B0D2D6380C300A9B4CF /* SampleBufferTests.swift in Sources */, - E142681D2D8483FD0046CBBC /* MockCaptureSession.swift in Sources */, - E15139182D80980900FEE47B /* FLTCamSetDeviceOrientationTests.swift in Sources */, - 972CA92B2D5A1D8C004B846F /* CameraPropertiesTests.swift in Sources */, - E15BC7E42D86D08700F66474 /* MockFlutterTextureRegistry.swift in Sources */, - 978296CF2D5F744B0009BDD3 /* PhotoCaptureTests.swift in Sources */, - 979B3E002D5B9E6C009BDE1A /* CameraMethodChannelTests.swift in Sources */, - E142F13C2D8596F100824824 /* MockCaptureDeviceFormat.swift in Sources */, - E1FFEAAF2D6CDA8C00B14107 /* CameraPluginCreateCameraTests.swift in Sources */, - E142F13E2D859ADC00824824 /* MockFrameRateRange.swift in Sources */, - 97DB234D2D566D0700CEFE66 /* CameraPreviewPauseTests.swift in Sources */, - E1ABED732D943DC700AED9CC /* MockCaptureInput.swift in Sources */, - 970ADAC02D6764CC00EFDCD9 /* MockEventChannel.swift in Sources */, - E1ABED6F2D943B2500AED9CC /* MockCaptureDevice.swift in Sources */, - E1ABED722D943DC700AED9CC /* MockCaptureDeviceInputFactory.swift in Sources */, - 977A25202D5A439300931E34 /* AvailableCamerasTests.swift in Sources */, - E142681F2D8566230046CBBC /* CameraTestUtils.swift in Sources */, - E1FFEAAD2D6C8DD700B14107 /* MockCamera.swift in Sources */, - E16602952D8471C0003CFE12 /* FLTCamZoomTests.swift in Sources */, - 97BD4A102D5CE13500F857D5 /* CameraSessionPresetsTests.swift in Sources */, - 979B3E022D5BA48F009BDE1A /* CameraOrientationTests.swift in Sources */, - E12C4FF62D68C69000515E70 /* CameraPluginDelegatingMethodTests.swift in Sources */, - 977A25222D5A49EC00931E34 /* FLTCamFocusTests.swift in Sources */, - 978D90B42D5F630300CD817E /* StreamingTests.swift in Sources */, - E142F1382D85919700824824 /* MockDeviceOrientationProvider.swift in Sources */, - E11D6A8F2D81B81D0031E6C5 /* MockCaptureVideoDataOutput.swift in Sources */, - 977CAC9F2D5E5180001E5DC3 /* ThreadSafeEventChannelTests.swift in Sources */, - E142F1402D85AD7900824824 /* MockCaptureConnection.swift in Sources */, - E15BC7E62D86D17D00F66474 /* MockFlutterBinaryMessenger.swift in Sources */, - 97C0FFAE2D5E023200A36284 /* SavePhotoDelegateTests.swift in Sources */, + 335A7B032F6B061D005902FE /* CameraZoomTests.swift in Sources */, + 335A7B042F6B061D005902FE /* AvailableCamerasTests.swift in Sources */, + 335A7B052F6B061D005902FE /* PhotoCaptureTests.swift in Sources */, + 335A7B062F6B061D005902FE /* SavePhotoDelegateTests.swift in Sources */, + 335A7B072F6B061D005902FE /* MockCameraDeviceDiscoverer.swift in Sources */, + 335A7B082F6B061D005902FE /* MockFlutterTextureRegistry.swift in Sources */, + 335A7B092F6B061D005902FE /* QueueUtilsTests.swift in Sources */, + 335A7B0A2F6B061D005902FE /* CameraPreviewPauseTests.swift in Sources */, + 335A7B0B2F6B061D005902FE /* CameraPluginCreateCameraTests.swift in Sources */, + 335A7B0C2F6B061D005902FE /* MockCaptureDevice.swift in Sources */, + 335A7B0D2F6B061D005902FE /* MockWritableData.swift in Sources */, + 335A7B0E2F6B061D005902FE /* CameraOrientationTests.swift in Sources */, + 335A7B0F2F6B061D005902FE /* CameraSetFlashModeTests.swift in Sources */, + 335A7B102F6B061D005902FE /* CameraSettingsTests.swift in Sources */, + 335A7B112F6B061D005902FE /* CameraExposureTests.swift in Sources */, + 335A7B122F6B061D005902FE /* CameraMethodChannelTests.swift in Sources */, + 335A7B132F6B061D005902FE /* MockGlobalEventApi.swift in Sources */, + 335A7B142F6B061D005902FE /* MockAssetWriter.swift in Sources */, + 335A7B152F6B061D005902FE /* MockCapturePhotoOutput.swift in Sources */, + 335A7B162F6B061D005902FE /* CameraSetFocusModeTests.swift in Sources */, + 335A7B172F6B061D005902FE /* CameraPluginInitializeCameraTests.swift in Sources */, + 335A7B182F6B061D005902FE /* CameraPluginDelegatingMethodTests.swift in Sources */, + 335A7B192F6B061D005902FE /* MockAssetWriterInput.swift in Sources */, + 335A7B1A2F6B061D005902FE /* CameraTestUtils.swift in Sources */, + 335A7B1B2F6B061D005902FE /* MockAssetWriterInputPixelBufferAdaptor.swift in Sources */, + 335A7B1C2F6B061D005902FE /* MockFrameRateRange.swift in Sources */, + 335A7B1D2F6B061D005902FE /* MockDeviceOrientationProvider.swift in Sources */, + 335A7B1E2F6B061D005902FE /* MockCaptureSession.swift in Sources */, + 335A7B1F2F6B061D005902FE /* CameraPermissionTests.swift in Sources */, + 335A7B202F6B061D005902FE /* MockCaptureDeviceInputFactory.swift in Sources */, + 335A7B212F6B061D005902FE /* SampleBufferTests.swift in Sources */, + 335A7B222F6B061D005902FE /* MockCaptureInput.swift in Sources */, + 335A7B232F6B061D005902FE /* CameraSetDeviceOrientationTests.swift in Sources */, + 335A7B242F6B061D005902FE /* MockCamera.swift in Sources */, + 335A7B252F6B061D005902FE /* MockCaptureDeviceFormat.swift in Sources */, + 335A7B262F6B061D005902FE /* MockFLTCameraPermissionManager.swift in Sources */, + 335A7B272F6B061D005902FE /* CameraPropertiesTests.swift in Sources */, + 335A7B282F6B061D005902FE /* CameraSessionPresetsTests.swift in Sources */, + 335A7B292F6B061D005902FE /* MockFlutterBinaryMessenger.swift in Sources */, + 335A7B2A2F6B061D005902FE /* CameraInitRaceConditionsTests.swift in Sources */, + 335A7B2B2F6B061D005902FE /* MockCaptureConnection.swift in Sources */, + 335A7B2C2F6B061D005902FE /* StreamingTests.swift in Sources */, + 335A7B2D2F6B061D005902FE /* MockCaptureVideoDataOutput.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -592,19 +457,19 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 978B8F6F1D3862AE00F588F7 /* AppDelegate.m in Sources */, - 97C146F31CF9000F007C117D /* main.m in Sources */, + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ - 03BB766E2665316900CE5A93 /* PBXTargetDependency */ = { + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 97C146ED1CF9000F007C117D /* Runner */; - targetProxy = 03BB766D2665316900CE5A93 /* PBXContainerItemProxy */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ @@ -628,75 +493,131 @@ /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ - 03BB766F2665316900CE5A93 /* Debug */ = { + 249021D3217E4FDB00AE95B9 /* Profile */ = { isa = XCBuildConfiguration; - baseConfigurationReference = B61D98BBC8FB276D1C4A7BB2 /* Pods-RunnerTests.debug.xcconfig */; buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CODE_SIGN_STYLE = Automatic; - GCC_C_LANGUAGE_STANDARD = gnu11; - INFOPLIST_FILE = RunnerTests/Info.plist; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", - "@loader_path/Frameworks", ); - MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; - MTL_FAST_MATH = YES; - PRODUCT_BUNDLE_IDENTIFIER = "dev.flutter.plugins.cameraExample.camera-exampleTests"; + PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.cameraExample; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_OBJC_BRIDGING_HEADER = "RunnerTests/RunnerTests-Bridging-Header.h"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.cameraExample.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/Runner"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; }; name = Debug; }; - 03BB76702665316900CE5A93 /* Release */ = { + 331C8089294A63A400263BE5 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = E67C6DBF6478BE708993169F /* Pods-RunnerTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = NO; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; CODE_SIGN_STYLE = Automatic; - GCC_C_LANGUAGE_STANDARD = gnu11; - INFOPLIST_FILE = RunnerTests/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MTL_FAST_MATH = YES; - PRODUCT_BUNDLE_IDENTIFIER = "dev.flutter.plugins.cameraExample.camera-exampleTests"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.cameraExample.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_OBJC_BRIDGING_HEADER = "RunnerTests/RunnerTests-Bridging-Header.h"; SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/Runner"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; }; name = Release; }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.cameraExample.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; 97C147031CF9000F007C117D /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; @@ -726,6 +647,7 @@ DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; @@ -752,7 +674,7 @@ isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; @@ -782,6 +704,7 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; @@ -793,6 +716,9 @@ IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; @@ -803,22 +729,20 @@ baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.cameraExample; + PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.cameraExample; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; }; name = Debug; }; @@ -827,33 +751,31 @@ baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.cameraExample; + PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.cameraExample; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ - 03BB76712665316900CE5A93 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { isa = XCConfigurationList; buildConfigurations = ( - 03BB766F2665316900CE5A93 /* Debug */, - 03BB76702665316900CE5A93 /* Release */, + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; @@ -863,6 +785,7 @@ buildConfigurations = ( 97C147031CF9000F007C117D /* Debug */, 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; @@ -872,6 +795,7 @@ buildConfigurations = ( 97C147061CF9000F007C117D /* Debug */, 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; diff --git a/packages/google_maps_flutter/google_maps_flutter_ios/example/ios14/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/packages/camera/camera_avfoundation/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist similarity index 100% rename from packages/google_maps_flutter/google_maps_flutter_ios/example/ios14/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist rename to packages/camera/camera_avfoundation/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist diff --git a/packages/camera/camera_avfoundation/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/packages/camera/camera_avfoundation/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 000000000000..f9b0d7c5ea15 --- /dev/null +++ b/packages/camera/camera_avfoundation/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/packages/camera/camera_avfoundation/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/packages/camera/camera_avfoundation/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index ba0c5508103c..c3fedb29c990 100644 --- a/packages/camera/camera_avfoundation/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/packages/camera/camera_avfoundation/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -44,6 +44,7 @@ buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + customLLDBInitFile = "$(SRCROOT)/Flutter/ephemeral/flutter_lldbinit" shouldUseLaunchSchemeArgsEnv = "YES"> + skipped = "NO" + parallelizable = "YES"> @@ -71,6 +73,7 @@ buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + customLLDBInitFile = "$(SRCROOT)/Flutter/ephemeral/flutter_lldbinit" launchStyle = "0" useCustomWorkingDirectory = "NO" ignoresPersistentStateOnLaunch = "NO" @@ -88,16 +91,9 @@ ReferencedContainer = "container:Runner.xcodeproj"> - - - - - - diff --git a/packages/camera/camera_avfoundation/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/packages/camera/camera_avfoundation/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 000000000000..f9b0d7c5ea15 --- /dev/null +++ b/packages/camera/camera_avfoundation/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/AppDelegate.h b/packages/camera/camera_avfoundation/example/ios/Runner/AppDelegate.h deleted file mode 100644 index 721cca1e11bb..000000000000 --- a/packages/camera/camera_avfoundation/example/ios/Runner/AppDelegate.h +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import -#import - -@interface AppDelegate : FlutterAppDelegate - -@end diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/AppDelegate.m b/packages/camera/camera_avfoundation/example/ios/Runner/AppDelegate.m deleted file mode 100644 index fff9545d5055..000000000000 --- a/packages/camera/camera_avfoundation/example/ios/Runner/AppDelegate.m +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "AppDelegate.h" -#include "GeneratedPluginRegistrant.h" - -@implementation AppDelegate - -- (BOOL)application:(UIApplication *)application - didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - [GeneratedPluginRegistrant registerWithRegistry:self]; - // Override point for customization after application launch. - return [super application:application didFinishLaunchingWithOptions:launchOptions]; -} - -@end diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/AppDelegate.swift b/packages/camera/camera_avfoundation/example/ios/Runner/AppDelegate.swift new file mode 100644 index 000000000000..ba78d5879052 --- /dev/null +++ b/packages/camera/camera_avfoundation/example/ios/Runner/AppDelegate.swift @@ -0,0 +1,27 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } + + func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { + // Plugin registration eventually sends camera operations on the background queue, which + // would run concurrently with the test cases during unit tests, making the debugging + // process confusing. This setup is actually not necessary for the unit tests, so + // skip it when running unit tests. + if NSClassFromString("XCTestCase") != nil { + return + } + GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + } +} diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json index d225b3c2cfe2..d36b1fab2d9d 100644 --- a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json +++ b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -109,8 +109,9 @@ "scale" : "2x" }, { - "idiom" : "ios-marketing", "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", "scale" : "1x" } ], @@ -118,4 +119,4 @@ "version" : 1, "author" : "xcode" } -} \ No newline at end of file +} diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 000000000000..dc9ada4725e9 Binary files /dev/null and b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png index 28c6bf03016f..7353c41ecf9c 100644 Binary files a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png and b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png index 2ccbfd967d96..797d452e4589 100644 Binary files a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png and b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png index f091b6b0bca8..6ed2d933e112 100644 Binary files a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png and b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png index 4cde12118dda..4cd7b0099ca8 100644 Binary files a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png and b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png index d0ef06e7edb8..fe730945a01f 100644 Binary files a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png and b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png index dcdc2306c285..321773cd857a 100644 Binary files a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png and b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png index 2ccbfd967d96..797d452e4589 100644 Binary files a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png and b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png index c8f9ed8f5cee..502f463a9bc8 100644 Binary files a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png and b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png index a6d6b8609df0..0ec303439225 100644 Binary files a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png and b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png index a6d6b8609df0..0ec303439225 100644 Binary files a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png and b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png index 75b2d164a5a9..e9f5fea27c70 100644 Binary files a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png and b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png index c4df70d39da7..84ac32ae7d98 100644 Binary files a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png and b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png index 6a84f41e14e2..8953cba09064 100644 Binary files a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png and b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png index d0e1f5853602..0467bf12aa4d 100644 Binary files a/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png and b/packages/camera/camera_avfoundation/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/Info.plist b/packages/camera/camera_avfoundation/example/ios/Runner/Info.plist index adb62fb7803d..90a69cb598b5 100644 --- a/packages/camera/camera_avfoundation/example/ios/Runner/Info.plist +++ b/packages/camera/camera_avfoundation/example/ios/Runner/Info.plist @@ -5,7 +5,9 @@ CADisableMinimumFrameDurationOnPhone CFBundleDevelopmentRegion - en + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Camera Example CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier @@ -17,31 +19,47 @@ CFBundlePackageType APPL CFBundleShortVersionString - 1.0 + $(FLUTTER_BUILD_NAME) CFBundleSignature ???? CFBundleVersion - 1 - LSApplicationCategoryType - + $(FLUTTER_BUILD_NUMBER) LSRequiresIPhoneOS NSCameraUsageDescription Can I use the camera please? Only for demo purpose of the app NSMicrophoneUsageDescription Only for demo purpose of the app + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneClassName + UIWindowScene + UISceneConfigurationName + flutter + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UIApplicationSupportsIndirectInputEvents + UILaunchStoryboardName LaunchScreen UIMainStoryboardFile Main - UIRequiredDeviceCapabilities - - arm64 - UISupportedInterfaceOrientations UIInterfaceOrientationPortrait - UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight @@ -52,9 +70,5 @@ UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight - CADisableMinimumFrameDurationOnPhone - - UIApplicationSupportsIndirectInputEvents - diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/Runner-Bridging-Header.h b/packages/camera/camera_avfoundation/example/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 000000000000..ba04211afd0a --- /dev/null +++ b/packages/camera/camera_avfoundation/example/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1,5 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "GeneratedPluginRegistrant.h" diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/SceneDelegate.swift b/packages/camera/camera_avfoundation/example/ios/Runner/SceneDelegate.swift new file mode 100644 index 000000000000..8c7b10c639d1 --- /dev/null +++ b/packages/camera/camera_avfoundation/example/ios/Runner/SceneDelegate.swift @@ -0,0 +1,10 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import Flutter +import UIKit + +class SceneDelegate: FlutterSceneDelegate { + +} diff --git a/packages/camera/camera_avfoundation/example/ios/Runner/main.m b/packages/camera/camera_avfoundation/example/ios/Runner/main.m deleted file mode 100644 index 3ec494eae7e8..000000000000 --- a/packages/camera/camera_avfoundation/example/ios/Runner/main.m +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import -#import -#import "AppDelegate.h" - -int main(int argc, char *argv[]) { - @autoreleasepool { - // The setup logic in `AppDelegate::didFinishLaunchingWithOptions:` eventually sends camera - // operations on the background queue, which would run concurrently with the test cases during - // unit tests, making the debugging process confusing. This setup is actually not necessary for - // the unit tests, so it is better to skip the AppDelegate when running unit tests. - BOOL isTesting = NSClassFromString(@"XCTestCase") != nil; - return UIApplicationMain(argc, argv, nil, - isTesting ? nil : NSStringFromClass([AppDelegate class])); - } -} diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/AvailableCamerasTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/AvailableCamerasTests.swift index 50eb2f62ab16..4fbece5523d5 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/AvailableCamerasTests.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/AvailableCamerasTests.swift @@ -7,11 +7,6 @@ import XCTest @testable import camera_avfoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - final class AvailableCamerasTest: XCTestCase { private func createCameraPlugin(with deviceDiscoverer: MockCameraDeviceDiscoverer) -> CameraPlugin { @@ -20,7 +15,7 @@ final class AvailableCamerasTest: XCTestCase { messenger: MockFlutterBinaryMessenger(), globalAPI: MockGlobalEventApi(), deviceDiscoverer: deviceDiscoverer, - permissionManager: MockFLTCameraPermissionManager(), + permissionManager: MockCameraPermissionManager(), deviceFactory: { _ in MockCaptureDevice() }, captureSessionFactory: { MockCaptureSession() }, captureDeviceInputFactory: MockCaptureDeviceInputFactory(), @@ -62,10 +57,9 @@ final class AvailableCamerasTest: XCTestCase { return cameras } - var resultValue: [FCPPlatformCameraDescription]? - cameraPlugin.availableCameras { result, error in - XCTAssertNil(error) - resultValue = result + var resultValue: [PlatformCameraDescription]? + cameraPlugin.getAvailableCameras { result in + resultValue = self.assertSuccess(result) expectation.fulfill() } waitForExpectations(timeout: 30, handler: nil) @@ -100,10 +94,9 @@ final class AvailableCamerasTest: XCTestCase { return cameras } - var resultValue: [FCPPlatformCameraDescription]? - cameraPlugin.availableCameras { result, error in - XCTAssertNil(error) - resultValue = result + var resultValue: [PlatformCameraDescription]? + cameraPlugin.getAvailableCameras { result in + resultValue = self.assertSuccess(result) expectation.fulfill() } waitForExpectations(timeout: 30, handler: nil) @@ -133,10 +126,9 @@ final class AvailableCamerasTest: XCTestCase { return cameras } - var resultValue: [FCPPlatformCameraDescription]? - cameraPlugin.availableCameras { result, error in - XCTAssertNil(error) - resultValue = result + var resultValue: [PlatformCameraDescription]? + cameraPlugin.getAvailableCameras { result in + resultValue = self.assertSuccess(result) expectation.fulfill() } waitForExpectations(timeout: 30, handler: nil) diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraExposureTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraExposureTests.swift new file mode 100644 index 000000000000..da5531b652bb --- /dev/null +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraExposureTests.swift @@ -0,0 +1,146 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import XCTest + +@testable import camera_avfoundation + +final class CameraExposureTests: XCTestCase { + private func createCamera() -> (Camera, MockCaptureDevice, MockDeviceOrientationProvider) { + let mockDevice = MockCaptureDevice() + let mockDeviceOrientationProvider = MockDeviceOrientationProvider() + + let configuration = CameraTestUtils.createTestCameraConfiguration() + configuration.videoCaptureDeviceFactory = { _ in mockDevice } + configuration.deviceOrientationProvider = mockDeviceOrientationProvider + let camera = CameraTestUtils.createTestCamera(configuration) + + return (camera, mockDevice, mockDeviceOrientationProvider) + } + + func testSetExposureModeLocked_setsAuthExposeMode() { + let (camera, mockDevice, _) = createCamera() + + mockDevice.setExposureModeStub = { mode in + // AVCaptureExposureModeAutoExpose automatically adjusts the exposure one time, and then + // locks exposure for the device + XCTAssertEqual(mode, .autoExpose) + } + + camera.setExposureMode(.locked) + } + + func testSetExposureModeAuto_setsContinousAutoExposureMode_ifSupported() { + let (camera, mockDevice, _) = createCamera() + + // All exposure modes are supported + mockDevice.isExposureModeSupportedStub = { _ in true } + + mockDevice.setExposureModeStub = { mode in + XCTAssertEqual(mode, .continuousAutoExposure) + } + + camera.setExposureMode(.auto) + } + + func testSetExposureModeAuto_setsAutoExposeMode_ifContinousAutoIsNotSupported() { + let (camera, mockDevice, _) = createCamera() + + // Continous auto exposure is not supported + mockDevice.isExposureModeSupportedStub = { mode in + mode != .continuousAutoExposure + } + + mockDevice.setExposureModeStub = { mode in + XCTAssertEqual(mode, .autoExpose) + } + + camera.setExposureMode(.auto) + } + + func testSetExposurePoint_setsExposurePointOfInterest() { + let (camera, mockDevice, mockDeviceOrientationProvider) = createCamera() + // UI is currently in landscape left orientation. + mockDeviceOrientationProvider.orientationStub = { .landscapeLeft } + // Exposure point of interest is supported. + mockDevice.isExposurePointOfInterestSupported = true + + // Verify the focus point of interest has been set. + var setPoint = CGPoint.zero + mockDevice.setExposurePointOfInterestStub = { point in + if point == CGPoint(x: 1, y: 1) { + setPoint = point + } + } + + let expectation = expectation(description: "Completion called") + camera.setExposurePoint(PlatformPoint(x: 1, y: 1)) { + result in + let _ = self.assertSuccess(result) + expectation.fulfill() + } + + waitForExpectations(timeout: 30, handler: nil) + XCTAssertEqual(setPoint, CGPoint(x: 1.0, y: 1.0)) + } + + func testSetExposurePoint_returnsError_ifNotSupported() { + let (camera, mockDevice, mockDeviceOrientationProvider) = createCamera() + // UI is currently in landscape left orientation. + mockDeviceOrientationProvider.orientationStub = { .landscapeLeft } + // Exposure point of interest is not supported. + mockDevice.isExposurePointOfInterestSupported = false + + let expectation = expectation(description: "Completion with error") + + camera.setExposurePoint(PlatformPoint(x: 1, y: 1)) { result in + switch result { + case .failure(let error as PigeonError): + XCTAssertEqual(error.code, "setExposurePointFailed") + XCTAssertEqual(error.message, "Device does not have exposure point capabilities") + default: + XCTFail("Expected failure") + } + expectation.fulfill() + } + + waitForExpectations(timeout: 30, handler: nil) + } + + func testSetExposureOffset_setsExposureTargetBias() { + let (camera, mockDevice, _) = createCamera() + + let targetOffset = CGFloat(1.0) + + var setExposureTargetBiasCalled = false + mockDevice.setExposureTargetBiasStub = { bias, handler in + XCTAssertEqual(bias, Float(targetOffset)) + setExposureTargetBiasCalled = true + } + + camera.setExposureOffset(targetOffset) + + XCTAssertTrue(setExposureTargetBiasCalled) + } + + func testMaximumExposureOffset_returnsDeviceMaxExposureTargetBias() { + let (camera, mockDevice, _) = createCamera() + + let targetOffset = CGFloat(1.0) + + mockDevice.maxExposureTargetBias = Float(targetOffset) + + XCTAssertEqual(camera.maximumExposureOffset, targetOffset) + } + + func testMinimumExposureOffset_returnsDeviceMinExposureTargetBias() { + let (camera, mockDevice, _) = createCamera() + + let targetOffset = CGFloat(1.0) + + mockDevice.minExposureTargetBias = Float(targetOffset) + + XCTAssertEqual(camera.minimumExposureOffset, targetOffset) + } +} diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraInitRaceConditionsTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraInitRaceConditionsTests.swift index 3f60374101b1..03f5fa3e9fab 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraInitRaceConditionsTests.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraInitRaceConditionsTests.swift @@ -6,11 +6,6 @@ import XCTest @testable import camera_avfoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - final class CameraInitRaceConditionsTests: XCTestCase { private func createCameraPlugin() -> (CameraPlugin, DispatchQueue) { let captureSessionQueue = DispatchQueue(label: "io.flutter.camera.captureSessionQueue") @@ -20,7 +15,7 @@ final class CameraInitRaceConditionsTests: XCTestCase { messenger: MockFlutterBinaryMessenger(), globalAPI: MockGlobalEventApi(), deviceDiscoverer: MockCameraDeviceDiscoverer(), - permissionManager: MockFLTCameraPermissionManager(), + permissionManager: MockCameraPermissionManager(), deviceFactory: { _ in MockCaptureDevice() }, captureSessionFactory: { MockCaptureSession() }, captureDeviceInputFactory: MockCaptureDeviceInputFactory(), @@ -37,20 +32,20 @@ final class CameraInitRaceConditionsTests: XCTestCase { // Mimic a dispose call followed by a create call, which can be triggered by slightly dragging the // home bar, causing the app to be inactive, and immediately regain active. - cameraPlugin.disposeCamera(0) { error in + cameraPlugin.dispose(cameraId: 0) { error in disposeExpectation.fulfill() } cameraPlugin.createCameraOnSessionQueue( withName: "acamera", - settings: FCPPlatformMediaSettings.make( - with: .medium, + settings: PlatformMediaSettings( + resolutionPreset: .medium, framesPerSecond: nil, videoBitrate: nil, audioBitrate: nil, enableAudio: true ) - ) { result, error in + ) { result in createExpectation.fulfill() } @@ -69,14 +64,14 @@ final class CameraInitRaceConditionsTests: XCTestCase { cameraPlugin.createCameraOnSessionQueue( withName: "acamera", - settings: FCPPlatformMediaSettings.make( - with: .medium, + settings: PlatformMediaSettings( + resolutionPreset: .medium, framesPerSecond: nil, videoBitrate: nil, audioBitrate: nil, enableAudio: true ) - ) { result, error in + ) { result in createExpectation.fulfill() } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraMethodChannelTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraMethodChannelTests.swift index 3a46585ae3bd..80231393b5d4 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraMethodChannelTests.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraMethodChannelTests.swift @@ -7,11 +7,6 @@ import XCTest @testable import camera_avfoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - final class CameraMethodChannelTests: XCTestCase { private func createCameraPlugin(with session: MockCaptureSession) -> CameraPlugin { return CameraPlugin( @@ -19,7 +14,7 @@ final class CameraMethodChannelTests: XCTestCase { messenger: MockFlutterBinaryMessenger(), globalAPI: MockGlobalEventApi(), deviceDiscoverer: MockCameraDeviceDiscoverer(), - permissionManager: MockFLTCameraPermissionManager(), + permissionManager: MockCameraPermissionManager(), deviceFactory: { _ in MockCaptureDevice() }, captureSessionFactory: { session }, captureDeviceInputFactory: MockCaptureDeviceInputFactory(), @@ -33,18 +28,18 @@ final class CameraMethodChannelTests: XCTestCase { let camera = createCameraPlugin(with: avCaptureSessionMock) let expectation = self.expectation(description: "Result finished") - var resultValue: NSNumber? + var resultValue: Int64? camera.createCameraOnSessionQueue( withName: "acamera", - settings: FCPPlatformMediaSettings.make( - with: FCPPlatformResolutionPreset.medium, + settings: PlatformMediaSettings( + resolutionPreset: .medium, framesPerSecond: nil, videoBitrate: nil, audioBitrate: nil, enableAudio: true ) - ) { result, error in - resultValue = result + ) { result in + resultValue = self.assertSuccess(result) expectation.fulfill() } @@ -60,14 +55,14 @@ final class CameraMethodChannelTests: XCTestCase { camera.createCameraOnSessionQueue( withName: "acamera", - settings: FCPPlatformMediaSettings.make( - with: .medium, + settings: PlatformMediaSettings( + resolutionPreset: .medium, framesPerSecond: nil, videoBitrate: nil, audioBitrate: nil, enableAudio: true ) - ) { result, error in + ) { result in createExpectation.fulfill() } @@ -75,7 +70,7 @@ final class CameraMethodChannelTests: XCTestCase { XCTAssertNotNil(camera.camera) let disposeExpectation = self.expectation(description: "dispose's result block must be called") - camera.disposeCamera(0) { error in + camera.dispose(cameraId: 0) { error in disposeExpectation.fulfill() } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraOrientationTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraOrientationTests.swift index 23d00a86e152..4878cbe51d6f 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraOrientationTests.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraOrientationTests.swift @@ -8,11 +8,6 @@ import XCTest @testable import camera_avfoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - private final class MockUIDevice: UIDevice { var mockOrientation: UIDeviceOrientation = .unknown @@ -41,7 +36,7 @@ final class CameraOrientationTests: XCTestCase { messenger: MockFlutterBinaryMessenger(), globalAPI: mockEventAPI, deviceDiscoverer: mockDeviceDiscoverer, - permissionManager: MockFLTCameraPermissionManager(), + permissionManager: MockCameraPermissionManager(), deviceFactory: { _ in mockDevice }, captureSessionFactory: { MockCaptureSession() }, captureDeviceInputFactory: MockCaptureDeviceInputFactory(), @@ -130,7 +125,7 @@ final class CameraOrientationTests: XCTestCase { messenger: MockFlutterBinaryMessenger(), globalAPI: mockEventAPI, deviceDiscoverer: mockDeviceDiscoverer, - permissionManager: MockFLTCameraPermissionManager(), + permissionManager: MockCameraPermissionManager(), deviceFactory: { _ in weakDevice! }, captureSessionFactory: { MockCaptureSession() }, captureDeviceInputFactory: MockCaptureDeviceInputFactory(), diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPermissionTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPermissionTests.swift index 0709b8a3c0da..d8ca79f65eca 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPermissionTests.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPermissionTests.swift @@ -3,32 +3,28 @@ // found in the LICENSE file. import AVFoundation +import Flutter import XCTest @testable import camera_avfoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - -private final class MockPermissionService: NSObject, FLTPermissionServicing { +private final class MockPermissionService: NSObject, PermissionServicing { var authorizationStatusStub: ((AVMediaType) -> AVAuthorizationStatus)? - var requestAccessStub: ((AVMediaType, @escaping (Bool) -> Void) -> Void)? + var requestAccessStub: ((AVMediaType, @escaping @Sendable (Bool) -> Void) -> Void)? func authorizationStatus(for mediaType: AVMediaType) -> AVAuthorizationStatus { return authorizationStatusStub?(mediaType) ?? .notDetermined } - func requestAccess(for mediaType: AVMediaType, completion: @escaping (Bool) -> Void) { + func requestAccess(for mediaType: AVMediaType, completion: @escaping @Sendable (Bool) -> Void) { requestAccessStub?(mediaType, completion) } } final class CameraPermissionManagerTests: XCTestCase { - private func createSutAndMocks() -> (FLTCameraPermissionManager, MockPermissionService) { + private func createSutAndMocks() -> (CameraPermissionManager, MockPermissionService) { let mockPermissionService = MockPermissionService() - let permissionManager = FLTCameraPermissionManager(permissionService: mockPermissionService) + let permissionManager = CameraPermissionManager(permissionService: mockPermissionService) return (permissionManager, mockPermissionService) } @@ -56,18 +52,17 @@ final class CameraPermissionManagerTests: XCTestCase { let (permissionManager, mockPermissionService) = createSutAndMocks() let expectation = self.expectation( description: "Must complete with error if camera access was previously denied.") - let expectedError = FlutterError( - code: "CameraAccessDeniedWithoutPrompt", - message: - "User has previously denied the camera access request. Go to Settings to enable camera access.", - details: nil) mockPermissionService.authorizationStatusStub = { mediaType in XCTAssertEqual(mediaType, .video) return .denied } permissionManager.requestCameraPermission { error in - XCTAssertEqual(error, expectedError) + XCTAssertEqual(error?.code, "CameraAccessDeniedWithoutPrompt") + XCTAssertEqual( + error?.message, + "User has previously denied the camera access request. Go to Settings to enable camera access." + ) expectation.fulfill() } @@ -78,17 +73,14 @@ final class CameraPermissionManagerTests: XCTestCase { let (permissionManager, mockPermissionService) = createSutAndMocks() let expectation = self.expectation( description: "Must complete with error if camera access is restricted.") - let expectedError = FlutterError( - code: "CameraAccessRestricted", - message: "Camera access is restricted.", - details: nil) mockPermissionService.authorizationStatusStub = { mediaType in XCTAssertEqual(mediaType, .video) return .restricted } permissionManager.requestCameraPermission { error in - XCTAssertEqual(error, expectedError) + XCTAssertEqual(error?.code, "CameraAccessRestricted") + XCTAssertEqual(error?.message, "Camera access is restricted.") expectation.fulfill() } @@ -121,10 +113,6 @@ final class CameraPermissionManagerTests: XCTestCase { let (permissionManager, mockPermissionService) = createSutAndMocks() let expectation = self.expectation( description: "Must complete with error if user denied access.") - let expectedError = FlutterError( - code: "CameraAccessDenied", - message: "User denied the camera access request.", - details: nil) mockPermissionService.authorizationStatusStub = { mediaType in XCTAssertEqual(mediaType, .video) @@ -136,7 +124,8 @@ final class CameraPermissionManagerTests: XCTestCase { handler(false) } permissionManager.requestCameraPermission { error in - XCTAssertEqual(error, expectedError) + XCTAssertEqual(error?.code, "CameraAccessDenied") + XCTAssertEqual(error?.message, "User denied the camera access request.") expectation.fulfill() } @@ -166,18 +155,17 @@ final class CameraPermissionManagerTests: XCTestCase { let (permissionManager, mockPermissionService) = createSutAndMocks() let expectation = self.expectation( description: "Must complete with error if audio access was previously denied.") - let expectedError = FlutterError( - code: "AudioAccessDeniedWithoutPrompt", - message: - "User has previously denied the audio access request. Go to Settings to enable audio access.", - details: nil) mockPermissionService.authorizationStatusStub = { mediaType in XCTAssertEqual(mediaType, .audio) return .denied } permissionManager.requestAudioPermission { error in - XCTAssertEqual(error, expectedError) + XCTAssertEqual(error?.code, "AudioAccessDeniedWithoutPrompt") + XCTAssertEqual( + error?.message, + "User has previously denied the audio access request. Go to Settings to enable audio access." + ) expectation.fulfill() } @@ -188,17 +176,14 @@ final class CameraPermissionManagerTests: XCTestCase { let (permissionManager, mockPermissionService) = createSutAndMocks() let expectation = self.expectation( description: "Must complete with error if audio access is restricted.") - let expectedError = FlutterError( - code: "AudioAccessRestricted", - message: "Audio access is restricted.", - details: nil) mockPermissionService.authorizationStatusStub = { mediaType in XCTAssertEqual(mediaType, .audio) return .restricted } permissionManager.requestAudioPermission { error in - XCTAssertEqual(error, expectedError) + XCTAssertEqual(error?.code, "AudioAccessRestricted") + XCTAssertEqual(error?.message, "Audio access is restricted.") expectation.fulfill() } @@ -231,10 +216,6 @@ final class CameraPermissionManagerTests: XCTestCase { let (permissionManager, mockPermissionService) = createSutAndMocks() let expectation = self.expectation( description: "Must complete with error if user denied access") - let expectedError = FlutterError( - code: "AudioAccessDenied", - message: "User denied the audio access request.", - details: nil) mockPermissionService.authorizationStatusStub = { mediaType in XCTAssertEqual(mediaType, .audio) @@ -246,7 +227,8 @@ final class CameraPermissionManagerTests: XCTestCase { handler(false) } permissionManager.requestAudioPermission { error in - XCTAssertEqual(error, expectedError) + XCTAssertEqual(error?.code, "AudioAccessDenied") + XCTAssertEqual(error?.message, "User denied the audio access request.") expectation.fulfill() } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPluginCreateCameraTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPluginCreateCameraTests.swift index e7f333153dbb..269ba03067b0 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPluginCreateCameraTests.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPluginCreateCameraTests.swift @@ -6,16 +6,11 @@ import XCTest @testable import camera_avfoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - final class CameraPluginCreateCameraTests: XCTestCase { private func createCameraPlugin() -> ( - CameraPlugin, MockFLTCameraPermissionManager, MockCaptureSession + CameraPlugin, MockCameraPermissionManager, MockCaptureSession ) { - let mockPermissionManager = MockFLTCameraPermissionManager() + let mockPermissionManager = MockCameraPermissionManager() let mockCaptureSession = MockCaptureSession() let cameraPlugin = CameraPlugin( @@ -41,24 +36,24 @@ final class CameraPluginCreateCameraTests: XCTestCase { mockPermissionManager.requestCameraPermissionStub = { completion in requestCameraPermissionCalled = true // Permission is granted - completion?(nil) + completion(nil) } var requestAudioPermissionCalled = false mockPermissionManager.requestAudioPermissionStub = { completion in requestAudioPermissionCalled = true // Permission is granted - completion?(nil) + completion(nil) } - cameraPlugin.createCamera( - withName: "camera_name", - settings: FCPPlatformMediaSettings.make( - with: .medium, + cameraPlugin.create( + cameraName: "camera_name", + settings: PlatformMediaSettings( + resolutionPreset: .medium, framesPerSecond: nil, videoBitrate: nil, audioBitrate: nil, enableAudio: false) - ) { result, error in + ) { result in expectation.fulfill() } @@ -76,24 +71,24 @@ final class CameraPluginCreateCameraTests: XCTestCase { mockPermissionManager.requestCameraPermissionStub = { completion in requestCameraPermissionCalled = true // Permission is granted - completion?(nil) + completion(nil) } var requestAudioPermissionCalled = false mockPermissionManager.requestAudioPermissionStub = { completion in requestAudioPermissionCalled = true // Permission is granted - completion?(nil) + completion(nil) } - cameraPlugin.createCamera( - withName: "camera_name", - settings: FCPPlatformMediaSettings.make( - with: .medium, + cameraPlugin.create( + cameraName: "camera_name", + settings: PlatformMediaSettings( + resolutionPreset: .medium, framesPerSecond: nil, videoBitrate: nil, audioBitrate: nil, enableAudio: true) - ) { result, error in + ) { result in expectation.fulfill() } @@ -103,29 +98,29 @@ final class CameraPluginCreateCameraTests: XCTestCase { XCTAssertTrue(requestAudioPermissionCalled) } - func testCreateCamera_createsFLTCamSuccessfully() { + func testCreateCamera_createsCameraSuccessfully() { let (cameraPlugin, mockPermissionManager, mockCaptureSession) = createCameraPlugin() let expectation = expectation(description: "Initialization completed") mockPermissionManager.requestCameraPermissionStub = { completion in // Permission is granted - completion?(nil) + completion(nil) } mockPermissionManager.requestAudioPermissionStub = { completion in // Permission is granted - completion?(nil) + completion(nil) } mockCaptureSession.canSetSessionPresetStub = { _ in true } - cameraPlugin.createCamera( - withName: "camera_name", - settings: FCPPlatformMediaSettings.make( - with: .medium, + cameraPlugin.create( + cameraName: "camera_name", + settings: PlatformMediaSettings( + resolutionPreset: .medium, framesPerSecond: nil, videoBitrate: nil, audioBitrate: nil, enableAudio: true) - ) { result, error in + ) { result in expectation.fulfill() } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPluginDelegatingMethodTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPluginDelegatingMethodTests.swift index 31fad0c008ae..34a306b511d7 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPluginDelegatingMethodTests.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPluginDelegatingMethodTests.swift @@ -6,12 +6,7 @@ import XCTest @testable import camera_avfoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - -/// Tests of `CameraPlugin` methods delegating to `FLTCam` instance +/// Tests of `CameraPlugin` methods delegating to `Camera` instance final class CameraPluginDelegatingMethodTests: XCTestCase { private func createCameraPlugin() -> (CameraPlugin, MockCamera) { let mockCamera = MockCamera() @@ -21,7 +16,7 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { messenger: MockFlutterBinaryMessenger(), globalAPI: MockGlobalEventApi(), deviceDiscoverer: MockCameraDeviceDiscoverer(), - permissionManager: MockFLTCameraPermissionManager(), + permissionManager: MockCameraPermissionManager(), deviceFactory: { _ in MockCaptureDevice() }, captureSessionFactory: { MockCaptureSession() }, captureDeviceInputFactory: MockCaptureDeviceInputFactory(), @@ -36,7 +31,7 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { let (cameraPlugin, mockCamera) = createCameraPlugin() let expectation = expectation(description: "Call completed") - let targetOrientation = FCPPlatformDeviceOrientation.landscapeLeft + let targetOrientation = PlatformDeviceOrientation.landscapeLeft var lockCaptureCalled = false mockCamera.lockCaptureOrientationStub = { orientation in @@ -44,8 +39,8 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { lockCaptureCalled = true } - cameraPlugin.lockCapture(targetOrientation) { error in - XCTAssertNil(error) + cameraPlugin.lockCaptureOrientation(orientation: targetOrientation) { result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -63,8 +58,8 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { pausePreviewCalled = true } - cameraPlugin.pausePreview { error in - XCTAssertNil(error) + cameraPlugin.pausePreview { result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -82,8 +77,8 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { pauseVideoRecordingCalled = true } - cameraPlugin.pauseVideoRecording { error in - XCTAssertNil(error) + cameraPlugin.pauseVideoRecording { result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -101,8 +96,8 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { setUpCaptureSessionForAudioIfNeededCalled = true } - cameraPlugin.prepareForVideoRecording { error in - XCTAssertNil(error) + cameraPlugin.prepareForVideoRecording { result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -120,8 +115,8 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { receivedImageStreamDataCalled = true } - cameraPlugin.receivedImageStreamData { error in - XCTAssertNil(error) + cameraPlugin.receivedImageStreamData { result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -139,8 +134,8 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { resumeVideoRecordingCalled = true } - cameraPlugin.resumeVideoRecording { error in - XCTAssertNil(error) + cameraPlugin.resumeVideoRecording { result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -158,8 +153,8 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { resumePreviewCalled = true } - cameraPlugin.resumePreview { error in - XCTAssertNil(error) + cameraPlugin.resumePreview { result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -172,7 +167,7 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { let (cameraPlugin, mockCamera) = createCameraPlugin() let expectation = expectation(description: "Call completed") - let targetExposureMode = FCPPlatformExposureMode.locked + let targetExposureMode = PlatformExposureMode.locked var setExposureModeCalled = false mockCamera.setExposureModeStub = { mode in @@ -180,8 +175,8 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { setExposureModeCalled = true } - cameraPlugin.setExposureMode(targetExposureMode) { error in - XCTAssertNil(error) + cameraPlugin.setExposureMode(mode: targetExposureMode) { result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -202,8 +197,8 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { setExposureOffsetCalled = true } - cameraPlugin.setExposureOffset(targetExposureOffset) { error in - XCTAssertNil(error) + cameraPlugin.setExposureOffset(offset: targetExposureOffset) { result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -216,7 +211,7 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { let (cameraPlugin, mockCamera) = createCameraPlugin() let expectation = expectation(description: "Call completed") - let targetFocusMode = FCPPlatformFocusMode.locked + let targetFocusMode = PlatformFocusMode.locked var setFocusModeCalled = false mockCamera.setFocusModeStub = { mode in @@ -224,8 +219,8 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { setFocusModeCalled = true } - cameraPlugin.setFocusMode(targetFocusMode) { error in - XCTAssertNil(error) + cameraPlugin.setFocusMode(mode: targetFocusMode) { result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -238,7 +233,7 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { let (cameraPlugin, mockCamera) = createCameraPlugin() let expectation = expectation(description: "Call completed") - let targetFileFormat = FCPPlatformImageFileFormat.heif + let targetFileFormat = PlatformImageFileFormat.heif var setImageFileFormatCalled = false mockCamera.setImageFileFormatStub = { fileFormat in @@ -246,8 +241,8 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { setImageFileFormatCalled = true } - cameraPlugin.setImageFileFormat(targetFileFormat) { error in - XCTAssertNil(error) + cameraPlugin.setImageFileFormat(format: targetFileFormat) { result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -263,11 +258,11 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { var startImageStreamCalled = false mockCamera.startImageStreamStub = { messenger, completion in startImageStreamCalled = true - completion(nil) + completion(.success(())) } - cameraPlugin.startImageStream { error in - XCTAssertNil(error) + cameraPlugin.startImageStream { result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -285,8 +280,8 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { stopImageStreamCalled = true } - cameraPlugin.stopImageStream { error in - XCTAssertNil(error) + cameraPlugin.stopImageStream { result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -302,12 +297,12 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { var startVideoRecordingCalled = false mockCamera.startVideoRecordingStub = { completion, messenger in XCTAssertNotNil(messenger) - completion(nil) + completion(.success(())) startVideoRecordingCalled = true } - cameraPlugin.startVideoRecording(withStreaming: true) { error in - XCTAssertNil(error) + cameraPlugin.startVideoRecording(enableStream: true) { result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -323,12 +318,12 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { var startVideoRecordingCalled = false mockCamera.startVideoRecordingStub = { completion, messenger in XCTAssertNil(messenger) - completion(nil) + completion(.success(())) startVideoRecordingCalled = true } - cameraPlugin.startVideoRecording(withStreaming: false) { error in - XCTAssertNil(error) + cameraPlugin.startVideoRecording(enableStream: false) { result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -345,13 +340,17 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { var stopVideoRecordingCalled = false mockCamera.stopVideoRecordingStub = { completion in - completion?(targetPath, nil) + completion(.success(targetPath)) stopVideoRecordingCalled = true } - cameraPlugin.stopVideoRecording { path, error in - XCTAssertEqual(path, targetPath) - XCTAssertNil(error) + cameraPlugin.stopVideoRecording { result in + switch result { + case .success(let path): + XCTAssertEqual(path, targetPath) + case .failure: + XCTFail("Unexpected error") + } expectation.fulfill() } @@ -369,8 +368,8 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { unlockCaptureOrientationCalled = true } - cameraPlugin.unlockCaptureOrientation { error in - XCTAssertNil(error) + cameraPlugin.unlockCaptureOrientation { result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -383,17 +382,17 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { let (cameraPlugin, mockCamera) = createCameraPlugin() let expectation = expectation(description: "Call completed") - let targetExposurePoint = FCPPlatformPoint.makeWith(x: 1.0, y: 1.0) + let targetExposurePoint = PlatformPoint(x: 1.0, y: 1.0) var setExposurePointCalled = false mockCamera.setExposurePointStub = { point, completion in XCTAssertEqual(point, targetExposurePoint) - completion?(nil) + completion(.success(())) setExposurePointCalled = true } - cameraPlugin.setExposurePoint(targetExposurePoint) { error in - XCTAssertNil(error) + cameraPlugin.setExposurePoint(point: targetExposurePoint) { result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -406,17 +405,17 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { let (cameraPlugin, mockCamera) = createCameraPlugin() let expectation = expectation(description: "Call completed") - let targetFlashMode = FCPPlatformFlashMode.auto + let targetFlashMode = PlatformFlashMode.auto var setFlashModeCalled = false mockCamera.setFlashModeStub = { mode, completion in XCTAssertEqual(mode, targetFlashMode) - completion?(nil) + completion(.success(())) setFlashModeCalled = true } - cameraPlugin.setFlashMode(targetFlashMode) { error in - XCTAssertNil(error) + cameraPlugin.setFlashMode(mode: targetFlashMode) { result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -429,17 +428,17 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { let (cameraPlugin, mockCamera) = createCameraPlugin() let expectation = expectation(description: "Call completed") - let targetFocusPoint = FCPPlatformPoint.makeWith(x: 1.0, y: 1.0) + let targetFocusPoint = PlatformPoint(x: 1.0, y: 1.0) var setFocusPointCalled = false mockCamera.setFocusPointStub = { point, completion in XCTAssertEqual(point, targetFocusPoint) - completion?(nil) + completion(.success(())) setFocusPointCalled = true } - cameraPlugin.setFocus(targetFocusPoint) { error in - XCTAssertNil(error) + cameraPlugin.setFocusPoint(point: targetFocusPoint) { result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -457,12 +456,12 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { var setZoomLevelCalled = false mockCamera.setZoomLevelStub = { zoom, completion in XCTAssertEqual(zoom, targetZoomLevel) - completion?(nil) + completion(.success(())) setZoomLevelCalled = true } - cameraPlugin.setZoomLevel(targetZoomLevel) { error in - XCTAssertNil(error) + cameraPlugin.setZoomLevel(zoom: targetZoomLevel) { result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -479,13 +478,17 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { var captureToFileCalled = false mockCamera.captureToFileStub = { completion in - completion?(targetPath, nil) + completion(.success(targetPath)) captureToFileCalled = true } - cameraPlugin.takePicture { path, error in - XCTAssertEqual(path, targetPath) - XCTAssertNil(error) + cameraPlugin.takePicture { result in + switch result { + case .success(let path): + XCTAssertEqual(path, targetPath) + case .failure: + XCTFail("Unexpected error") + } expectation.fulfill() } @@ -494,7 +497,7 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { XCTAssertTrue(captureToFileCalled) } - func testUpdateDescriptionWhileRecordingCameraName_callsCameraSetDescriptionWhileRecording() { + func testUpdateDescriptionWhileRecording_callsCameraSetDescriptionWhileRecording() { let (cameraPlugin, mockCamera) = createCameraPlugin() let expectation = expectation(description: "Call completed") @@ -503,12 +506,12 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { var setDescriptionWhileRecordingCalled = false mockCamera.setDescriptionWhileRecordingStub = { cameraName, completion in XCTAssertEqual(cameraName, targetCameraName) - completion?(nil) + completion(.success(())) setDescriptionWhileRecordingCalled = true } - cameraPlugin.updateDescriptionWhileRecordingCameraName(targetCameraName) { error in - XCTAssertNil(error) + cameraPlugin.updateDescriptionWhileRecording(cameraName: targetCameraName) { result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -517,7 +520,7 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { XCTAssertTrue(setDescriptionWhileRecordingCalled) } - func testGetMaximumZoomLevel_returnsValueFromCameraGetMaximumAvailableZoomFactor() { + func testGetMaxZoomLevel_returnsValueFromCameraGetMaximumAvailableZoomFactor() { let (cameraPlugin, mockCamera) = createCameraPlugin() let expectation = expectation(description: "Call completed") @@ -529,9 +532,13 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { return targetMaximumZoomLevel } - cameraPlugin.getMaximumZoomLevel { zoom, error in - XCTAssertEqual(zoom?.doubleValue, targetMaximumZoomLevel) - XCTAssertNil(error) + cameraPlugin.getMaxZoomLevel { result in + switch result { + case .success(let zoom): + XCTAssertEqual(zoom, targetMaximumZoomLevel) + case .failure: + XCTFail("Unexpected error") + } expectation.fulfill() } @@ -540,7 +547,7 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { XCTAssertTrue(getMaximumAvailableZoomFactorCalled) } - func testGetMinimumZoomLevel_returnsValueFromCameraGetMinimumAvailableZoomFactor() { + func testGetMinZoomLevel_returnsValueFromCameraGetMinimumAvailableZoomFactor() { let (cameraPlugin, mockCamera) = createCameraPlugin() let expectation = expectation(description: "Call completed") @@ -552,9 +559,13 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { return targetMinimumZoomLevel } - cameraPlugin.getMinimumZoomLevel { zoom, error in - XCTAssertEqual(zoom?.doubleValue, targetMinimumZoomLevel) - XCTAssertNil(error) + cameraPlugin.getMinZoomLevel { result in + switch result { + case .success(let zoom): + XCTAssertEqual(zoom, targetMinimumZoomLevel) + case .failure: + XCTFail("Unexpected error") + } expectation.fulfill() } @@ -563,7 +574,7 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { XCTAssertTrue(getMinimumAvailableZoomFactorCalled) } - func testGetMaximumExposureOffset_returnsValueFromCameraGetMaximumExposureOffset() { + func testGetMaxExposureOffset_returnsValueFromCameraGetMaximumExposureOffset() { let (cameraPlugin, mockCamera) = createCameraPlugin() let expectation = expectation(description: "Call completed") @@ -575,9 +586,13 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { return targetMaximumExposureOffset } - cameraPlugin.getMaximumExposureOffset { offset, error in - XCTAssertEqual(offset?.doubleValue, targetMaximumExposureOffset) - XCTAssertNil(error) + cameraPlugin.getMaxExposureOffset { result in + switch result { + case .success(let offset): + XCTAssertEqual(offset, targetMaximumExposureOffset) + case .failure: + XCTFail("Unexpected error") + } expectation.fulfill() } @@ -586,7 +601,7 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { XCTAssertTrue(getMaximumExposureOffsetCalled) } - func testGetMinimumExposureOffset_returnsValueFromCameraGetMinimumExposureOffset() { + func testGetMinExposureOffset_returnsValueFromCameraGetMinimumExposureOffset() { let (cameraPlugin, mockCamera) = createCameraPlugin() let expectation = expectation(description: "Call completed") @@ -598,9 +613,13 @@ final class CameraPluginDelegatingMethodTests: XCTestCase { return targetMinimumExposureOffset } - cameraPlugin.getMinimumExposureOffset { offset, error in - XCTAssertEqual(offset?.doubleValue, targetMinimumExposureOffset) - XCTAssertNil(error) + cameraPlugin.getMinExposureOffset { result in + switch result { + case .success(let offset): + XCTAssertEqual(offset, targetMinimumExposureOffset) + case .failure: + XCTFail("Unexpected error") + } expectation.fulfill() } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPluginInitializeCameraTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPluginInitializeCameraTests.swift index 1eca0ec8c697..979ff895cfed 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPluginInitializeCameraTests.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPluginInitializeCameraTests.swift @@ -6,11 +6,6 @@ import XCTest @testable import camera_avfoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - final class CameraPluginInitializeCameraTests: XCTestCase { private func createCameraPlugin() -> ( CameraPlugin, MockCamera, MockGlobalEventApi, DispatchQueue @@ -24,7 +19,7 @@ final class CameraPluginInitializeCameraTests: XCTestCase { messenger: MockFlutterBinaryMessenger(), globalAPI: mockGlobalEventApi, deviceDiscoverer: MockCameraDeviceDiscoverer(), - permissionManager: MockFLTCameraPermissionManager(), + permissionManager: MockCameraPermissionManager(), deviceFactory: { _ in MockCaptureDevice() }, captureSessionFactory: { MockCaptureSession() }, captureDeviceInputFactory: MockCaptureDeviceInputFactory(), @@ -44,9 +39,9 @@ final class CameraPluginInitializeCameraTests: XCTestCase { onFrameAvailableSet = true } - cameraPlugin.initializeCamera(0, withImageFormat: FCPPlatformImageFormatGroup.bgra8888) { - error in - XCTAssertNil(error) + cameraPlugin.initialize(cameraId: 0, imageFormat: PlatformImageFormatGroup.bgra8888) { + result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -64,9 +59,9 @@ final class CameraPluginInitializeCameraTests: XCTestCase { dartAPISet = true } - cameraPlugin.initializeCamera(0, withImageFormat: FCPPlatformImageFormatGroup.bgra8888) { - error in - XCTAssertNil(error) + cameraPlugin.initialize(cameraId: 0, imageFormat: PlatformImageFormatGroup.bgra8888) { + result in + let _ = self.assertSuccess(result) expectation.fulfill() } @@ -78,9 +73,9 @@ final class CameraPluginInitializeCameraTests: XCTestCase { func testInitializeCamera_sendsDeviceOrientation() { let (cameraPlugin, _, mockGlobalEventApi, captureSessionQueue) = createCameraPlugin() - cameraPlugin.initializeCamera(0, withImageFormat: FCPPlatformImageFormatGroup.bgra8888) { - error in - XCTAssertNil(error) + cameraPlugin.initialize(cameraId: 0, imageFormat: PlatformImageFormatGroup.bgra8888) { + result in + let _ = self.assertSuccess(result) } waitForQueueRoundTrip(with: captureSessionQueue) @@ -97,9 +92,9 @@ final class CameraPluginInitializeCameraTests: XCTestCase { startCalled = true } - cameraPlugin.initializeCamera(0, withImageFormat: FCPPlatformImageFormatGroup.bgra8888) { - error in - XCTAssertNil(error) + cameraPlugin.initialize(cameraId: 0, imageFormat: PlatformImageFormatGroup.bgra8888) { + result in + let _ = self.assertSuccess(result) expectation.fulfill() } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPreviewPauseTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPreviewPauseTests.swift index c5424d1657bc..7803ec38ec0a 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPreviewPauseTests.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPreviewPauseTests.swift @@ -7,11 +7,6 @@ import XCTest @testable import camera_avfoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - final class CameraPreviewPauseTests: XCTestCase { func testPausePreviewWithResult_shouldPausePreview() { let camera = CameraTestUtils.createTestCamera() diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPropertiesTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPropertiesTests.swift index cf397b5dd8b0..bac0ce6ed19e 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPropertiesTests.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraPropertiesTests.swift @@ -8,30 +8,19 @@ import XCTest @testable import camera_avfoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - final class CameraPropertiesTests: XCTestCase { // MARK: - Flash Mode Tests func testGetAVCaptureFlashModeForPigeonFlashMode() { XCTAssertEqual( AVCaptureDevice.FlashMode.off, - FCPGetAVCaptureFlashModeForPigeonFlashMode(FCPPlatformFlashMode.off)) + getAVCaptureFlashMode(for: .off)) XCTAssertEqual( AVCaptureDevice.FlashMode.auto, - FCPGetAVCaptureFlashModeForPigeonFlashMode(FCPPlatformFlashMode.auto)) + getAVCaptureFlashMode(for: .auto)) XCTAssertEqual( AVCaptureDevice.FlashMode.on, - FCPGetAVCaptureFlashModeForPigeonFlashMode(FCPPlatformFlashMode.always)) - - // TODO(FirentisTFW): Migrate implementation to throw Swift error in this case. - let exception = ExceptionCatcher.catchException { - _ = FCPGetAVCaptureFlashModeForPigeonFlashMode(.torch) - } - XCTAssertNotNil(exception) + getAVCaptureFlashMode(for: .always)) } // MARK: - Video Format Tests @@ -39,10 +28,10 @@ final class CameraPropertiesTests: XCTestCase { func testGetPixelFormatForPigeonFormat() { XCTAssertEqual( kCVPixelFormatType_32BGRA, - FCPGetPixelFormatForPigeonFormat(FCPPlatformImageFormatGroup.bgra8888)) + getPixelFormat(for: .bgra8888)) XCTAssertEqual( kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, - FCPGetPixelFormatForPigeonFormat(FCPPlatformImageFormatGroup.yuv420)) + getPixelFormat(for: .yuv420)) } // MARK: - Device Orientation Tests @@ -50,37 +39,35 @@ final class CameraPropertiesTests: XCTestCase { func testGetUIDeviceOrientationForPigeonDeviceOrientation() { XCTAssertEqual( UIDeviceOrientation.portraitUpsideDown, - FCPGetUIDeviceOrientationForPigeonDeviceOrientation(FCPPlatformDeviceOrientation.portraitDown) + getUIDeviceOrientation(for: .portraitDown) ) XCTAssertEqual( UIDeviceOrientation.landscapeLeft, - FCPGetUIDeviceOrientationForPigeonDeviceOrientation( - FCPPlatformDeviceOrientation.landscapeLeft)) + getUIDeviceOrientation(for: .landscapeLeft)) XCTAssertEqual( UIDeviceOrientation.landscapeRight, - FCPGetUIDeviceOrientationForPigeonDeviceOrientation( - FCPPlatformDeviceOrientation.landscapeRight)) + getUIDeviceOrientation(for: .landscapeRight)) XCTAssertEqual( UIDeviceOrientation.portrait, - FCPGetUIDeviceOrientationForPigeonDeviceOrientation(FCPPlatformDeviceOrientation.portraitUp)) + getUIDeviceOrientation(for: .portraitUp)) } func testGetPigeonDeviceOrientationForUIDeviceOrientation() { XCTAssertEqual( - FCPPlatformDeviceOrientation.portraitDown, - FCPGetPigeonDeviceOrientationForOrientation(UIDeviceOrientation.portraitUpsideDown)) + PlatformDeviceOrientation.portraitDown, + getPigeonDeviceOrientation(for: .portraitUpsideDown)) XCTAssertEqual( - FCPPlatformDeviceOrientation.landscapeLeft, - FCPGetPigeonDeviceOrientationForOrientation(UIDeviceOrientation.landscapeLeft)) + PlatformDeviceOrientation.landscapeLeft, + getPigeonDeviceOrientation(for: .landscapeLeft)) XCTAssertEqual( - FCPPlatformDeviceOrientation.landscapeRight, - FCPGetPigeonDeviceOrientationForOrientation(UIDeviceOrientation.landscapeRight)) + PlatformDeviceOrientation.landscapeRight, + getPigeonDeviceOrientation(for: .landscapeRight)) XCTAssertEqual( - FCPPlatformDeviceOrientation.portraitUp, - FCPGetPigeonDeviceOrientationForOrientation(UIDeviceOrientation.portrait)) + PlatformDeviceOrientation.portraitUp, + getPigeonDeviceOrientation(for: .portrait)) // Test default case. XCTAssertEqual( - FCPPlatformDeviceOrientation.portraitUp, - FCPGetPigeonDeviceOrientationForOrientation(UIDeviceOrientation.unknown)) + PlatformDeviceOrientation.portraitUp, + getPigeonDeviceOrientation(for: .unknown)) } } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraSessionPresetsTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraSessionPresetsTests.swift index 43d02a8b5e6e..5d56567959f0 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraSessionPresetsTests.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraSessionPresetsTests.swift @@ -7,12 +7,7 @@ import XCTest @testable import camera_avfoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - -/// Includes test cases related to resolution presets setting operations for FLTCam class. +/// Includes test cases related to resolution presets setting operations for Camera class. final class CameraSessionPresetsTests: XCTestCase { func testResolutionPresetWithBestFormat_mustUpdateCaptureSessionPreset() { let expectedPreset = AVCaptureSession.Preset.inputPriority @@ -21,6 +16,7 @@ final class CameraSessionPresetsTests: XCTestCase { description: "Expected lockForConfiguration called") let videoSessionMock = MockCaptureSession() + videoSessionMock.canSetSessionPresetStub = { _ in true } videoSessionMock.setSessionPresetStub = { preset in if preset == expectedPreset { presetExpectation.fulfill() @@ -29,19 +25,22 @@ final class CameraSessionPresetsTests: XCTestCase { let captureFormatMock = MockCaptureDeviceFormat() let captureDeviceMock = MockCaptureDevice() captureDeviceMock.flutterFormats = [captureFormatMock] - captureDeviceMock.flutterActiveFormat = captureFormatMock + var currentFormat: CaptureDeviceFormat = captureFormatMock + captureDeviceMock.activeFormatStub = { + return currentFormat + } captureDeviceMock.lockForConfigurationStub = { lockForConfigurationExpectation.fulfill() } let configuration = CameraTestUtils.createTestCameraConfiguration() configuration.videoCaptureDeviceFactory = { _ in captureDeviceMock } - configuration.videoDimensionsConverter = { format in - return CMVideoDimensions(width: 1, height: 1) + configuration.videoDimensionsConverter = { _ in + return CMVideoDimensions(width: 4, height: 3) } configuration.videoCaptureSession = videoSessionMock configuration.mediaSettings = CameraTestUtils.createDefaultMediaSettings( - resolutionPreset: FCPPlatformResolutionPreset.max) + resolutionPreset: PlatformResolutionPreset.max) let _ = CameraTestUtils.createTestCamera(configuration) @@ -64,7 +63,7 @@ final class CameraSessionPresetsTests: XCTestCase { let configuration = CameraTestUtils.createTestCameraConfiguration() configuration.videoCaptureSession = videoSessionMock configuration.mediaSettings = CameraTestUtils.createDefaultMediaSettings( - resolutionPreset: FCPPlatformResolutionPreset.max) + resolutionPreset: PlatformResolutionPreset.max) configuration.videoCaptureDeviceFactory = { _ in MockCaptureDevice() } let _ = CameraTestUtils.createTestCamera(configuration) @@ -89,7 +88,7 @@ final class CameraSessionPresetsTests: XCTestCase { let configuration = CameraTestUtils.createTestCameraConfiguration() configuration.videoCaptureSession = videoSessionMock configuration.mediaSettings = CameraTestUtils.createDefaultMediaSettings( - resolutionPreset: FCPPlatformResolutionPreset.ultraHigh) + resolutionPreset: PlatformResolutionPreset.ultraHigh) let _ = CameraTestUtils.createTestCamera(configuration) diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraSetDeviceOrientationTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraSetDeviceOrientationTests.swift new file mode 100644 index 000000000000..c6ca992d236b --- /dev/null +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraSetDeviceOrientationTests.swift @@ -0,0 +1,108 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import AVFoundation +import XCTest + +@testable import camera_avfoundation + +final class CameraSetDeviceOrientationTests: XCTestCase { + private func createCamera() -> (Camera, MockCaptureConnection, MockCaptureConnection) { + let camera = CameraTestUtils.createTestCamera() + + let mockCapturePhotoOutput = MockCapturePhotoOutput() + let mockPhotoCaptureConnection = MockCaptureConnection() + mockPhotoCaptureConnection.isVideoOrientationSupported = true + + mockCapturePhotoOutput.connectionWithMediaTypeStub = { _ in mockPhotoCaptureConnection } + camera.capturePhotoOutput = mockCapturePhotoOutput + + let mockCaptureVideoDataOutput = MockCaptureVideoDataOutput() + let mockVideoCaptureConnection = MockCaptureConnection() + mockVideoCaptureConnection.isVideoOrientationSupported = true + + mockCaptureVideoDataOutput.connectionWithMediaTypeStub = { _ in mockVideoCaptureConnection } + camera.captureVideoOutput = mockCaptureVideoDataOutput + + return (camera, mockPhotoCaptureConnection, mockVideoCaptureConnection) + } + + func testSetDeviceOrientation_setsOrientationsOfCaptureConnections() { + let (camera, mockPhotoCaptureConnection, mockVideoCaptureConnection) = createCamera() + var photoSetVideoOrientationCalled = false + mockPhotoCaptureConnection.setVideoOrientationStub = { orientation in + // Device orientation is flipped compared to video orientation. When UIDeviceOrientation + // is landscape left the video orientation should be landscape right. + XCTAssertEqual(orientation, .landscapeRight) + photoSetVideoOrientationCalled = true + } + + var videoSetVideoOrientationCalled = false + mockVideoCaptureConnection.setVideoOrientationStub = { orientation in + // Device orientation is flipped compared to video orientation. When UIDeviceOrientation + // is landscape left the video orientation should be landscape right. + XCTAssertEqual(orientation, .landscapeRight) + videoSetVideoOrientationCalled = true + } + + camera.deviceOrientation = .landscapeLeft + + XCTAssertTrue(photoSetVideoOrientationCalled) + XCTAssertTrue(videoSetVideoOrientationCalled) + } + + func + testSetDeviceOrientation_setsLockedOrientationsOfCaptureConnection_ifCaptureOrientationIsLocked() + { + let (camera, mockPhotoCaptureConnection, mockVideoCaptureConnection) = createCamera() + var photoSetVideoOrientationCalled = false + mockPhotoCaptureConnection.setVideoOrientationStub = { orientation in + XCTAssertEqual(orientation, .portraitUpsideDown) + photoSetVideoOrientationCalled = true + } + + var videoSetVideoOrientationCalled = false + mockVideoCaptureConnection.setVideoOrientationStub = { orientation in + XCTAssertEqual(orientation, .portraitUpsideDown) + videoSetVideoOrientationCalled = true + } + + camera.lockCaptureOrientation(PlatformDeviceOrientation.portraitDown) + + camera.deviceOrientation = .landscapeLeft + + XCTAssertTrue(photoSetVideoOrientationCalled) + XCTAssertTrue(videoSetVideoOrientationCalled) + } + + func testSetDeviceOrientation_doesNotSetOrientations_ifRecordingIsInProgress() { + let (camera, mockPhotoCaptureConnection, mockVideoCaptureConnection) = createCamera() + + camera.startVideoRecording(completion: { _ in }, messengerForStreaming: nil) + + mockPhotoCaptureConnection.setVideoOrientationStub = { _ in XCTFail() } + mockVideoCaptureConnection.setVideoOrientationStub = { _ in XCTFail() } + + camera.deviceOrientation = .landscapeLeft + } + + func testSetDeviceOrientation_doesNotSetOrientations_forDuplicateUpdates() { + let (camera, mockPhotoCaptureConnection, mockVideoCaptureConnection) = createCamera() + var photoSetVideoOrientationCallCount = 0 + mockPhotoCaptureConnection.setVideoOrientationStub = { _ in + photoSetVideoOrientationCallCount += 1 + } + + var videoSetVideoOrientationCallCount = 0 + mockVideoCaptureConnection.setVideoOrientationStub = { _ in + videoSetVideoOrientationCallCount += 1 + } + + camera.deviceOrientation = .landscapeRight + camera.deviceOrientation = .landscapeRight + + XCTAssertEqual(photoSetVideoOrientationCallCount, 1) + XCTAssertEqual(videoSetVideoOrientationCallCount, 1) + } +} diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraSetFlashModeTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraSetFlashModeTests.swift new file mode 100644 index 000000000000..7a931a7f1e25 --- /dev/null +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraSetFlashModeTests.swift @@ -0,0 +1,168 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import AVFoundation +import XCTest + +@testable import camera_avfoundation + +final class CameraSetFlashModeTests: XCTestCase { + private func createCamera() -> (Camera, MockCaptureDevice, MockCapturePhotoOutput) { + let mockDevice = MockCaptureDevice() + let mockCapturePhotoOutput = MockCapturePhotoOutput() + + let configuration = CameraTestUtils.createTestCameraConfiguration() + configuration.videoCaptureDeviceFactory = { _ in mockDevice } + let camera = CameraTestUtils.createTestCamera(configuration) + camera.capturePhotoOutput = mockCapturePhotoOutput + + return (camera, mockDevice, mockCapturePhotoOutput) + } + + func testSetFlashModeWithTorchMode_setsTrochModeOn() { + let (camera, mockDevice, _) = createCamera() + + mockDevice.hasTorch = true + mockDevice.isTorchAvailable = true + + var setTorchModeCalled = false + mockDevice.setTorchModeStub = { torchMode in + XCTAssertEqual(torchMode, .on) + setTorchModeCalled = true + } + + let expectation = expectation(description: "Call completed") + + camera.setFlashMode(.torch) { + result in + let _ = self.assertSuccess(result) + expectation.fulfill() + } + + waitForExpectations(timeout: 30) + + XCTAssertTrue(setTorchModeCalled) + } + + func testSetFlashModeWithTorchMode_returnError_ifHasNoTorch() { + let (camera, mockDevice, _) = createCamera() + + mockDevice.hasTorch = false + + let expectation = expectation(description: "Call completed") + + camera.setFlashMode(.torch) { result in + switch result { + case .failure(let error as PigeonError): + XCTAssertEqual(error.code, "setFlashModeFailed") + XCTAssertEqual(error.message, "Device does not support torch mode") + default: + XCTFail("Expected failure") + } + expectation.fulfill() + } + + waitForExpectations(timeout: 30) + } + + func testSetFlashModeWithTorchMode_returnError_ifTorchIsNotAvailable() { + let (camera, mockDevice, _) = createCamera() + + mockDevice.hasTorch = true + mockDevice.isTorchAvailable = false + + let expectation = expectation(description: "Call completed") + + camera.setFlashMode(.torch) { result in + switch result { + case .failure(let error as PigeonError): + XCTAssertEqual(error.code, "setFlashModeFailed") + XCTAssertEqual(error.message, "Torch mode is currently not available") + default: + XCTFail("Expected failure") + } + expectation.fulfill() + } + + waitForExpectations(timeout: 30) + } + + func testSetFlashModeWithNonTorchMode_setsTrochModeOff_ifTorchModeIsEnabled() { + let (camera, mockDevice, mockCapturePhotoOutput) = createCamera() + + mockCapturePhotoOutput.supportedFlashModes = [.auto] + + mockDevice.hasFlash = true + // Torch mode is enabled + mockDevice.getTorchModeStub = { .on } + + var setTorchModeCalled = false + mockDevice.setTorchModeStub = { torchMode in + XCTAssertEqual(torchMode, .off) + setTorchModeCalled = true + } + + let expectation = expectation(description: "Call completed") + + camera.setFlashMode(.auto) { + result in + switch result { + case .success: + break + case .failure: + XCTFail("Unexpected failure") + } + expectation.fulfill() + } + + waitForExpectations(timeout: 30) + + XCTAssertTrue(setTorchModeCalled) + } + + func testSetFlashModeWithNonTorchMode_returnError_ifHasNoFlash() { + let (camera, mockDevice, _) = createCamera() + + mockDevice.hasFlash = false + + let expectation = expectation(description: "Call completed") + + camera.setFlashMode(.auto) { result in + switch result { + case .failure(let error as PigeonError): + XCTAssertEqual(error.code, "setFlashModeFailed") + XCTAssertEqual(error.message, "Device does not have flash capabilities") + default: + XCTFail("Expected failure") + } + expectation.fulfill() + } + + waitForExpectations(timeout: 30) + } + + func testSetFlashModeWithNonTorchMode_returnError_ifModeIsNotSupported() { + let (camera, mockDevice, mockCapturePhotoOutput) = createCamera() + + // No flash modes are supported + mockCapturePhotoOutput.supportedFlashModes = [] + + mockDevice.hasFlash = true + + let expectation = expectation(description: "Call completed") + + camera.setFlashMode(.auto) { result in + switch result { + case .failure(let error as PigeonError): + XCTAssertEqual(error.code, "setFlashModeFailed") + XCTAssertEqual(error.message, "Device does not support this specific flash mode") + default: + XCTFail("Expected failure") + } + expectation.fulfill() + } + + waitForExpectations(timeout: 30) + } +} diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraSetFocusModeTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraSetFocusModeTests.swift new file mode 100644 index 000000000000..75c1cf38e6fb --- /dev/null +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraSetFocusModeTests.swift @@ -0,0 +1,166 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import AVFoundation +import XCTest + +@testable import camera_avfoundation + +final class CameraSetFocusModeTests: XCTestCase { + private func createCamera() -> (Camera, MockCaptureDevice, MockDeviceOrientationProvider) { + let mockDevice = MockCaptureDevice() + let mockDeviceOrientationProvider = MockDeviceOrientationProvider() + + let configuration = CameraTestUtils.createTestCameraConfiguration() + configuration.videoCaptureDeviceFactory = { _ in mockDevice } + configuration.deviceOrientationProvider = mockDeviceOrientationProvider + let camera = CameraTestUtils.createTestCamera(configuration) + + return (camera, mockDevice, mockDeviceOrientationProvider) + } + + func testAutoFocusWithContinuousModeSupported_ShouldSetContinuousAutoFocus() { + let (camera, mockDevice, _) = createCamera() + // AVCaptureFocusModeContinuousAutoFocus and AVCaptureFocusModeAutoFocus are supported. + mockDevice.isFocusModeSupportedStub = { mode in + mode == .continuousAutoFocus || mode == .autoFocus + } + + var setFocusModeContinuousAutoFocusCalled = false + + mockDevice.setFocusModeStub = { mode in + // Don't expect setFocusMode:AVCaptureFocusModeAutoFocus. + if mode == .autoFocus { + XCTFail("Unexpected call to setFocusMode") + } else if mode == .continuousAutoFocus { + setFocusModeContinuousAutoFocusCalled = true + } + } + + camera.setFocusMode(.auto) + + XCTAssertTrue(setFocusModeContinuousAutoFocusCalled) + } + + func testAutoFocusWithContinuousModeNotSupported_ShouldSetAutoFocus() { + let (camera, mockDevice, _) = createCamera() + // AVCaptureFocusModeContinuousAutoFocus is not supported. + // AVCaptureFocusModeAutoFocus is supported. + mockDevice.isFocusModeSupportedStub = { mode in + mode == .autoFocus + } + + var setFocusModeAutoFocusCalled = false + + // Don't expect setFocusMode:AVCaptureFocusModeContinuousAutoFocus. + mockDevice.setFocusModeStub = { mode in + if mode == .continuousAutoFocus { + XCTFail("Unexpected call to setFocusMode") + } else if mode == .autoFocus { + setFocusModeAutoFocusCalled = true + } + } + + camera.setFocusMode(.auto) + + XCTAssertTrue(setFocusModeAutoFocusCalled) + } + + func testAutoFocusWithNoModeSupported_ShouldSetNothing() { + let (camera, mockDevice, _) = createCamera() + // No modes are supported. + mockDevice.isFocusModeSupportedStub = { _ in + false + } + + // Don't expect any setFocus. + mockDevice.setFocusModeStub = { + _ in XCTFail("Unexpected call to setFocusMode") + } + + camera.setFocusMode(.auto) + } + + func testLockedFocusWithModeSupported_ShouldSetModeAutoFocus() { + let (camera, mockDevice, _) = createCamera() + // AVCaptureFocusModeContinuousAutoFocus and AVCaptureFocusModeAutoFocus are supported. + mockDevice.isFocusModeSupportedStub = { mode in + mode == .continuousAutoFocus || mode == .autoFocus + } + + var setFocusModeAutoFocusCalled = false + + // AVCaptureFocusModeAutoFocus automatically adjusts the focus one time, and then locks focus + mockDevice.setFocusModeStub = { mode in + if mode == .continuousAutoFocus { + XCTFail("Unexpected call to setFocusMode") + } else if mode == .autoFocus { + setFocusModeAutoFocusCalled = true + } + } + + camera.setFocusMode(.locked) + + XCTAssertTrue(setFocusModeAutoFocusCalled) + } + + func testLockedFocusWithModeNotSupported_ShouldSetNothing() { + let (camera, mockDevice, _) = createCamera() + mockDevice.isFocusModeSupportedStub = { mode in + mode == .continuousAutoFocus + } + + // Don't expect any setFocus. + mockDevice.setFocusModeStub = { _ in + XCTFail("Unexpected call to setFocusMode") + } + + camera.setFocusMode(.locked) + } + + func testSetFocusPointWithResult_SetsFocusPointOfInterest() { + let (camera, mockDevice, mockDeviceOrientationProvider) = createCamera() + // UI is currently in landscape left orientation. + mockDeviceOrientationProvider.orientationStub = { .landscapeLeft } + // Focus point of interest is supported. + mockDevice.isFocusPointOfInterestSupported = true + + var setFocusPointOfInterestCalled = false + mockDevice.setFocusPointOfInterestStub = { point in + if point == CGPoint(x: 1.0, y: 1.0) { + setFocusPointOfInterestCalled = true + } + } + + camera.setFocusPoint(PlatformPoint(x: 1, y: 1)) { + result in + let _ = self.assertSuccess(result) + } + + XCTAssertTrue(setFocusPointOfInterestCalled) + } + + func testSetFocusPoint_WhenNotSupported_ReturnsError() { + let (camera, mockDevice, mockDeviceOrientationProvider) = createCamera() + // UI is currently in landscape left orientation. + mockDeviceOrientationProvider.orientationStub = { .landscapeLeft } + // Focus point of interest is not supported. + mockDevice.isFocusPointOfInterestSupported = false + + let expectation = self.expectation(description: "Completion with error") + + camera.setFocusPoint(PlatformPoint(x: 1, y: 1)) { result in + switch result { + case .failure(let error as PigeonError): + XCTAssertEqual(error.code, "setFocusPointFailed") + XCTAssertEqual(error.message, "Device does not have focus point capabilities") + default: + XCTFail("Expected failure") + } + expectation.fulfill() + } + + waitForExpectations(timeout: 30, handler: nil) + } +} diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraSettingsTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraSettingsTests.swift index 8729b3f4fb13..0c9f45e5e50a 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraSettingsTests.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraSettingsTests.swift @@ -3,19 +3,15 @@ // found in the LICENSE file. import AVFoundation +import Flutter import XCTest @testable import camera_avfoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - -private let testResolutionPreset = FCPPlatformResolutionPreset.medium -private let testFramesPerSecond = 15 -private let testVideoBitrate = 200000 -private let testAudioBitrate = 32000 +private let testResolutionPreset = PlatformResolutionPreset.medium +private let testFramesPerSecond: Int64 = 15 +private let testVideoBitrate: Int64 = 200000 +private let testAudioBitrate: Int64 = 32000 private final class TestMediaSettingsAVWrapper: FLTCamMediaSettingsAVWrapper { let lockExpectation: XCTestExpectation @@ -56,7 +52,7 @@ private final class TestMediaSettingsAVWrapper: FLTCamMediaSettingsAVWrapper { } override func setMinFrameDuration(_ duration: CMTime, on captureDevice: CaptureDevice) { - // FLTCam allows to set frame rate with 1/10 precision. + // Camera allows to set frame rate with 1/10 precision. let expectedDuration = CMTimeMake(value: 10, timescale: Int32(testFramesPerSecond * 10)) if duration == expectedDuration { minFrameDurationExpectation.fulfill() @@ -64,7 +60,7 @@ private final class TestMediaSettingsAVWrapper: FLTCamMediaSettingsAVWrapper { } override func setMaxFrameDuration(_ duration: CMTime, on captureDevice: CaptureDevice) { - // FLTCam allows to set frame rate with 1/10 precision. + // Camera allows to set frame rate with 1/10 precision. let expectedDuration = CMTimeMake(value: 10, timescale: Int32(testFramesPerSecond * 10)) if duration == expectedDuration { maxFrameDurationExpectation.fulfill() @@ -72,22 +68,23 @@ private final class TestMediaSettingsAVWrapper: FLTCamMediaSettingsAVWrapper { } override func assetWriterAudioInput(withOutputSettings outputSettings: [String: Any]?) - -> FLTAssetWriterInput + -> AssetWriterInput { - if let bitrate = outputSettings?[AVEncoderBitRateKey] as? Int, bitrate == testAudioBitrate { + if let bitrate = outputSettings?[AVEncoderBitRateKey] as? Int, bitrate == Int(testAudioBitrate) + { audioSettingsExpectation.fulfill() } return MockAssetWriterInput() } override func assetWriterVideoInput(withOutputSettings outputSettings: [String: Any]?) - -> FLTAssetWriterInput + -> AssetWriterInput { if let compressionProperties = outputSettings?[AVVideoCompressionPropertiesKey] as? [String: Any], let bitrate = compressionProperties[AVVideoAverageBitRateKey] as? Int, - let frameRate = compressionProperties[AVVideoExpectedSourceFrameRateKey] as? Int, - bitrate == testVideoBitrate, frameRate == testFramesPerSecond + let frameRate = compressionProperties[AVVideoExpectedSourceFrameRateKey] as? Double, + bitrate == testVideoBitrate, frameRate == Double(testFramesPerSecond) { videoSettingsExpectation.fulfill() } @@ -101,7 +98,7 @@ private final class TestMediaSettingsAVWrapper: FLTCamMediaSettingsAVWrapper { return MockAssetWriterInput() } - override func addInput(_ writerInput: FLTAssetWriterInput, to writer: FLTAssetWriter) { + override func addInput(_ writerInput: AssetWriterInput, to writer: AssetWriter) { // No-op. } @@ -115,11 +112,11 @@ private final class TestMediaSettingsAVWrapper: FLTCamMediaSettingsAVWrapper { final class CameraSettingsTests: XCTestCase { func testSettings_shouldPassConfigurationToCameraDeviceAndWriter() { let enableAudio: Bool = true - let settings = FCPPlatformMediaSettings.make( - with: testResolutionPreset, - framesPerSecond: NSNumber(value: testFramesPerSecond), - videoBitrate: NSNumber(value: testVideoBitrate), - audioBitrate: NSNumber(value: testAudioBitrate), + let settings = PlatformMediaSettings( + resolutionPreset: testResolutionPreset, + framesPerSecond: testFramesPerSecond, + videoBitrate: testVideoBitrate, + audioBitrate: testAudioBitrate, enableAudio: enableAudio ) let injectedWrapper = TestMediaSettingsAVWrapper(test: self, expectAudio: enableAudio) @@ -161,7 +158,7 @@ final class CameraSettingsTests: XCTestCase { messenger: MockFlutterBinaryMessenger(), globalAPI: MockGlobalEventApi(), deviceDiscoverer: MockCameraDeviceDiscoverer(), - permissionManager: MockFLTCameraPermissionManager(), + permissionManager: MockCameraPermissionManager(), deviceFactory: { _ in mockDevice }, captureSessionFactory: { mockSession }, captureDeviceInputFactory: MockCaptureDeviceInputFactory(), @@ -169,20 +166,19 @@ final class CameraSettingsTests: XCTestCase { ) let expectation = self.expectation(description: "Result finished") - let mediaSettings = FCPPlatformMediaSettings.make( - with: testResolutionPreset, - framesPerSecond: NSNumber(value: testFramesPerSecond), - videoBitrate: NSNumber(value: testVideoBitrate), - audioBitrate: NSNumber(value: testAudioBitrate), + let mediaSettings = PlatformMediaSettings( + resolutionPreset: testResolutionPreset, + framesPerSecond: testFramesPerSecond, + videoBitrate: testVideoBitrate, + audioBitrate: testAudioBitrate, enableAudio: false ) - var resultValue: NSNumber? + var resultValue: Int64? camera.createCameraOnSessionQueue( withName: "acamera", settings: mediaSettings - ) { result, error in - XCTAssertNil(error) - resultValue = result + ) { result in + resultValue = self.assertSuccess(result) expectation.fulfill() } @@ -191,11 +187,11 @@ final class CameraSettingsTests: XCTestCase { } func testSettings_ShouldSelectFormatWhichSupports60FPS() { - let settings = FCPPlatformMediaSettings.make( - with: testResolutionPreset, - framesPerSecond: NSNumber(value: 60), - videoBitrate: NSNumber(value: testVideoBitrate), - audioBitrate: NSNumber(value: testAudioBitrate), + let settings = PlatformMediaSettings( + resolutionPreset: testResolutionPreset, + framesPerSecond: 60, + videoBitrate: testVideoBitrate, + audioBitrate: testAudioBitrate, enableAudio: false ) @@ -203,16 +199,17 @@ final class CameraSettingsTests: XCTestCase { configuration.mediaSettings = settings let camera = CameraTestUtils.createTestCamera(configuration) - let range = camera.captureDevice.flutterActiveFormat.videoSupportedFrameRateRanges[0] + let range = camera.captureDevice.flutterActiveFormat.flutterVideoSupportedFrameRateRanges[0] XCTAssertLessThanOrEqual(range.minFrameRate, 60) XCTAssertGreaterThanOrEqual(range.maxFrameRate, 60) } + func test_setUpCaptureSessionForAudioIfNeeded_skipsAudioSession_whenAudioDisabled() { - let settings = FCPPlatformMediaSettings.make( - with: testResolutionPreset, - framesPerSecond: NSNumber(value: testFramesPerSecond), - videoBitrate: NSNumber(value: testVideoBitrate), - audioBitrate: NSNumber(value: testAudioBitrate), + let settings = PlatformMediaSettings( + resolutionPreset: testResolutionPreset, + framesPerSecond: testFramesPerSecond, + videoBitrate: testVideoBitrate, + audioBitrate: testAudioBitrate, enableAudio: false ) @@ -255,11 +252,11 @@ final class CameraSettingsTests: XCTestCase { } func test_setUpCaptureSessionForAudioIfNeeded_addsAudioSession_whenAudioEnabled() { - let settings = FCPPlatformMediaSettings.make( - with: testResolutionPreset, - framesPerSecond: NSNumber(value: testFramesPerSecond), - videoBitrate: NSNumber(value: testVideoBitrate), - audioBitrate: NSNumber(value: testAudioBitrate), + let settings = PlatformMediaSettings( + resolutionPreset: testResolutionPreset, + framesPerSecond: testFramesPerSecond, + videoBitrate: testVideoBitrate, + audioBitrate: testAudioBitrate, enableAudio: true ) @@ -300,4 +297,60 @@ final class CameraSettingsTests: XCTestCase { "Audio session should receive AVCaptureAudioDataOutput when enableAudio is true" ) } + + func testResolutionPresetWithMax_mustIgnoreLossyFormatsAndSquares() { + let videoSessionMock = MockCaptureSession() + videoSessionMock.canSetSessionPresetStub = { _ in true } + + let lossyFormat = MockCaptureDeviceFormat( + codecType: 1_651_798_066, // 'btp2' + width: 4224, + height: 3024 + ) + let squareFormat = MockCaptureDeviceFormat( + codecType: kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, + width: 4032, + height: 4032 + ) + let safe4KFormat = MockCaptureDeviceFormat( + codecType: kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, + width: 3840, + height: 2160 + ) + + let captureDeviceMock = MockCaptureDevice() + captureDeviceMock.flutterFormats = [lossyFormat, squareFormat, safe4KFormat] + + var currentFormat: CaptureDeviceFormat = safe4KFormat + captureDeviceMock.activeFormatStub = { currentFormat } + captureDeviceMock.setActiveFormatStub = { newFormat in currentFormat = newFormat } + + let configuration = CameraTestUtils.createTestCameraConfiguration() + configuration.videoCaptureDeviceFactory = { _ in captureDeviceMock } + configuration.videoCaptureSession = videoSessionMock + + configuration.videoDimensionsConverter = { format in + return CMVideoFormatDescriptionGetDimensions(format.formatDescription) + } + + configuration.mediaSettings = CameraTestUtils.createDefaultMediaSettings( + resolutionPreset: PlatformResolutionPreset.max + ) + + let _ = CameraTestUtils.createTestCamera(configuration) + + let selectedFormat = captureDeviceMock.flutterActiveFormat + let selectedDimensions = CMVideoFormatDescriptionGetDimensions(selectedFormat.formatDescription) + + XCTAssertEqual( + selectedDimensions.width, + 3840, + "Camera should have ignored the lossy and square formats, safely falling back to 4K." + ) + XCTAssertEqual( + selectedDimensions.height, + 2160, + "Camera should have ignored the lossy and square formats, safely falling back to 4K." + ) + } } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraTestUtils.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraTestUtils.swift index 10a7802cca2b..a46d23cfe7b1 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraTestUtils.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraTestUtils.swift @@ -2,24 +2,20 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import AVFoundation import XCTest @testable import camera_avfoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - /// Utils for creating default class instances used in tests enum CameraTestUtils { /// This method provides a convenient way to create media settings with minimal configuration. /// Audio is enabled by default, while other parameters use platform-specific defaults. - static func createDefaultMediaSettings(resolutionPreset: FCPPlatformResolutionPreset) - -> FCPPlatformMediaSettings + static func createDefaultMediaSettings(resolutionPreset: PlatformResolutionPreset) + -> PlatformMediaSettings { - return FCPPlatformMediaSettings.make( - with: resolutionPreset, + return PlatformMediaSettings( + resolutionPreset: resolutionPreset, framesPerSecond: nil, videoBitrate: nil, audioBitrate: nil, @@ -39,17 +35,17 @@ enum CameraTestUtils { let frameRateRangeMock1 = MockFrameRateRange.init(minFrameRate: 3, maxFrameRate: 30) let captureDeviceFormatMock1 = MockCaptureDeviceFormat() - captureDeviceFormatMock1.videoSupportedFrameRateRanges = [frameRateRangeMock1] + captureDeviceFormatMock1.flutterVideoSupportedFrameRateRanges = [frameRateRangeMock1] let frameRateRangeMock2 = MockFrameRateRange.init(minFrameRate: 3, maxFrameRate: 60) let captureDeviceFormatMock2 = MockCaptureDeviceFormat() - captureDeviceFormatMock2.videoSupportedFrameRateRanges = [frameRateRangeMock2] + captureDeviceFormatMock2.flutterVideoSupportedFrameRateRanges = [frameRateRangeMock2] let captureDeviceMock = MockCaptureDevice() captureDeviceMock.flutterFormats = [captureDeviceFormatMock1, captureDeviceFormatMock2] - var currentFormat: FLTCaptureDeviceFormat = captureDeviceFormatMock1 + var currentFormat: CaptureDeviceFormat = captureDeviceFormatMock1 captureDeviceMock.activeFormatStub = { currentFormat } captureDeviceMock.setActiveFormatStub = { format in @@ -58,7 +54,7 @@ enum CameraTestUtils { let configuration = CameraConfiguration( mediaSettings: createDefaultMediaSettings( - resolutionPreset: FCPPlatformResolutionPreset.medium), + resolutionPreset: PlatformResolutionPreset.medium), mediaSettingsWrapper: FLTCamMediaSettingsAVWrapper(), captureDeviceFactory: { _ in captureDeviceMock }, audioCaptureDeviceFactory: { MockCaptureDevice() }, @@ -99,7 +95,10 @@ enum CameraTestUtils { /// Creates a test sample buffer. /// @return a test sample buffer. - static func createTestSampleBuffer() -> CMSampleBuffer { + static func createTestSampleBuffer( + timestamp: CMTime = .zero, + duration: CMTime = CMTimeMake(value: 1, timescale: 44100) + ) -> CMSampleBuffer { var pixelBuffer: CVPixelBuffer? CVPixelBufferCreate(kCFAllocatorDefault, 100, 100, kCVPixelFormatType_32BGRA, nil, &pixelBuffer) @@ -110,9 +109,9 @@ enum CameraTestUtils { formatDescriptionOut: &formatDescription) var timingInfo = CMSampleTimingInfo( - duration: CMTimeMake(value: 1, timescale: 44100), - presentationTimeStamp: CMTime.zero, - decodeTimeStamp: CMTime.invalid) + duration: duration, + presentationTimeStamp: timestamp, + decodeTimeStamp: .invalid) var sampleBuffer: CMSampleBuffer? CMSampleBufferCreateReadyWithImageBuffer( @@ -127,22 +126,25 @@ enum CameraTestUtils { /// Creates a test audio sample buffer. /// @return a test audio sample buffer. - static func createTestAudioSampleBuffer() -> CMSampleBuffer { + static func createTestAudioSampleBuffer( + timestamp: CMTime = .zero, + duration: CMTime = CMTimeMake(value: 1, timescale: 44100) + ) -> CMSampleBuffer { var blockBuffer: CMBlockBuffer? CMBlockBufferCreateWithMemoryBlock( allocator: kCFAllocatorDefault, memoryBlock: nil, - blockLength: 100, + blockLength: Int(duration.value), blockAllocator: kCFAllocatorDefault, customBlockSource: nil, offsetToData: 0, - dataLength: 100, + dataLength: Int(duration.value), flags: kCMBlockBufferAssureMemoryNowFlag, blockBufferOut: &blockBuffer) var formatDescription: CMFormatDescription? var basicDescription = AudioStreamBasicDescription( - mSampleRate: 44100, + mSampleRate: Float64(duration.timescale), mFormatID: kAudioFormatLinearPCM, mFormatFlags: 0, mBytesPerPacket: 1, @@ -167,8 +169,8 @@ enum CameraTestUtils { allocator: kCFAllocatorDefault, dataBuffer: blockBuffer!, formatDescription: formatDescription!, - sampleCount: 1, - presentationTimeStamp: .zero, + sampleCount: CMItemCount(duration.value), + presentationTimeStamp: timestamp, packetDescriptions: nil, sampleBufferOut: &sampleBuffer) @@ -202,4 +204,16 @@ extension XCTestCase { wait(for: [expectation], timeout: 1) } + + func assertSuccess( + _ result: Result, file: StaticString = #file, line: UInt = #line + ) -> T? { + switch result { + case .success(let value): + return value + case .failure(let error): + XCTFail("Expected success, but got failure: \(error)", file: file, line: line) + return nil + } + } } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraUtilTests.m b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraUtilTests.m deleted file mode 100644 index 7bfba21507c2..000000000000 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraUtilTests.m +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -@import camera_avfoundation; -@import XCTest; -@import AVFoundation; -#import - -@interface FLTCam : NSObject - -- (CGPoint)getCGPointForCoordsWithOrientation:(UIDeviceOrientation)orientation - x:(double)x - y:(double)y; - -@end - -@interface CameraUtilTests : XCTestCase -@property(readonly, nonatomic) FLTCam *camera; - -@end - -@implementation CameraUtilTests - -- (void)setUp { - _camera = [[FLTCam alloc] init]; -} - -- (void)testGetCGPointForCoordsWithOrientation_ShouldRotateCoords { - CGPoint point; - point = [_camera getCGPointForCoordsWithOrientation:UIDeviceOrientationLandscapeLeft x:1 y:1]; - XCTAssertTrue(CGPointEqualToPoint(point, CGPointMake(1, 1)), - @"Resulting coordinates are invalid."); - point = [_camera getCGPointForCoordsWithOrientation:UIDeviceOrientationPortrait x:0 y:1]; - XCTAssertTrue(CGPointEqualToPoint(point, CGPointMake(1, 1)), - @"Resulting coordinates are invalid."); - point = [_camera getCGPointForCoordsWithOrientation:UIDeviceOrientationLandscapeRight x:0 y:0]; - XCTAssertTrue(CGPointEqualToPoint(point, CGPointMake(1, 1)), - @"Resulting coordinates are invalid."); - point = [_camera getCGPointForCoordsWithOrientation:UIDeviceOrientationPortraitUpsideDown - x:1 - y:0]; - XCTAssertTrue(CGPointEqualToPoint(point, CGPointMake(1, 1)), - @"Resulting coordinates are invalid."); -} - -@end diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraZoomTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraZoomTests.swift new file mode 100644 index 000000000000..f0c62add69fb --- /dev/null +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/CameraZoomTests.swift @@ -0,0 +1,111 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import AVFoundation +import XCTest + +@testable import camera_avfoundation + +final class CameraZoomTests: XCTestCase { + private func createCamera() -> (Camera, MockCaptureDevice) { + let mockDevice = MockCaptureDevice() + + let configuration = CameraTestUtils.createTestCameraConfiguration() + configuration.videoCaptureDeviceFactory = { _ in mockDevice } + let camera = CameraTestUtils.createTestCamera(configuration) + + return (camera, mockDevice) + } + + func testSetZoomLevel_setVideoZoomFactor() { + let (camera, mockDevice) = createCamera() + + mockDevice.maxAvailableVideoZoomFactor = 2.0 + mockDevice.minAvailableVideoZoomFactor = 0.0 + + let targetZoom = CGFloat(1.0) + + var setVideoZoomFactorCalled = false + mockDevice.setVideoZoomFactorStub = { zoom in + XCTAssertEqual(zoom, targetZoom) + setVideoZoomFactorCalled = true + } + + let expectation = expectation(description: "Call completed") + + camera.setZoomLevel(targetZoom) { + result in + let _ = self.assertSuccess(result) + expectation.fulfill() + } + + waitForExpectations(timeout: 30) + + XCTAssertTrue(setVideoZoomFactorCalled) + } + + func testSetZoomLevel_returnsError_forZoomLevelBlowMinimum() { + let (camera, mockDevice) = createCamera() + + // Allowed zoom range between 2.0 and 3.0 + mockDevice.maxAvailableVideoZoomFactor = 2.0 + mockDevice.minAvailableVideoZoomFactor = 3.0 + + let expectation = expectation(description: "Call completed") + + camera.setZoomLevel(CGFloat(1.0)) { result in + switch result { + case .failure(let error as PigeonError): + XCTAssertEqual(error.code, "ZOOM_ERROR") + default: + XCTFail("Expected failure") + } + expectation.fulfill() + } + + waitForExpectations(timeout: 30) + } + + func testSetZoomLevel_returnsError_forZoomLevelAboveMaximum() { + let (camera, mockDevice) = createCamera() + + // Allowed zoom range between 0.0 and 1.0 + mockDevice.maxAvailableVideoZoomFactor = 0.0 + mockDevice.minAvailableVideoZoomFactor = 1.0 + + let expectation = expectation(description: "Call completed") + + camera.setZoomLevel(CGFloat(2.0)) { result in + switch result { + case .failure(let error as PigeonError): + XCTAssertEqual(error.code, "ZOOM_ERROR") + default: + XCTFail("Expected failure") + } + expectation.fulfill() + } + + waitForExpectations(timeout: 30) + } + + func testMaximumAvailableZoomFactor_returnsDeviceMaxAvailableVideoZoomFactor() { + let (camera, mockDevice) = createCamera() + + let targetZoom = CGFloat(1.0) + + mockDevice.maxAvailableVideoZoomFactor = CGFloat(targetZoom) + + XCTAssertEqual(camera.maximumAvailableZoomFactor, targetZoom) + } + + func testMinimumAvailableZoomFactor_returnsDeviceMinAvailableVideoZoomFactor() { + let (camera, mockDevice) = createCamera() + + let targetZoom = CGFloat(1.0) + + mockDevice.minAvailableVideoZoomFactor = CGFloat(targetZoom) + + XCTAssertEqual(camera.minimumAvailableZoomFactor, targetZoom) + } +} diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/ExceptionCatcher.h b/packages/camera/camera_avfoundation/example/ios/RunnerTests/ExceptionCatcher.h deleted file mode 100644 index 4c7ae95dac32..000000000000 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/ExceptionCatcher.h +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// TODO(FirentisTFW): Remove this file when the plugin code that uses it is migrated to Swift. -// After the migration, the code should throw Swift errors instead of Objective-C exceptions, thus -// this file will not be needed. - -#import - -NS_ASSUME_NONNULL_BEGIN - -/// A utility class for catching Objective-C exceptions. -/// -/// It allows to execute a block of code and catch any exceptions that are thrown during its -/// execution. This is useful for bridging between Objective-C and Swift code, as Swift does not -/// support catching Objective-C exceptions directly. -@interface ExceptionCatcher : NSObject -/// Executes a block of code and catches any exceptions that are thrown. -+ (nullable NSException *)catchException:(void (^)(void))tryBlock; -@end - -NS_ASSUME_NONNULL_END diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/ExceptionCatcher.m b/packages/camera/camera_avfoundation/example/ios/RunnerTests/ExceptionCatcher.m deleted file mode 100644 index febd9ac4f79d..000000000000 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/ExceptionCatcher.m +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "ExceptionCatcher.h" - -@implementation ExceptionCatcher -+ (nullable NSException *)catchException:(void (^)(void))tryBlock { - @try { - tryBlock(); - // No exception occurred. - return nil; - } @catch (NSException *exception) { - return exception; - } -} -@end diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/FLTCamExposureTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/FLTCamExposureTests.swift deleted file mode 100644 index 8310bbba606c..000000000000 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/FLTCamExposureTests.swift +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import XCTest - -@testable import camera_avfoundation - -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - -final class FLTCamExposureTests: XCTestCase { - private func createCamera() -> (Camera, MockCaptureDevice, MockDeviceOrientationProvider) { - let mockDevice = MockCaptureDevice() - let mockDeviceOrientationProvider = MockDeviceOrientationProvider() - - let configuration = CameraTestUtils.createTestCameraConfiguration() - configuration.videoCaptureDeviceFactory = { _ in mockDevice } - configuration.deviceOrientationProvider = mockDeviceOrientationProvider - let camera = CameraTestUtils.createTestCamera(configuration) - - return (camera, mockDevice, mockDeviceOrientationProvider) - } - - func testSetExposureModeLocked_setsAuthExposeMode() { - let (camera, mockDevice, _) = createCamera() - - mockDevice.setExposureModeStub = { mode in - // AVCaptureExposureModeAutoExpose automatically adjusts the exposure one time, and then - // locks exposure for the device - XCTAssertEqual(mode, .autoExpose) - } - - camera.setExposureMode(.locked) - } - - func testSetExposureModeAuto_setsContinousAutoExposureMode_ifSupported() { - let (camera, mockDevice, _) = createCamera() - - // All exposure modes are supported - mockDevice.isExposureModeSupportedStub = { _ in true } - - mockDevice.setExposureModeStub = { mode in - XCTAssertEqual(mode, .continuousAutoExposure) - } - - camera.setExposureMode(.auto) - } - - func testSetExposureModeAuto_setsAutoExposeMode_ifContinousAutoIsNotSupported() { - let (camera, mockDevice, _) = createCamera() - - // Continous auto exposure is not supported - mockDevice.isExposureModeSupportedStub = { mode in - mode != .continuousAutoExposure - } - - mockDevice.setExposureModeStub = { mode in - XCTAssertEqual(mode, .autoExpose) - } - - camera.setExposureMode(.auto) - } - - func testSetExposurePoint_setsExposurePointOfInterest() { - let (camera, mockDevice, mockDeviceOrientationProvider) = createCamera() - // UI is currently in landscape left orientation. - mockDeviceOrientationProvider.orientationStub = { .landscapeLeft } - // Exposure point of interest is supported. - mockDevice.isExposurePointOfInterestSupported = true - - // Verify the focus point of interest has been set. - var setPoint = CGPoint.zero - mockDevice.setExposurePointOfInterestStub = { point in - if point == CGPoint(x: 1, y: 1) { - setPoint = point - } - } - - let expectation = expectation(description: "Completion called") - camera.setExposurePoint(FCPPlatformPoint.makeWith(x: 1, y: 1)) { error in - XCTAssertNil(error) - expectation.fulfill() - } - - waitForExpectations(timeout: 30, handler: nil) - XCTAssertEqual(setPoint, CGPoint(x: 1.0, y: 1.0)) - } - - func testSetExposurePoint_returnsError_ifNotSupported() { - let (camera, mockDevice, mockDeviceOrientationProvider) = createCamera() - // UI is currently in landscape left orientation. - mockDeviceOrientationProvider.orientationStub = { .landscapeLeft } - // Exposure point of interest is not supported. - mockDevice.isExposurePointOfInterestSupported = false - - let expectation = expectation(description: "Completion with error") - - camera.setExposurePoint(FCPPlatformPoint.makeWith(x: 1, y: 1)) { error in - XCTAssertNotNil(error) - XCTAssertEqual(error?.code, "setExposurePointFailed") - XCTAssertEqual(error?.message, "Device does not have exposure point capabilities") - expectation.fulfill() - } - - waitForExpectations(timeout: 30, handler: nil) - } - - func testSetExposureOffset_setsExposureTargetBias() { - let (camera, mockDevice, _) = createCamera() - - let targetOffset = CGFloat(1.0) - - var setExposureTargetBiasCalled = false - mockDevice.setExposureTargetBiasStub = { bias, handler in - XCTAssertEqual(bias, Float(targetOffset)) - setExposureTargetBiasCalled = true - } - - camera.setExposureOffset(targetOffset) - - XCTAssertTrue(setExposureTargetBiasCalled) - } - - func testMaximumExposureOffset_returnsDeviceMaxExposureTargetBias() { - let (camera, mockDevice, _) = createCamera() - - let targetOffset = CGFloat(1.0) - - mockDevice.maxExposureTargetBias = Float(targetOffset) - - XCTAssertEqual(camera.maximumExposureOffset, targetOffset) - } - - func testMinimumExposureOffset_returnsDeviceMinExposureTargetBias() { - let (camera, mockDevice, _) = createCamera() - - let targetOffset = CGFloat(1.0) - - mockDevice.minExposureTargetBias = Float(targetOffset) - - XCTAssertEqual(camera.minimumExposureOffset, targetOffset) - } -} diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/FLTCamFocusTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/FLTCamFocusTests.swift deleted file mode 100644 index 570fd2022b82..000000000000 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/FLTCamFocusTests.swift +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import AVFoundation -import XCTest - -@testable import camera_avfoundation - -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - -final class FLTCamSetFocusModeTests: XCTestCase { - private func createCamera() -> (Camera, MockCaptureDevice, MockDeviceOrientationProvider) { - let mockDevice = MockCaptureDevice() - let mockDeviceOrientationProvider = MockDeviceOrientationProvider() - - let configuration = CameraTestUtils.createTestCameraConfiguration() - configuration.videoCaptureDeviceFactory = { _ in mockDevice } - configuration.deviceOrientationProvider = mockDeviceOrientationProvider - let camera = CameraTestUtils.createTestCamera(configuration) - - return (camera, mockDevice, mockDeviceOrientationProvider) - } - - func testAutoFocusWithContinuousModeSupported_ShouldSetContinuousAutoFocus() { - let (camera, mockDevice, _) = createCamera() - // AVCaptureFocusModeContinuousAutoFocus and AVCaptureFocusModeAutoFocus are supported. - mockDevice.isFocusModeSupportedStub = { mode in - mode == .continuousAutoFocus || mode == .autoFocus - } - - var setFocusModeContinuousAutoFocusCalled = false - - mockDevice.setFocusModeStub = { mode in - // Don't expect setFocusMode:AVCaptureFocusModeAutoFocus. - if mode == .autoFocus { - XCTFail("Unexpected call to setFocusMode") - } else if mode == .continuousAutoFocus { - setFocusModeContinuousAutoFocusCalled = true - } - } - - camera.setFocusMode(.auto) - - XCTAssertTrue(setFocusModeContinuousAutoFocusCalled) - } - - func testAutoFocusWithContinuousModeNotSupported_ShouldSetAutoFocus() { - let (camera, mockDevice, _) = createCamera() - // AVCaptureFocusModeContinuousAutoFocus is not supported. - // AVCaptureFocusModeAutoFocus is supported. - mockDevice.isFocusModeSupportedStub = { mode in - mode == .autoFocus - } - - var setFocusModeAutoFocusCalled = false - - // Don't expect setFocusMode:AVCaptureFocusModeContinuousAutoFocus. - mockDevice.setFocusModeStub = { mode in - if mode == .continuousAutoFocus { - XCTFail("Unexpected call to setFocusMode") - } else if mode == .autoFocus { - setFocusModeAutoFocusCalled = true - } - } - - camera.setFocusMode(.auto) - - XCTAssertTrue(setFocusModeAutoFocusCalled) - } - - func testAutoFocusWithNoModeSupported_ShouldSetNothing() { - let (camera, mockDevice, _) = createCamera() - // No modes are supported. - mockDevice.isFocusModeSupportedStub = { _ in - false - } - - // Don't expect any setFocus. - mockDevice.setFocusModeStub = { - _ in XCTFail("Unexpected call to setFocusMode") - } - - camera.setFocusMode(.auto) - } - - func testLockedFocusWithModeSupported_ShouldSetModeAutoFocus() { - let (camera, mockDevice, _) = createCamera() - // AVCaptureFocusModeContinuousAutoFocus and AVCaptureFocusModeAutoFocus are supported. - mockDevice.isFocusModeSupportedStub = { mode in - mode == .continuousAutoFocus || mode == .autoFocus - } - - var setFocusModeAutoFocusCalled = false - - // AVCaptureFocusModeAutoFocus automatically adjusts the focus one time, and then locks focus - mockDevice.setFocusModeStub = { mode in - if mode == .continuousAutoFocus { - XCTFail("Unexpected call to setFocusMode") - } else if mode == .autoFocus { - setFocusModeAutoFocusCalled = true - } - } - - camera.setFocusMode(.locked) - - XCTAssertTrue(setFocusModeAutoFocusCalled) - } - - func testLockedFocusWithModeNotSupported_ShouldSetNothing() { - let (camera, mockDevice, _) = createCamera() - mockDevice.isFocusModeSupportedStub = { mode in - mode == .continuousAutoFocus - } - - // Don't expect any setFocus. - mockDevice.setFocusModeStub = { _ in - XCTFail("Unexpected call to setFocusMode") - } - - camera.setFocusMode(.locked) - } - - func testSetFocusPointWithResult_SetsFocusPointOfInterest() { - let (camera, mockDevice, mockDeviceOrientationProvider) = createCamera() - // UI is currently in landscape left orientation. - mockDeviceOrientationProvider.orientationStub = { .landscapeLeft } - // Focus point of interest is supported. - mockDevice.isFocusPointOfInterestSupported = true - - var setFocusPointOfInterestCalled = false - mockDevice.setFocusPointOfInterestStub = { point in - if point == CGPoint(x: 1.0, y: 1.0) { - setFocusPointOfInterestCalled = true - } - } - - camera.setFocusPoint(FCPPlatformPoint.makeWith(x: 1, y: 1)) { error in - XCTAssertNil(error) - } - - XCTAssertTrue(setFocusPointOfInterestCalled) - } - - func testSetFocusPoint_WhenNotSupported_ReturnsError() { - let (camera, mockDevice, mockDeviceOrientationProvider) = createCamera() - // UI is currently in landscape left orientation. - mockDeviceOrientationProvider.orientationStub = { .landscapeLeft } - // Focus point of interest is not supported. - mockDevice.isFocusPointOfInterestSupported = false - - let expectation = self.expectation(description: "Completion with error") - - camera.setFocusPoint(FCPPlatformPoint.makeWith(x: 1, y: 1)) { error in - XCTAssertNotNil(error) - XCTAssertEqual(error?.code, "setFocusPointFailed") - XCTAssertEqual(error?.message, "Device does not have focus point capabilities") - expectation.fulfill() - } - - waitForExpectations(timeout: 30, handler: nil) - } -} diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/FLTCamSetDeviceOrientationTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/FLTCamSetDeviceOrientationTests.swift deleted file mode 100644 index 627929761d63..000000000000 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/FLTCamSetDeviceOrientationTests.swift +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import AVFoundation -import XCTest - -@testable import camera_avfoundation - -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - -final class FLTCamSetDeviceOrientationTests: XCTestCase { - private func createCamera() -> (Camera, MockCaptureConnection, MockCaptureConnection) { - let camera = CameraTestUtils.createTestCamera() - - let mockCapturePhotoOutput = MockCapturePhotoOutput() - let mockPhotoCaptureConnection = MockCaptureConnection() - mockPhotoCaptureConnection.isVideoOrientationSupported = true - - mockCapturePhotoOutput.connectionWithMediaTypeStub = { _ in mockPhotoCaptureConnection } - camera.capturePhotoOutput = mockCapturePhotoOutput - - let mockCaptureVideoDataOutput = MockCaptureVideoDataOutput() - let mockVideoCaptureConnection = MockCaptureConnection() - mockVideoCaptureConnection.isVideoOrientationSupported = true - - mockCaptureVideoDataOutput.connectionWithMediaTypeStub = { _ in mockVideoCaptureConnection } - camera.captureVideoOutput = mockCaptureVideoDataOutput - - return (camera, mockPhotoCaptureConnection, mockVideoCaptureConnection) - } - - func testSetDeviceOrientation_setsOrientationsOfCaptureConnections() { - let (camera, mockPhotoCaptureConnection, mockVideoCaptureConnection) = createCamera() - var photoSetVideoOrientationCalled = false - mockPhotoCaptureConnection.setVideoOrientationStub = { orientation in - // Device orientation is flipped compared to video orientation. When UIDeviceOrientation - // is landscape left the video orientation should be landscape right. - XCTAssertEqual(orientation, .landscapeRight) - photoSetVideoOrientationCalled = true - } - - var videoSetVideoOrientationCalled = false - mockVideoCaptureConnection.setVideoOrientationStub = { orientation in - // Device orientation is flipped compared to video orientation. When UIDeviceOrientation - // is landscape left the video orientation should be landscape right. - XCTAssertEqual(orientation, .landscapeRight) - videoSetVideoOrientationCalled = true - } - - camera.deviceOrientation = .landscapeLeft - - XCTAssertTrue(photoSetVideoOrientationCalled) - XCTAssertTrue(videoSetVideoOrientationCalled) - } - - func - testSetDeviceOrientation_setsLockedOrientationsOfCaptureConnection_ifCaptureOrientationIsLocked() - { - let (camera, mockPhotoCaptureConnection, mockVideoCaptureConnection) = createCamera() - var photoSetVideoOrientationCalled = false - mockPhotoCaptureConnection.setVideoOrientationStub = { orientation in - XCTAssertEqual(orientation, .portraitUpsideDown) - photoSetVideoOrientationCalled = true - } - - var videoSetVideoOrientationCalled = false - mockVideoCaptureConnection.setVideoOrientationStub = { orientation in - XCTAssertEqual(orientation, .portraitUpsideDown) - videoSetVideoOrientationCalled = true - } - - camera.lockCaptureOrientation(FCPPlatformDeviceOrientation.portraitDown) - - camera.deviceOrientation = .landscapeLeft - - XCTAssertTrue(photoSetVideoOrientationCalled) - XCTAssertTrue(videoSetVideoOrientationCalled) - } - - func testSetDeviceOrientation_doesNotSetOrientations_ifRecordingIsInProgress() { - let (camera, mockPhotoCaptureConnection, mockVideoCaptureConnection) = createCamera() - - camera.startVideoRecording(completion: { _ in }, messengerForStreaming: nil) - - mockPhotoCaptureConnection.setVideoOrientationStub = { _ in XCTFail() } - mockVideoCaptureConnection.setVideoOrientationStub = { _ in XCTFail() } - - camera.deviceOrientation = .landscapeLeft - } - - func testSetDeviceOrientation_doesNotSetOrientations_forDuplicateUpdates() { - let (camera, mockPhotoCaptureConnection, mockVideoCaptureConnection) = createCamera() - var photoSetVideoOrientationCallCount = 0 - mockPhotoCaptureConnection.setVideoOrientationStub = { _ in - photoSetVideoOrientationCallCount += 1 - } - - var videoSetVideoOrientationCallCount = 0 - mockVideoCaptureConnection.setVideoOrientationStub = { _ in - videoSetVideoOrientationCallCount += 1 - } - - camera.deviceOrientation = .landscapeRight - camera.deviceOrientation = .landscapeRight - - XCTAssertEqual(photoSetVideoOrientationCallCount, 1) - XCTAssertEqual(videoSetVideoOrientationCallCount, 1) - } -} diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/FLTCamSetFlashModeTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/FLTCamSetFlashModeTests.swift deleted file mode 100644 index 34f47c09346e..000000000000 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/FLTCamSetFlashModeTests.swift +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import AVFoundation -import XCTest - -@testable import camera_avfoundation - -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - -final class FLTCamSetFlashModeTests: XCTestCase { - private func createCamera() -> (Camera, MockCaptureDevice, MockCapturePhotoOutput) { - let mockDevice = MockCaptureDevice() - let mockCapturePhotoOutput = MockCapturePhotoOutput() - - let configuration = CameraTestUtils.createTestCameraConfiguration() - configuration.videoCaptureDeviceFactory = { _ in mockDevice } - let camera = CameraTestUtils.createTestCamera(configuration) - camera.capturePhotoOutput = mockCapturePhotoOutput - - return (camera, mockDevice, mockCapturePhotoOutput) - } - - func testSetFlashModeWithTorchMode_setsTrochModeOn() { - let (camera, mockDevice, _) = createCamera() - - mockDevice.hasTorch = true - mockDevice.isTorchAvailable = true - - var setTorchModeCalled = false - mockDevice.setTorchModeStub = { torchMode in - XCTAssertEqual(torchMode, .on) - setTorchModeCalled = true - } - - let expectation = expectation(description: "Call completed") - - camera.setFlashMode(.torch) { error in - XCTAssertNil(error) - expectation.fulfill() - } - - waitForExpectations(timeout: 30) - - XCTAssertTrue(setTorchModeCalled) - } - - func testSetFlashModeWithTorchMode_returnError_ifHasNoTorch() { - let (camera, mockDevice, _) = createCamera() - - mockDevice.hasTorch = false - - let expectation = expectation(description: "Call completed") - - camera.setFlashMode(.torch) { error in - XCTAssertNotNil(error) - XCTAssertEqual(error?.code, "setFlashModeFailed") - XCTAssertEqual(error?.message, "Device does not support torch mode") - expectation.fulfill() - } - - waitForExpectations(timeout: 30) - } - - func testSetFlashModeWithTorchMode_returnError_ifTorchIsNotAvailable() { - let (camera, mockDevice, _) = createCamera() - - mockDevice.hasTorch = true - mockDevice.isTorchAvailable = false - - let expectation = expectation(description: "Call completed") - - camera.setFlashMode(.torch) { error in - XCTAssertNotNil(error) - XCTAssertEqual(error?.code, "setFlashModeFailed") - XCTAssertEqual(error?.message, "Torch mode is currently not available") - expectation.fulfill() - } - - waitForExpectations(timeout: 30) - } - - func testSetFlashModeWithNonTorchMode_setsTrochModeOff_ifTorchModeIsEnabled() { - let (camera, mockDevice, mockCapturePhotoOutput) = createCamera() - - mockCapturePhotoOutput.supportedFlashModes = [.auto] - - mockDevice.hasFlash = true - // Torch mode is enabled - mockDevice.getTorchModeStub = { .on } - - var setTorchModeCalled = false - mockDevice.setTorchModeStub = { torchMode in - XCTAssertEqual(torchMode, .off) - setTorchModeCalled = true - } - - let expectation = expectation(description: "Call completed") - - camera.setFlashMode(.auto) { error in - XCTAssertNil(error) - expectation.fulfill() - } - - waitForExpectations(timeout: 30) - - XCTAssertTrue(setTorchModeCalled) - } - - func testSetFlashModeWithNonTorchMode_returnError_ifHasNoFlash() { - let (camera, mockDevice, _) = createCamera() - - mockDevice.hasFlash = false - - let expectation = expectation(description: "Call completed") - - camera.setFlashMode(.auto) { error in - XCTAssertNotNil(error) - XCTAssertEqual(error?.code, "setFlashModeFailed") - XCTAssertEqual(error?.message, "Device does not have flash capabilities") - expectation.fulfill() - } - - waitForExpectations(timeout: 30) - } - - func testSetFlashModeWithNonTorchMode_returnError_ifModeIsNotSupported() { - let (camera, mockDevice, mockCapturePhotoOutput) = createCamera() - - // No flash modes are supported - mockCapturePhotoOutput.supportedFlashModes = [] - - mockDevice.hasFlash = true - - let expectation = expectation(description: "Call completed") - - camera.setFlashMode(.auto) { error in - XCTAssertNotNil(error) - XCTAssertEqual(error?.code, "setFlashModeFailed") - XCTAssertEqual(error?.message, "Device does not support this specific flash mode") - expectation.fulfill() - } - - waitForExpectations(timeout: 30) - } -} diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/FLTCamZoomTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/FLTCamZoomTests.swift deleted file mode 100644 index b0641fc6daf7..000000000000 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/FLTCamZoomTests.swift +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import AVFoundation -import XCTest - -@testable import camera_avfoundation - -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - -final class FLTCamZoomTests: XCTestCase { - private func createCamera() -> (Camera, MockCaptureDevice) { - let mockDevice = MockCaptureDevice() - - let configuration = CameraTestUtils.createTestCameraConfiguration() - configuration.videoCaptureDeviceFactory = { _ in mockDevice } - let camera = CameraTestUtils.createTestCamera(configuration) - - return (camera, mockDevice) - } - - func testSetZoomLevel_setVideoZoomFactor() { - let (camera, mockDevice) = createCamera() - - mockDevice.maxAvailableVideoZoomFactor = 2.0 - mockDevice.minAvailableVideoZoomFactor = 0.0 - - let targetZoom = CGFloat(1.0) - - var setVideoZoomFactorCalled = false - mockDevice.setVideoZoomFactorStub = { zoom in - XCTAssertEqual(zoom, targetZoom) - setVideoZoomFactorCalled = true - } - - let expectation = expectation(description: "Call completed") - - camera.setZoomLevel(targetZoom) { error in - XCTAssertNil(error) - expectation.fulfill() - } - - waitForExpectations(timeout: 30) - - XCTAssertTrue(setVideoZoomFactorCalled) - } - - func testSetZoomLevel_returnsError_forZoomLevelBlowMinimum() { - let (camera, mockDevice) = createCamera() - - // Allowed zoom range between 2.0 and 3.0 - mockDevice.maxAvailableVideoZoomFactor = 2.0 - mockDevice.minAvailableVideoZoomFactor = 3.0 - - let expectation = expectation(description: "Call completed") - - camera.setZoomLevel(CGFloat(1.0)) { error in - XCTAssertNotNil(error) - XCTAssertEqual(error?.code, "ZOOM_ERROR") - expectation.fulfill() - } - - waitForExpectations(timeout: 30) - } - - func testSetZoomLevel_returnsError_forZoomLevelAboveMaximum() { - let (camera, mockDevice) = createCamera() - - // Allowed zoom range between 0.0 and 1.0 - mockDevice.maxAvailableVideoZoomFactor = 0.0 - mockDevice.minAvailableVideoZoomFactor = 1.0 - - let expectation = expectation(description: "Call completed") - - camera.setZoomLevel(CGFloat(2.0)) { error in - XCTAssertNotNil(error) - XCTAssertEqual(error?.code, "ZOOM_ERROR") - expectation.fulfill() - } - - waitForExpectations(timeout: 30) - } - - func testMaximumAvailableZoomFactor_returnsDeviceMaxAvailableVideoZoomFactor() { - let (camera, mockDevice) = createCamera() - - let targetZoom = CGFloat(1.0) - - mockDevice.maxAvailableVideoZoomFactor = CGFloat(targetZoom) - - XCTAssertEqual(camera.maximumAvailableZoomFactor, targetZoom) - } - - func testMinimumAvailableZoomFactor_returnsDeviceMinAvailableVideoZoomFactor() { - let (camera, mockDevice) = createCamera() - - let targetZoom = CGFloat(1.0) - - mockDevice.minAvailableVideoZoomFactor = CGFloat(targetZoom) - - XCTAssertEqual(camera.minimumAvailableZoomFactor, targetZoom) - } -} diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockAssetWriter.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockAssetWriter.swift index 45be267358ce..2b345c00b3ab 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockAssetWriter.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockAssetWriter.swift @@ -2,16 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import camera_avfoundation +import AVFoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif +@testable import camera_avfoundation -/// Mock implementation of `FLTAssetWriter` protocol which allows injecting a custom +/// Mock implementation of `AssetWriter` protocol which allows injecting a custom /// implementation. -final class MockAssetWriter: NSObject, FLTAssetWriter { +final class MockAssetWriter: NSObject, AssetWriter { var statusStub: (() -> AVAssetWriter.Status)? var startWritingStub: (() -> Bool)? var finishWritingStub: ((() -> Void) -> Void)? diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockAssetWriterInput.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockAssetWriterInput.swift index 9b6d7e2ca898..9e70646e2fb1 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockAssetWriterInput.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockAssetWriterInput.swift @@ -2,25 +2,22 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import camera_avfoundation +import AVFoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif +@testable import camera_avfoundation -/// Mock implementation of `FLTAssetWriterInput` protocol which allows injecting a custom +/// Mock implementation of `AssetWriterInput` protocol which allows injecting a custom /// implementation. -final class MockAssetWriterInput: NSObject, FLTAssetWriterInput { +final class MockAssetWriterInput: NSObject, AssetWriterInput { var appendStub: ((CMSampleBuffer) -> Bool)? - var input: AVAssetWriterInput { - preconditionFailure("Attempted to access unimplemented property: input") + var avInput: AVAssetWriterInput { + preconditionFailure("Attempted to access unimplemented property: avInput") } var expectsMediaDataInRealTime = false - var readyForMoreMediaData = false + var isReadyForMoreMediaData = false func append(_ sampleBuffer: CMSampleBuffer) -> Bool { return appendStub?(sampleBuffer) ?? false diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockAssetWriterInputPixelBufferAdaptor.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockAssetWriterInputPixelBufferAdaptor.swift index f8d6731d469b..a27106e3a0a7 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockAssetWriterInputPixelBufferAdaptor.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockAssetWriterInputPixelBufferAdaptor.swift @@ -2,17 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import camera_avfoundation +import AVFoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif +@testable import camera_avfoundation -/// Mock implementation of `FLTAssetWriterInputPixelBufferAdaptor` protocol which allows injecting a custom +/// Mock implementation of `AssetWriterInputPixelBufferAdaptor` protocol which allows injecting a custom /// implementation. -final class MockAssetWriterInputPixelBufferAdaptor: NSObject, FLTAssetWriterInputPixelBufferAdaptor -{ +final class MockAssetWriterInputPixelBufferAdaptor: NSObject, AssetWriterInputPixelBufferAdaptor { var appendStub: ((CVPixelBuffer, CMTime) -> Bool)? func append(_ pixelBuffer: CVPixelBuffer, withPresentationTime presentationTime: CMTime) -> Bool { diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCamera.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCamera.swift index 76a416d92113..ec6e6fd88f9c 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCamera.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCamera.swift @@ -2,15 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -@testable import camera_avfoundation +import AVFoundation +import Flutter -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif +@testable import camera_avfoundation final class MockCamera: NSObject, Camera { - var setDartApiStub: ((FCPCameraEventApi?) -> Void)? + var setDartApiStub: ((CameraEventApi?) -> Void)? var setOnFrameAvailableStub: (((() -> Void)?) -> Void)? var getMinimumExposureOffsetStub: (() -> CGFloat)? var getMaximumExposureOffsetStub: (() -> CGFloat)? @@ -20,29 +18,34 @@ final class MockCamera: NSObject, Camera { var receivedImageStreamDataStub: (() -> Void)? var startStub: (() -> Void)? var startVideoRecordingStub: - ((@escaping (FlutterError?) -> Void, FlutterBinaryMessenger?) -> Void)? + ((@escaping (Result) -> Void, FlutterBinaryMessenger?) -> Void)? var pauseVideoRecordingStub: (() -> Void)? var resumeVideoRecordingStub: (() -> Void)? - var stopVideoRecordingStub: ((((String?, FlutterError?) -> Void)?) -> Void)? - var captureToFileStub: ((((String?, FlutterError?) -> Void)?) -> Void)? + var stopVideoRecordingStub: ((@escaping (Result) -> Void) -> Void)? + var captureToFileStub: ((@escaping (Result) -> Void) -> Void)? var setDeviceOrientationStub: ((UIDeviceOrientation) -> Void)? - var lockCaptureOrientationStub: ((FCPPlatformDeviceOrientation) -> Void)? + var lockCaptureOrientationStub: ((PlatformDeviceOrientation) -> Void)? var unlockCaptureOrientationStub: (() -> Void)? - var setImageFileFormatStub: ((FCPPlatformImageFileFormat) -> Void)? - var setExposureModeStub: ((FCPPlatformExposureMode) -> Void)? + var setImageFileFormatStub: ((PlatformImageFileFormat) -> Void)? + var setExposureModeStub: ((PlatformExposureMode) -> Void)? var setExposureOffsetStub: ((Double) -> Void)? - var setExposurePointStub: ((FCPPlatformPoint?, ((FlutterError?) -> Void)?) -> Void)? - var setFocusModeStub: ((FCPPlatformFocusMode) -> Void)? - var setFocusPointStub: ((FCPPlatformPoint?, ((FlutterError?) -> Void)?) -> Void)? - var setZoomLevelStub: ((CGFloat, ((FlutterError?) -> Void)?) -> Void)? - var setFlashModeStub: ((FCPPlatformFlashMode, ((FlutterError?) -> Void)?) -> Void)? + var setExposurePointStub: ((PlatformPoint?, @escaping (Result) -> Void) -> Void)? + var setFocusModeStub: ((PlatformFocusMode) -> Void)? + var setFocusPointStub: ((PlatformPoint?, @escaping (Result) -> Void) -> Void)? + var setZoomLevelStub: ((CGFloat, @escaping (Result) -> Void) -> Void)? + var setFlashModeStub: ((PlatformFlashMode, @escaping (Result) -> Void) -> Void)? var pausePreviewStub: (() -> Void)? var resumePreviewStub: (() -> Void)? - var setDescriptionWhileRecordingStub: ((String, ((FlutterError?) -> Void)?) -> Void)? - var startImageStreamStub: ((FlutterBinaryMessenger, (FlutterError?) -> Void) -> Void)? + var setDescriptionWhileRecordingStub: + ((String, @escaping (Result) -> Void) -> Void)? + var startImageStreamStub: + ((FlutterBinaryMessenger, @escaping (Result) -> Void) -> Void)? var stopImageStreamStub: (() -> Void)? + var setVideoStabilizationModeStub: + ((PlatformVideoStabilizationMode, @escaping (Result) -> Void) -> Void)? + var getIsVideoStabilizationModeSupportedStub: ((PlatformVideoStabilizationMode) -> Bool)? - var dartAPI: FCPCameraEventApi? { + var dartAPI: CameraEventApi? { get { preconditionFailure("Attempted to access unimplemented property: dartAPI") } @@ -107,7 +110,7 @@ final class MockCamera: NSObject, Camera { func stop() {} func startVideoRecording( - completion: @escaping (FlutterError?) -> Void, + completion: @escaping (Result) -> Void, messengerForStreaming messenger: FlutterBinaryMessenger? ) { startVideoRecordingStub?(completion, messenger) @@ -121,15 +124,15 @@ final class MockCamera: NSObject, Camera { resumeVideoRecordingStub?() } - func stopVideoRecording(completion: @escaping (String?, FlutterError?) -> Void) { + func stopVideoRecording(completion: @escaping (Result) -> Void) { stopVideoRecordingStub?(completion) } - func captureToFile(completion: @escaping (String?, FlutterError?) -> Void) { + func captureToFile(completion: @escaping (Result) -> Void) { captureToFileStub?(completion) } - func lockCaptureOrientation(_ orientation: FCPPlatformDeviceOrientation) { + func lockCaptureOrientation(_ orientation: PlatformDeviceOrientation) { lockCaptureOrientationStub?(orientation) } @@ -137,11 +140,11 @@ final class MockCamera: NSObject, Camera { unlockCaptureOrientationStub?() } - func setImageFileFormat(_ fileFormat: FCPPlatformImageFileFormat) { + func setImageFileFormat(_ fileFormat: PlatformImageFileFormat) { setImageFileFormatStub?(fileFormat) } - func setExposureMode(_ mode: FCPPlatformExposureMode) { + func setExposureMode(_ mode: PlatformExposureMode) { setExposureModeStub?(mode) } @@ -150,29 +153,31 @@ final class MockCamera: NSObject, Camera { } func setExposurePoint( - _ point: FCPPlatformPoint?, withCompletion: @escaping (FlutterError?) -> Void + _ point: PlatformPoint?, withCompletion: @escaping (Result) -> Void ) { setExposurePointStub?(point, withCompletion) } - func setFocusMode(_ mode: FCPPlatformFocusMode) { + func setFocusMode(_ mode: PlatformFocusMode) { setFocusModeStub?(mode) } - func setFocusPoint(_ point: FCPPlatformPoint?, completion: @escaping (FlutterError?) -> Void) { + func setFocusPoint( + _ point: PlatformPoint?, completion: @escaping (Result) -> Void + ) { setFocusPointStub?(point, completion) } func setZoomLevel( _ zoom: CGFloat, - withCompletion completion: @escaping (FlutterError?) -> Void + withCompletion completion: @escaping (Result) -> Void ) { setZoomLevelStub?(zoom, completion) } func setFlashMode( - _ mode: FCPPlatformFlashMode, - withCompletion completion: @escaping (FlutterError?) -> Void + _ mode: PlatformFlashMode, + withCompletion completion: @escaping (Result) -> Void ) { setFlashModeStub?(mode, completion) } @@ -185,16 +190,27 @@ final class MockCamera: NSObject, Camera { resumePreviewStub?() } + func setVideoStabilizationMode( + _ mode: PlatformVideoStabilizationMode, + withCompletion completion: @escaping (Result) -> Void + ) { + setVideoStabilizationModeStub?(mode, completion) + } + + func isVideoStabilizationModeSupported(_ mode: PlatformVideoStabilizationMode) -> Bool { + return getIsVideoStabilizationModeSupportedStub?(mode) ?? false + } + func setDescriptionWhileRecording( _ cameraName: String, - withCompletion completion: @escaping (FlutterError?) -> Void + withCompletion completion: @escaping (Result) -> Void ) { setDescriptionWhileRecordingStub?(cameraName, completion) } func startImageStream( with messenger: FlutterBinaryMessenger, - completion: @escaping (FlutterError?) -> Void + completion: @escaping (Result) -> Void ) { startImageStreamStub?(messenger, completion) } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCameraDeviceDiscoverer.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCameraDeviceDiscoverer.swift index 2a50f6889c98..f621aa620b5c 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCameraDeviceDiscoverer.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCameraDeviceDiscoverer.swift @@ -2,14 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -@testable import camera_avfoundation +import AVFoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif +@testable import camera_avfoundation -/// Mock implementation of `FLTCameraDeviceDiscoverer` protocol which allows injecting a custom +/// Mock implementation of `CameraDeviceDiscoverer` protocol which allows injecting a custom /// implementation for session discovery. final class MockCameraDeviceDiscoverer: NSObject, CameraDeviceDiscoverer { var discoverySessionStub: diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureConnection.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureConnection.swift index f65e0ce3c21f..d6ea85f20e29 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureConnection.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureConnection.swift @@ -2,15 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import camera_avfoundation +import AVFoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif +@testable import camera_avfoundation -/// A mock implementation of `FLTCaptureConnection` that allows injecting a custom implementation. -final class MockCaptureConnection: NSObject, FLTCaptureConnection { +/// A mock implementation of `CaptureConnection` that allows injecting a custom implementation. +final class MockCaptureConnection: NSObject, CaptureConnection { var setVideoOrientationStub: ((AVCaptureVideoOrientation) -> Void)? var connection: AVCaptureConnection { @@ -26,4 +23,5 @@ final class MockCaptureConnection: NSObject, FLTCaptureConnection { var inputPorts: [AVCaptureInput.Port] = [] var isVideoMirroringSupported = false var isVideoOrientationSupported = false + var preferredVideoStabilizationMode = AVCaptureVideoStabilizationMode.off } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureDevice.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureDevice.swift index 0e2a4442a397..71fe2fc8f7da 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureDevice.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureDevice.swift @@ -2,18 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -@testable import camera_avfoundation +import AVFoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif +@testable import camera_avfoundation -/// A mock implementation of `FLTCaptureDevice` that allows mocking the class +/// A mock implementation of `CaptureDevice` that allows mocking the class /// properties. class MockCaptureDevice: NSObject, CaptureDevice { - var activeFormatStub: (() -> FLTCaptureDeviceFormat)? - var setActiveFormatStub: ((FLTCaptureDeviceFormat) -> Void)? + var activeFormatStub: (() -> CaptureDeviceFormat)? + var setActiveFormatStub: ((CaptureDeviceFormat) -> Void)? var getTorchModeStub: (() -> AVCaptureDevice.TorchMode)? var setTorchModeStub: ((AVCaptureDevice.TorchMode) -> Void)? var isFocusModeSupportedStub: ((AVCaptureDevice.FocusMode) -> Bool)? @@ -34,7 +31,7 @@ class MockCaptureDevice: NSObject, CaptureDevice { var position = AVCaptureDevice.Position.unspecified var deviceType = AVCaptureDevice.DeviceType.builtInWideAngleCamera - var flutterActiveFormat: FLTCaptureDeviceFormat { + var flutterActiveFormat: CaptureDeviceFormat { get { activeFormatStub?() ?? MockCaptureDeviceFormat() } @@ -43,7 +40,7 @@ class MockCaptureDevice: NSObject, CaptureDevice { } } - var flutterFormats: [FLTCaptureDeviceFormat] = [] + var flutterFormats: [CaptureDeviceFormat] = [] var hasFlash = false var hasTorch = false var isTorchAvailable = false @@ -110,11 +107,17 @@ class MockCaptureDevice: NSObject, CaptureDevice { return isExposureModeSupportedStub?(mode) ?? false } - var lensAperture: Float { 0 } + var lensAperture: Float { 1.8 } var exposureDuration: CMTime { CMTime(value: 1, timescale: 1) } - var iso: Float { 0 } + var iso: Float { 100 } + + func isVideoStabilizationModeSupported(_ videoStabilizationMode: AVCaptureVideoStabilizationMode) + -> Bool + { + return false + } func lockForConfiguration() throws { try lockForConfigurationStub?() diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureDeviceFormat.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureDeviceFormat.swift index b34040ae0cfb..557ff4ba7ca2 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureDeviceFormat.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureDeviceFormat.swift @@ -2,20 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import camera_avfoundation +import AVFoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif +@testable import camera_avfoundation -/// A mock implementation of `FLTCaptureDeviceFormat` that allows mocking the class +/// A mock implementation of `CaptureDeviceFormat` that allows mocking the class /// properties. -final class MockCaptureDeviceFormat: NSObject, FLTCaptureDeviceFormat { +final class MockCaptureDeviceFormat: NSObject, CaptureDeviceFormat { /// The format associated with the capture device. - var format: AVCaptureDevice.Format { - preconditionFailure("Attempted to access unimplemented property: format") + var avFormat: AVCaptureDevice.Format { + preconditionFailure("Attempted to access unimplemented property: avFormat") } var _formatDescription: CMVideoFormatDescription? @@ -26,7 +23,7 @@ final class MockCaptureDeviceFormat: NSObject, FLTCaptureDeviceFormat { } /// The array of frame rate ranges supported by the video format. - var videoSupportedFrameRateRanges: [FLTFrameRateRange] = [] + var flutterVideoSupportedFrameRateRanges: [FrameRateRange] = [] override init() { super.init() @@ -35,4 +32,12 @@ final class MockCaptureDeviceFormat: NSObject, FLTCaptureDeviceFormat { allocator: kCFAllocatorDefault, codecType: kCVPixelFormatType_32BGRA, width: 1920, height: 1080, extensions: nil, formatDescriptionOut: &_formatDescription) } + + init(codecType: OSType, width: Int32, height: Int32) { + super.init() + + CMVideoFormatDescriptionCreate( + allocator: kCFAllocatorDefault, codecType: codecType, width: width, + height: height, extensions: nil, formatDescriptionOut: &_formatDescription) + } } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureDeviceInputFactory.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureDeviceInputFactory.swift index abf66e49106b..0222750a43e1 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureDeviceInputFactory.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureDeviceInputFactory.swift @@ -2,14 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -@testable import camera_avfoundation +import Foundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif +@testable import camera_avfoundation -///// A mocked implementation of FLTCaptureDeviceInputFactory which allows injecting a custom +///// A mocked implementation of CaptureDeviceInputFactory which allows injecting a custom ///// implementation. final class MockCaptureDeviceInputFactory: NSObject, CaptureDeviceInputFactory { func deviceInput(with device: CaptureDevice) throws -> CaptureInput { diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureInput.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureInput.swift index 0c6a38d1bc26..394dbf9b5b67 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureInput.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureInput.swift @@ -2,14 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -@testable import camera_avfoundation +import AVFoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif +@testable import camera_avfoundation -/// A mocked implementation of FLTCaptureInput which allows injecting a custom +/// A mocked implementation of CaptureInput which allows injecting a custom /// implementation. final class MockCaptureInput: NSObject, CaptureInput { var avInput: AVCaptureInput { diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCapturePhotoOutput.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCapturePhotoOutput.swift index ad8f480f22cb..184fd0be36b2 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCapturePhotoOutput.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCapturePhotoOutput.swift @@ -2,14 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -@testable import camera_avfoundation +import AVFoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif +@testable import camera_avfoundation -/// Mock implementation of `FLTCapturePhotoOutput` protocol which allows injecting a custom +/// Mock implementation of `CapturePhotoOutput` protocol which allows injecting a custom /// implementation. final class MockCapturePhotoOutput: NSObject, CapturePhotoOutput { var avOutput = AVCapturePhotoOutput() @@ -22,14 +19,14 @@ final class MockCapturePhotoOutput: NSObject, CapturePhotoOutput { ((_ settings: AVCapturePhotoSettings, _ delegate: AVCapturePhotoCaptureDelegate) -> Void)? // Stub that is called when the corresponding public method is called. - var connectionWithMediaTypeStub: ((_ mediaType: AVMediaType) -> FLTCaptureConnection?)? + var connectionWithMediaTypeStub: ((_ mediaType: AVMediaType) -> CaptureConnection?)? func capturePhoto(with settings: AVCapturePhotoSettings, delegate: AVCapturePhotoCaptureDelegate) { capturePhotoWithSettingsStub?(settings, delegate) } - func connection(with mediaType: AVMediaType) -> FLTCaptureConnection? { + func connection(with mediaType: AVMediaType) -> CaptureConnection? { return connectionWithMediaTypeStub?(mediaType) } } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureSession.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureSession.swift index 4f5a7f9e7295..23ce72bbe9f8 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureSession.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureSession.swift @@ -2,14 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -@testable import camera_avfoundation +import AVFoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif +@testable import camera_avfoundation -/// Mock implementation of `FLTCaptureSession` protocol which allows injecting a custom +/// Mock implementation of `CaptureSession` protocol which allows injecting a custom /// implementation. final class MockCaptureSession: NSObject, CaptureSession { var setSessionPresetStub: ((AVCaptureSession.Preset) -> Void)? @@ -26,6 +23,7 @@ final class MockCaptureSession: NSObject, CaptureSession { private(set) var addedAudioOutputCount: Int = 0 var automaticallyConfiguresApplicationAudioSession = false + var isRunning = true var sessionPreset: AVCaptureSession.Preset { get { diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureVideoDataOutput.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureVideoDataOutput.swift index 98d1296a8b27..23e54734f853 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureVideoDataOutput.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockCaptureVideoDataOutput.swift @@ -2,23 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -@testable import camera_avfoundation +import AVFoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif +@testable import camera_avfoundation -/// Mock implementation of `FLTCaptureVideoDataOutput` protocol which allows injecting a custom +/// Mock implementation of `CaptureVideoDataOutput` protocol which allows injecting a custom /// implementation. class MockCaptureVideoDataOutput: NSObject, CaptureVideoDataOutput { var avOutput = AVCaptureVideoDataOutput() var alwaysDiscardsLateVideoFrames = false var videoSettings: [String: Any]! = [:] + var availableVideoPixelFormatTypes: [FourCharCode] = [] - var connectionWithMediaTypeStub: ((AVMediaType) -> FLTCaptureConnection?)? + var connectionWithMediaTypeStub: ((AVMediaType) -> CaptureConnection?)? - func connection(with mediaType: AVMediaType) -> FLTCaptureConnection? { + func connection(with mediaType: AVMediaType) -> CaptureConnection? { return connectionWithMediaTypeStub?(mediaType) } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockDeviceOrientationProvider.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockDeviceOrientationProvider.swift index 3c1ffacad5a7..034eafc4d184 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockDeviceOrientationProvider.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockDeviceOrientationProvider.swift @@ -2,12 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -@testable import camera_avfoundation +import UIKit -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif +@testable import camera_avfoundation final class MockDeviceOrientationProvider: NSObject, DeviceOrientationProvider { var orientationStub: (() -> UIDeviceOrientation)? diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockEventChannel.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockEventChannel.swift deleted file mode 100644 index b0e776111630..000000000000 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockEventChannel.swift +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import camera_avfoundation - -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - -/// A mock implementation of `FLTEventChannel` that allows injecting a custom implementation -/// for setting a stream handler. -final class MockEventChannel: NSObject, FLTEventChannel { - var setStreamHandlerStub: ((FlutterStreamHandler?) -> Void)? - - func setStreamHandler(_ handler: (FlutterStreamHandler & NSObjectProtocol)?) { - setStreamHandlerStub?(handler) - } -} diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockFLTCameraPermissionManager.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockFLTCameraPermissionManager.swift index 6288389cd92b..73f991f43a38 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockFLTCameraPermissionManager.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockFLTCameraPermissionManager.swift @@ -2,22 +2,31 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import camera_avfoundation +import Flutter -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif +@testable import camera_avfoundation -final class MockFLTCameraPermissionManager: FLTCameraPermissionManager { - var requestCameraPermissionStub: ((((FlutterError?) -> Void)?) -> Void)? - var requestAudioPermissionStub: ((((FlutterError?) -> Void)?) -> Void)? +final class MockCameraPermissionManager: CameraPermissionManager { + var requestCameraPermissionStub: ((@escaping CameraPermissionRequestCompletionHandler) -> Void)? + var requestAudioPermissionStub: ((@escaping CameraPermissionRequestCompletionHandler) -> Void)? - override func requestCameraPermission(completionHandler: ((FlutterError?) -> Void)?) { - requestCameraPermissionStub?(completionHandler) + init() { + super.init(permissionService: DefaultPermissionService()) } - override func requestAudioPermission(completionHandler: ((FlutterError?) -> Void)?) { - requestAudioPermissionStub?(completionHandler) + override func requestCameraPermission(completionHandler: @escaping (PigeonError?) -> Void) { + if let stub = requestCameraPermissionStub { + stub(completionHandler) + } else { + super.requestCameraPermission(completionHandler: completionHandler) + } + } + + override func requestAudioPermission(completionHandler: @escaping (PigeonError?) -> Void) { + if let stub = requestAudioPermissionStub { + stub(completionHandler) + } else { + super.requestAudioPermission(completionHandler: completionHandler) + } } } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockFrameRateRange.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockFrameRateRange.swift index 866e108d211b..d4bfbda30385 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockFrameRateRange.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockFrameRateRange.swift @@ -2,20 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import camera_avfoundation +import Foundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif +@testable import camera_avfoundation -/// A mock implementation of `FLTFrameRateRange` that allows mocking the class properties. -final class MockFrameRateRange: NSObject, FLTFrameRateRange { - var minFrameRate: Float - var maxFrameRate: Float +/// A mock implementation of `FrameRateRange` that allows mocking the class properties. +final class MockFrameRateRange: NSObject, FrameRateRange { + var minFrameRate: Float64 + var maxFrameRate: Float64 /// Initializes a `MockFrameRateRange` with the given frame rate range. - init(minFrameRate: Float, maxFrameRate: Float) { + init(minFrameRate: Float64, maxFrameRate: Float64) { self.minFrameRate = minFrameRate self.maxFrameRate = maxFrameRate } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockGlobalEventApi.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockGlobalEventApi.swift index 774f598168d6..1a95e4278216 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockGlobalEventApi.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockGlobalEventApi.swift @@ -2,29 +2,25 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import camera_avfoundation +import Flutter -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif +@testable import camera_avfoundation -/// A mock implementation of `FCPCameraGlobalEventApi` that captures received +/// A mock implementation of `CameraGlobalEventApi` that captures received /// `deviceOrientationChanged` events and exposes whether they were received to the testing code. -final class MockGlobalEventApi: FCPCameraGlobalEventApi { - +final class MockGlobalEventApi: CameraGlobalEventApiProtocol { /// Whether the `deviceOrientationChanged` callback was called. var deviceOrientationChangedCalled = false /// The last orientation received by the `deviceOrientationChanged` callback. - var lastOrientation = FCPPlatformDeviceOrientation.portraitUp + var lastOrientation = PlatformDeviceOrientation.portraitUp - override func deviceOrientationChangedOrientation( - _ orientation: FCPPlatformDeviceOrientation, - completion: @escaping (FlutterError?) -> Void + func deviceOrientationChanged( + orientation orientationArg: PlatformDeviceOrientation, + completion: @escaping (Result) -> Void ) { deviceOrientationChangedCalled = true - lastOrientation = orientation - completion(nil) + lastOrientation = orientationArg + completion(.success(())) } } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockWritableData.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockWritableData.swift index bf0fd30d6685..8666c4d96093 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockWritableData.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/Mocks/MockWritableData.swift @@ -2,21 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import camera_avfoundation +import Foundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif +@testable import camera_avfoundation -/// A mock implementation of `FLTWritableData` that allows injecting a custom implementation +/// A mock implementation of `WritableData` that allows injecting a custom implementation /// for writing to a file. -final class MockWritableData: NSObject, FLTWritableData { - var writeToFileStub: ((String, NSData.WritingOptions) throws -> Void)? +final class MockWritableData: WritableData { + var writeToFileStub: ((String, Data.WritingOptions) throws -> Void)? - func write(toFile path: String, options writeOptionsMask: NSData.WritingOptions) throws { + func writeToPath(_ path: String, options: Data.WritingOptions) throws { if let stub = self.writeToFileStub { - try stub(path, writeOptionsMask) + try stub(path, options) } } } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/PhotoCaptureTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/PhotoCaptureTests.swift index 7f8cef124d6f..1113fb424450 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/PhotoCaptureTests.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/PhotoCaptureTests.swift @@ -7,12 +7,7 @@ import XCTest @testable import camera_avfoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - -/// Includes test cases related to photo capture operations for FLTCam class. +/// Includes test cases related to photo capture operations for Camera class. final class PhotoCaptureTests: XCTestCase { private func createCam(with captureSessionQueue: DispatchQueue) -> DefaultCamera { let configuration = CameraTestUtils.createTestCameraConfiguration() @@ -41,11 +36,15 @@ final class PhotoCaptureTests: XCTestCase { } cam.capturePhotoOutput = mockOutput - // `FLTCam::captureToFile` runs on capture session queue. + // `Camera.captureToFile` runs on capture session queue. captureSessionQueue.async { - cam.captureToFile { result, error in - XCTAssertNil(result) - XCTAssertNotNil(error) + cam.captureToFile { result in + switch result { + case .success(_): + XCTFail("Expected failure") + case .failure(_): + break + } errorExpectation.fulfill() } } @@ -74,10 +73,15 @@ final class PhotoCaptureTests: XCTestCase { } cam.capturePhotoOutput = mockOutput - // `FLTCam::captureToFile` runs on capture session queue. + // `Camera.captureToFile` runs on capture session queue. captureSessionQueue.async { - cam.captureToFile { result, error in - XCTAssertEqual(result, filePath) + cam.captureToFile { result in + switch result { + case .success(let result): + XCTAssertEqual(result, filePath) + case .failure(_): + XCTFail("Unexpected failure") + } pathExpectation.fulfill() } } @@ -93,7 +97,7 @@ final class PhotoCaptureTests: XCTestCase { captureSessionQueue.setSpecific( key: captureSessionQueueSpecificKey, value: captureSessionQueueSpecificValue) let cam = createCam(with: captureSessionQueue) - cam.setImageFileFormat(FCPPlatformImageFileFormat.heif) + cam.setImageFileFormat(PlatformImageFileFormat.heif) let mockOutput = MockCapturePhotoOutput() mockOutput.availablePhotoCodecTypes = [AVVideoCodecType.hevc] @@ -108,10 +112,12 @@ final class PhotoCaptureTests: XCTestCase { } cam.capturePhotoOutput = mockOutput - // `FLTCam::captureToFile` runs on capture session queue. + // `Camera.captureToFile` runs on capture session queue. captureSessionQueue.async { - cam.captureToFile { filePath, error in - XCTAssertEqual((filePath! as NSString).pathExtension, "heif") + cam.captureToFile { result in + if let filePath = self.assertSuccess(result) { + XCTAssertEqual((filePath as NSString).pathExtension, "heif") + } expectation.fulfill() } } @@ -128,7 +134,7 @@ final class PhotoCaptureTests: XCTestCase { captureSessionQueue.setSpecific( key: captureSessionQueueSpecificKey, value: captureSessionQueueSpecificValue) let cam = createCam(with: captureSessionQueue) - cam.setImageFileFormat(FCPPlatformImageFileFormat.heif) + cam.setImageFileFormat(PlatformImageFileFormat.heif) let mockOutput = MockCapturePhotoOutput() mockOutput.capturePhotoWithSettingsStub = { settings, photoDelegate in @@ -142,10 +148,12 @@ final class PhotoCaptureTests: XCTestCase { } cam.capturePhotoOutput = mockOutput - // `FLTCam::captureToFile` runs on capture session queue. + // `Camera.captureToFile` runs on capture session queue. captureSessionQueue.async { - cam.captureToFile { filePath, error in - XCTAssertEqual((filePath! as NSString).pathExtension, "jpg") + cam.captureToFile { result in + if let filePath = self.assertSuccess(result) { + XCTAssertEqual((filePath as NSString).pathExtension, "jpg") + } expectation.fulfill() } } @@ -190,15 +198,51 @@ final class PhotoCaptureTests: XCTestCase { } cam.capturePhotoOutput = mockOutput - // `FLTCam::captureToFile` runs on capture session queue. + // `Camera.captureToFile` runs on capture session queue. captureSessionQueue.async { cam.setFlashMode(.torch) { _ in } - cam.captureToFile { result, error in - XCTAssertEqual(result, filePath) + cam.captureToFile { result in + if let result = self.assertSuccess(result) { + XCTAssertEqual(result, filePath) + } pathExpectation.fulfill() } } waitForExpectations(timeout: 30, handler: nil) } + + func testCaptureToFile_mustSavePhotoToCameraPicturesDirectory() { + let expectedPath = "/tmp/camera/pictures/" + let expectation = self.expectation( + description: "Photo must be saved to \(expectedPath) directory.") + + let captureSessionQueue = DispatchQueue(label: "capture_session_queue") + captureSessionQueue.setSpecific( + key: captureSessionQueueSpecificKey, value: captureSessionQueueSpecificValue) + let cam = createCam(with: captureSessionQueue) + + let mockOutput = MockCapturePhotoOutput() + mockOutput.capturePhotoWithSettingsStub = { settings, photoDelegate in + let delegate = cam.inProgressSavePhotoDelegates[settings.uniqueID] + let ioQueue = DispatchQueue(label: "io_queue") + ioQueue.async { + delegate?.completionHandler(delegate?.filePath, nil) + } + } + cam.capturePhotoOutput = mockOutput + + captureSessionQueue.async { + cam.captureToFile { result in + if let filePath = self.assertSuccess(result) { + XCTAssertTrue( + filePath.contains(expectedPath) + ) + } + expectation.fulfill() + } + } + + waitForExpectations(timeout: 30, handler: nil) + } } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/QueueUtilsTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/QueueUtilsTests.swift index 740999c3e848..29a7cc5b453c 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/QueueUtilsTests.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/QueueUtilsTests.swift @@ -6,16 +6,11 @@ import XCTest @testable import camera_avfoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - final class QueueUtilsTests: XCTestCase { func testShouldStayOnMainQueueIfCalledFromMainQueue() { let expectation = expectation(description: "Block must be run on the main queue") - FLTEnsureToRunOnMainQueue { + ensureToRunOnMainQueue { if Thread.isMainThread { expectation.fulfill() } @@ -28,7 +23,7 @@ final class QueueUtilsTests: XCTestCase { let expectation = expectation(description: "Block must be run on the main queue") DispatchQueue.global(qos: .default).async { - FLTEnsureToRunOnMainQueue { + ensureToRunOnMainQueue { if Thread.isMainThread { expectation.fulfill() } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/RunnerTests-Bridging-Header.h b/packages/camera/camera_avfoundation/example/ios/RunnerTests/RunnerTests-Bridging-Header.h deleted file mode 100644 index 5b3a1852fb82..000000000000 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/RunnerTests-Bridging-Header.h +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "ExceptionCatcher.h" diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/SampleBufferTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/SampleBufferTests.swift index 132525207769..98759f16caba 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/SampleBufferTests.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/SampleBufferTests.swift @@ -7,11 +7,6 @@ import XCTest @testable import camera_avfoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - private class FakeMediaSettingsAVWrapper: FLTCamMediaSettingsAVWrapper { let inputMock: MockAssetWriterInput @@ -44,18 +39,18 @@ private class FakeMediaSettingsAVWrapper: FLTCamMediaSettingsAVWrapper { } override func assetWriterAudioInput(withOutputSettings outputSettings: [String: Any]?) - -> FLTAssetWriterInput + -> AssetWriterInput { return inputMock } override func assetWriterVideoInput(withOutputSettings outputSettings: [String: Any]?) - -> FLTAssetWriterInput + -> AssetWriterInput { return inputMock } - override func addInput(_ writerInput: FLTAssetWriterInput, to writer: FLTAssetWriter) { + override func addInput(_ writerInput: AssetWriterInput, to writer: AssetWriter) { // No-op. } @@ -66,7 +61,7 @@ private class FakeMediaSettingsAVWrapper: FLTCamMediaSettingsAVWrapper { } } -/// Includes test cases related to sample buffer handling for FLTCam class. +/// Includes test cases related to sample buffer handling for Camera class. final class CameraSampleBufferTests: XCTestCase { private func createCamera() -> ( DefaultCamera, @@ -79,8 +74,8 @@ final class CameraSampleBufferTests: XCTestCase { let input = MockAssetWriterInput() let configuration = CameraTestUtils.createTestCameraConfiguration() - configuration.mediaSettings = FCPPlatformMediaSettings.make( - with: .medium, + configuration.mediaSettings = PlatformMediaSettings( + resolutionPreset: .medium, framesPerSecond: nil, videoBitrate: nil, audioBitrate: nil, @@ -124,7 +119,7 @@ final class CameraSampleBufferTests: XCTestCase { let deliveredPixelBuffer = camera.copyPixelBuffer()?.takeRetainedValue() XCTAssertEqual( deliveredPixelBuffer, capturedPixelBuffer, - "FLTCam must deliver the latest captured pixel buffer to copyPixelBuffer API.") + "Camera must deliver the latest captured pixel buffer to copyPixelBuffer API.") } func testDidOutputSampleBuffer_mustNotChangeSampleBufferRetainCountAfterPauseResumeRecording() { @@ -175,7 +170,7 @@ final class CameraSampleBufferTests: XCTestCase { writtenSamples.append("video") return true } - inputMock.readyForMoreMediaData = true + inputMock.isReadyForMoreMediaData = true inputMock.appendStub = { buffer in writtenSamples.append("audio") return true @@ -222,7 +217,7 @@ final class CameraSampleBufferTests: XCTestCase { } var audioAppended = false - inputMock.readyForMoreMediaData = true + inputMock.isReadyForMoreMediaData = true inputMock.appendStub = { buffer in let sampleTime = CMSampleBufferGetPresentationTimeStamp(buffer) XCTAssert(CMTIME_IS_NUMERIC(sampleTime)) @@ -262,7 +257,7 @@ final class CameraSampleBufferTests: XCTestCase { camera.startVideoRecording(completion: { error in }, messengerForStreaming: nil) - inputMock.readyForMoreMediaData = true + inputMock.isReadyForMoreMediaData = true sampleAppended = false camera.captureOutput( camera.captureVideoOutput.avOutput, @@ -270,7 +265,7 @@ final class CameraSampleBufferTests: XCTestCase { from: testVideoConnection) XCTAssertTrue(sampleAppended, "Sample was not appended.") - inputMock.readyForMoreMediaData = false + inputMock.isReadyForMoreMediaData = false sampleAppended = false camera.captureOutput( camera.captureVideoOutput.avOutput, @@ -300,7 +295,7 @@ final class CameraSampleBufferTests: XCTestCase { camera.startVideoRecording(completion: { error in }, messengerForStreaming: nil) var completionCalled = false - camera.stopVideoRecording(completion: { path, error in + camera.stopVideoRecording(completion: { result in completionCalled = true }) @@ -327,7 +322,7 @@ final class CameraSampleBufferTests: XCTestCase { return true } - inputMock.readyForMoreMediaData = true + inputMock.isReadyForMoreMediaData = true camera.startVideoRecording(completion: { error in }, messengerForStreaming: nil) @@ -359,4 +354,189 @@ final class CameraSampleBufferTests: XCTestCase { AVAudioSession.sharedInstance().category == .playAndRecord, "Category should be PlayAndRecord.") } + + func testDidOutputSampleBufferMustUseSingleOffsetForVideoAndAudio() { + let (camera, writerMock, adaptorMock, inputMock) = createCamera() + + let testVideoConnection = CameraTestUtils.createTestConnection( + camera.captureVideoOutput.avOutput) + let testAudioOutput = CameraTestUtils.createTestAudioOutput() + let testAudioConnection = CameraTestUtils.createTestConnection(testAudioOutput) + + var status = AVAssetWriter.Status.unknown + writerMock.startWritingStub = { + status = .writing + return true + } + writerMock.statusStub = { + return status + } + + var appendedTime = CMTime.invalid + + adaptorMock.appendStub = { buffer, time in + appendedTime = time + return true + } + + inputMock.isReadyForMoreMediaData = true + inputMock.appendStub = { buffer in + appendedTime = CMSampleBufferGetPresentationTimeStamp(buffer) + return true + } + + camera.startVideoRecording(completion: { error in }, messengerForStreaming: nil) + + let appendVideoSample = { (time: Int64) in + camera.captureOutput( + camera.captureVideoOutput.avOutput, + didOutput: CameraTestUtils.createTestSampleBuffer( + timestamp: CMTimeMake(value: time, timescale: 1), + duration: .invalid), + from: testVideoConnection) + } + + let appendAudioSample = { (time: Int64, duration: Int64) in + camera.captureOutput( + testAudioOutput, + didOutput: CameraTestUtils.createTestAudioSampleBuffer( + timestamp: CMTimeMake(value: time, timescale: 1), + duration: CMTimeMake(value: duration, timescale: 1)), + from: testAudioConnection) + } + + appendedTime = .invalid + camera.pauseVideoRecording() + camera.resumeVideoRecording() + appendVideoSample(1) + XCTAssertEqual(appendedTime, CMTimeMake(value: 1, timescale: 1)) + + appendedTime = .invalid + camera.pauseVideoRecording() + camera.resumeVideoRecording() + appendVideoSample(11) + XCTAssertEqual(appendedTime, .invalid) + appendVideoSample(12) + XCTAssertEqual(appendedTime, CMTimeMake(value: 2, timescale: 1)) + + appendedTime = .invalid + camera.pauseVideoRecording() + camera.resumeVideoRecording() + appendAudioSample(20, 2) + XCTAssertEqual(appendedTime, .invalid) + appendVideoSample(23) + XCTAssertEqual(appendedTime, CMTimeMake(value: 3, timescale: 1)) + + appendedTime = .invalid + camera.pauseVideoRecording() + camera.resumeVideoRecording() + appendVideoSample(28) + XCTAssertEqual(appendedTime, .invalid) + appendAudioSample(30, 2) + XCTAssertEqual(appendedTime, .invalid) + appendVideoSample(33) + XCTAssertEqual(appendedTime, .invalid) + appendAudioSample(32, 2) + XCTAssertEqual(appendedTime, CMTimeMake(value: 2, timescale: 1)) + } + + func testDidOutputSampleBufferMustConnectVideoAfterSessionInterruption() { + let (camera, writerMock, adaptorMock, inputMock) = createCamera() + + let testVideoConnection = CameraTestUtils.createTestConnection( + camera.captureVideoOutput.avOutput) + let testAudioOutput = CameraTestUtils.createTestAudioOutput() + let testAudioConnection = CameraTestUtils.createTestConnection(testAudioOutput) + + var status = AVAssetWriter.Status.unknown + writerMock.startWritingStub = { + status = .writing + return true + } + writerMock.statusStub = { + return status + } + + var appendedTime = CMTime.invalid + + adaptorMock.appendStub = { buffer, time in + appendedTime = time + return true + } + + inputMock.isReadyForMoreMediaData = true + inputMock.appendStub = { buffer in + appendedTime = CMSampleBufferGetPresentationTimeStamp(buffer) + return true + } + + camera.startVideoRecording(completion: { error in }, messengerForStreaming: nil) + + let appendVideoSample = { (time: Int64) in + camera.captureOutput( + camera.captureVideoOutput.avOutput, + didOutput: CameraTestUtils.createTestSampleBuffer( + timestamp: CMTimeMake(value: time, timescale: 1), + duration: .invalid), + from: testVideoConnection) + } + + let appendAudioSample = { (time: Int64, duration: Int64) in + camera.captureOutput( + testAudioOutput, + didOutput: CameraTestUtils.createTestAudioSampleBuffer( + timestamp: CMTimeMake(value: time, timescale: 1), + duration: CMTimeMake(value: duration, timescale: 1)), + from: testAudioConnection) + } + + appendVideoSample(1) + appendAudioSample(1, 1) + + NotificationCenter.default.post( + name: AVCaptureSession.wasInterruptedNotification, + object: camera.audioCaptureSession) + + appendedTime = .invalid + appendAudioSample(11, 1) + XCTAssertEqual(appendedTime, .invalid) + appendVideoSample(12) + XCTAssertEqual(appendedTime, CMTimeMake(value: 2, timescale: 1)) + appendedTime = .invalid + appendAudioSample(12, 1) + XCTAssertEqual(appendedTime, CMTimeMake(value: 2, timescale: 1)) + } + + func testStartVideoRecordingReportsErrorWhenStartWritingFails() { + let (camera, writerMock, _, _) = createCamera() + + // Configure the mock to return false for startWriting + writerMock.startWritingStub = { + return false + } + + // Configure a mock error + let mockError = NSError( + domain: "test", code: 123, userInfo: [NSLocalizedDescriptionKey: "Mock write error"]) + writerMock.error = mockError + + let expectation = self.expectation(description: "Completion handler called with error") + + camera.startVideoRecording( + completion: { result in + switch result { + case .failure(let error as PigeonError): + XCTAssertEqual(error.code, "IOError") + XCTAssertEqual(error.message, "AVAssetWriter failed to start writing") + XCTAssertEqual(error.details as? String, "Mock write error") + XCTAssertFalse(camera.isRecording) + expectation.fulfill() + default: + XCTFail("Expected PigeonError") + } + + }, messengerForStreaming: nil) + + waitForExpectations(timeout: 1.0, handler: nil) + } } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/SavePhotoDelegateTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/SavePhotoDelegateTests.swift index e1807bce3581..76b4430dafed 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/SavePhotoDelegateTests.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/SavePhotoDelegateTests.swift @@ -7,18 +7,13 @@ import XCTest @testable import camera_avfoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - final class SavePhotoDelegateTests: XCTestCase { func testHandlePhotoCaptureResult_mustCompleteWithErrorIfFailedToCapture() { let completionExpectation = expectation( description: "Must complete with error if failed to capture photo.") let captureError = NSError(domain: "test", code: 0, userInfo: nil) let ioQueue = DispatchQueue(label: "test") - let delegate = FLTSavePhotoDelegate(path: "test", ioQueue: ioQueue) { path, error in + let delegate = SavePhotoDelegate(path: "test", ioQueue: ioQueue) { path, error in XCTAssertEqual(captureError, error as NSError?) XCTAssertNil(path) completionExpectation.fulfill() @@ -35,7 +30,7 @@ final class SavePhotoDelegateTests: XCTestCase { let ioQueue = DispatchQueue(label: "test") let ioError = NSError( domain: "IOError", code: 0, userInfo: [NSLocalizedDescriptionKey: "Localized IO Error"]) - let delegate = FLTSavePhotoDelegate(path: "test", ioQueue: ioQueue) { path, error in + let delegate = SavePhotoDelegate(path: "test", ioQueue: ioQueue) { path, error in XCTAssertEqual(ioError, error as NSError?) XCTAssertNil(path) completionExpectation.fulfill() @@ -56,7 +51,7 @@ final class SavePhotoDelegateTests: XCTestCase { description: "Must complete with file path if succeeds to write file.") let ioQueue = DispatchQueue(label: "test") let filePath = "test" - let delegate = FLTSavePhotoDelegate(path: filePath, ioQueue: ioQueue) { path, error in + let delegate = SavePhotoDelegate(path: filePath, ioQueue: ioQueue) { path, error in XCTAssertNil(error) XCTAssertEqual(filePath, path) completionExpectation.fulfill() @@ -88,7 +83,7 @@ final class SavePhotoDelegateTests: XCTestCase { } let filePath = "test" - let delegate = FLTSavePhotoDelegate(path: filePath, ioQueue: ioQueue) { path, error in + let delegate = SavePhotoDelegate(path: filePath, ioQueue: ioQueue) { path, error in completionExpectation.fulfill() } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/StreamingTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/StreamingTests.swift index 6b6188262edd..b018a7cca12d 100644 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/StreamingTests.swift +++ b/packages/camera/camera_avfoundation/example/ios/RunnerTests/StreamingTests.swift @@ -3,32 +3,56 @@ // found in the LICENSE file. import AVFoundation +import Flutter import XCTest @testable import camera_avfoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif +private class MockEventSink: PigeonEventSink { + var eventSinkSuccessStub: ((PlatformCameraImageData?) -> Void)? -private class MockImageStreamHandler: FLTImageStreamHandler { - var eventSinkStub: ((Any?) -> Void)? + init() { + super.init({ event in }) + } + + override func success(_ event: PlatformCameraImageData?) { + eventSinkSuccessStub?(event) + } + + override func error(code: String, message: String?, details: Any?) {} + + override func endOfStream() {} +} - override var eventSink: FlutterEventSink? { +private class MockImageStreamHandler: ImageDataStreamStreamHandler, ImageStreamHandler { + var mockEventSink = MockEventSink() + var captureSessionQueue: DispatchQueue { + preconditionFailure("Attempted to access unimplemented property: captureSessionQueue") + } + var eventSink: PigeonEventSink? { + set { + } get { - if let stub = eventSinkStub { - return { event in - stub(event) - } - } - return nil + return mockEventSink } + } + + var eventSinkSuccessStub: ((PlatformCameraImageData?) -> Void)? { set { - eventSinkStub = newValue + mockEventSink.eventSinkSuccessStub = newValue + } + get { + return mockEventSink.eventSinkSuccessStub } } + override func onListen( + withArguments arguments: Any?, sink: PigeonEventSink + ) { + } + + override func onCancel(withArguments arguments: Any?) { + } } final class StreamingTests: XCTestCase { @@ -73,7 +97,7 @@ final class StreamingTests: XCTestCase { let streamingExpectation = expectation( description: "Must not call handler over maxStreamingPendingFramesCount") - handlerMock.eventSinkStub = { event in + handlerMock.eventSinkSuccessStub = { event in streamingExpectation.fulfill() } @@ -108,7 +132,7 @@ final class StreamingTests: XCTestCase { // Setup mocked event sink after the stream starts let streamingExpectation = expectation( description: "Must be able to call the handler again when receivedImageStreamData is called") - handlerMock.eventSinkStub = { event in + handlerMock.eventSinkSuccessStub = { event in streamingExpectation.fulfill() } @@ -129,7 +153,7 @@ final class StreamingTests: XCTestCase { func testIgnoresNonImageBuffers() { let (camera, testAudioOutput, _, audioSampleBuffer, testAudioConnection) = createCamera() let handlerMock = MockImageStreamHandler() - handlerMock.eventSinkStub = { event in + handlerMock.eventSinkSuccessStub = { event in XCTFail() } @@ -152,29 +176,31 @@ final class StreamingTests: XCTestCase { waitForQueueRoundTrip(with: DispatchQueue.main) } - func testImageStreamEventFormat() { + func testImageStreamEventFormat() throws { let (camera, testAudioOutput, sampleBuffer, _, testAudioConnection) = createCamera() let expectation = expectation(description: "Received a valid event") let handlerMock = MockImageStreamHandler() - handlerMock.eventSinkStub = { event in - let imageBuffer = event as! [String: Any] - - XCTAssertTrue(imageBuffer["width"] is NSNumber) - XCTAssertTrue(imageBuffer["height"] is NSNumber) - XCTAssertTrue(imageBuffer["format"] is NSNumber) - XCTAssertTrue(imageBuffer["lensAperture"] is NSNumber) - XCTAssertTrue(imageBuffer["sensorExposureTime"] is NSNumber) - XCTAssertTrue(imageBuffer["sensorSensitivity"] is NSNumber) - - let planes = imageBuffer["planes"] as! [[String: Any]] + handlerMock.eventSinkSuccessStub = { event in + guard let imageBuffer = event else { + XCTFail() + return + } + XCTAssertGreaterThan(imageBuffer.width, 0) + XCTAssertGreaterThan(imageBuffer.height, 0) + XCTAssertGreaterThan(imageBuffer.formatCode, 0) + XCTAssertGreaterThan(imageBuffer.lensAperture, 0) + XCTAssertGreaterThan(imageBuffer.sensorExposureTimeNanoseconds, 0) + XCTAssertGreaterThan(imageBuffer.sensorSensitivity, 0) + + let planes = imageBuffer.planes let planeBuffer = planes[0] - XCTAssertTrue(planeBuffer["bytesPerRow"] is NSNumber) - XCTAssertTrue(planeBuffer["width"] is NSNumber) - XCTAssertTrue(planeBuffer["height"] is NSNumber) - XCTAssertTrue(planeBuffer["bytes"] is FlutterStandardTypedData) + XCTAssertGreaterThan(planeBuffer.bytesPerRow, 0) + XCTAssertGreaterThan(planeBuffer.width, 0) + XCTAssertGreaterThan(planeBuffer.height, 0) + XCTAssertGreaterThan(planeBuffer.bytes.data.count, 0) expectation.fulfill() } diff --git a/packages/camera/camera_avfoundation/example/ios/RunnerTests/ThreadSafeEventChannelTests.swift b/packages/camera/camera_avfoundation/example/ios/RunnerTests/ThreadSafeEventChannelTests.swift deleted file mode 100644 index af064e9fd9a5..000000000000 --- a/packages/camera/camera_avfoundation/example/ios/RunnerTests/ThreadSafeEventChannelTests.swift +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import XCTest - -@testable import camera_avfoundation - -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - -final class ThreadSafeEventChannelTests: XCTestCase { - func testSetStreamHandler_shouldStayOnMainThreadIfCalledFromMainThread() { - let mockEventChannel = MockEventChannel() - let threadSafeEventChannel = FLTThreadSafeEventChannel(eventChannel: mockEventChannel) - - let mainThreadExpectation = expectation( - description: "setStreamHandler must be called on the main thread") - let mainThreadCompletionExpectation = expectation( - description: "setStreamHandler's completion block must be called on the main thread") - - mockEventChannel.setStreamHandlerStub = { handler in - if Thread.isMainThread { - mainThreadExpectation.fulfill() - } - } - threadSafeEventChannel.setStreamHandler(nil) { - if Thread.isMainThread { - mainThreadCompletionExpectation.fulfill() - } - } - - waitForExpectations(timeout: 30, handler: nil) - } - - func testSetStreamHandler_shouldDispatchToMainThreadIfCalledFromBackgroundThread() { - let mockEventChannel = MockEventChannel() - let threadSafeEventChannel = FLTThreadSafeEventChannel(eventChannel: mockEventChannel) - - let mainThreadExpectation = expectation( - description: "setStreamHandler must be called on the main thread") - let mainThreadCompletionExpectation = expectation( - description: "setStreamHandler's completion block must be called on the main thread") - - mockEventChannel.setStreamHandlerStub = { handler in - if Thread.isMainThread { - mainThreadExpectation.fulfill() - } - } - DispatchQueue.global(qos: .default).async { - threadSafeEventChannel.setStreamHandler(nil) { - if Thread.isMainThread { - mainThreadCompletionExpectation.fulfill() - } - } - } - - waitForExpectations(timeout: 30, handler: nil) - } - - func testEventChannel_shouldBeKeptAliveWhenDispatchingBackToMainThread() { - let mockEventChannel = MockEventChannel() - - let expectation = self.expectation(description: "Completion should be called.") - - DispatchQueue(label: "test").async { - let channel = FLTThreadSafeEventChannel(eventChannel: mockEventChannel) - - channel.setStreamHandler(nil) { - expectation.fulfill() - } - } - - waitForExpectations(timeout: 30, handler: nil) - } -} diff --git a/packages/camera/camera_avfoundation/example/lib/camera_controller.dart b/packages/camera/camera_avfoundation/example/lib/camera_controller.dart index 4fff05829bb5..ed3a8e5a953d 100644 --- a/packages/camera/camera_avfoundation/example/lib/camera_controller.dart +++ b/packages/camera/camera_avfoundation/example/lib/camera_controller.dart @@ -222,8 +222,7 @@ class CameraController extends ValueNotifier { Future initialize() => _initializeWithDescription(description); Future _initializeWithDescription(CameraDescription description) async { - final Completer initializeCompleter = - Completer(); + final initializeCompleter = Completer(); _deviceOrientationSubscription = CameraPlatform.instance .onDeviceOrientationChanged() @@ -503,13 +502,7 @@ class Optional extends IterableBase { const Optional.absent() : _value = null; /// Constructs an Optional of the given [value]. - /// - /// Throws [ArgumentError] if [value] is null. - Optional.of(T value) : _value = value { - // TODO(cbracken): Delete and make this ctor const once mixed-mode - // execution is no longer around. - ArgumentError.checkNotNull(value); - } + const Optional.of(T value) : _value = value; /// Constructs an Optional of the given [value]. /// diff --git a/packages/camera/camera_avfoundation/example/lib/camera_preview.dart b/packages/camera/camera_avfoundation/example/lib/camera_preview.dart index 22fb2cc4d77f..0a768b340639 100644 --- a/packages/camera/camera_avfoundation/example/lib/camera_preview.dart +++ b/packages/camera/camera_avfoundation/example/lib/camera_preview.dart @@ -62,7 +62,7 @@ class CameraPreview extends StatelessWidget { } int _getQuarterTurns() { - final Map turns = { + final turns = { DeviceOrientation.portraitUp: 0, DeviceOrientation.landscapeRight: 1, DeviceOrientation.portraitDown: 2, diff --git a/packages/camera/camera_avfoundation/example/lib/main.dart b/packages/camera/camera_avfoundation/example/lib/main.dart index 4d12a6f367d6..f9576b96398f 100644 --- a/packages/camera/camera_avfoundation/example/lib/main.dart +++ b/packages/camera/camera_avfoundation/example/lib/main.dart @@ -577,7 +577,7 @@ class _CameraExampleHomeState extends State /// Display a row of toggle to select the camera (or a message if no camera is available). Widget _cameraTogglesRowWidget() { - final List toggles = []; + final toggles = []; if (_cameras.isEmpty) { SchedulerBinding.instance.addPostFrameCallback((_) async { @@ -627,7 +627,7 @@ class _CameraExampleHomeState extends State final CameraController cameraController = controller!; - final Point point = Point( + final point = Point( details.localPosition.dx / constraints.maxWidth, details.localPosition.dy / constraints.maxHeight, ); @@ -646,7 +646,7 @@ class _CameraExampleHomeState extends State Future _initializeCameraController( CameraDescription cameraDescription, ) async { - final CameraController cameraController = CameraController( + final cameraController = CameraController( cameraDescription, kIsWeb ? ResolutionPreset.max : ResolutionPreset.medium, enableAudio: enableAudio, @@ -903,7 +903,7 @@ class _CameraExampleHomeState extends State } try { - return cameraController.stopVideoRecording(); + return await cameraController.stopVideoRecording(); } on CameraException catch (e) { _showCameraException(e); return null; @@ -1000,7 +1000,7 @@ class _CameraExampleHomeState extends State return; } - final VideoPlayerController vController = kIsWeb + final vController = kIsWeb ? VideoPlayerController.networkUrl(Uri.parse(videoFile!.path)) : VideoPlayerController.file(File(videoFile!.path)); diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation.podspec b/packages/camera/camera_avfoundation/ios/camera_avfoundation.podspec index 34722dd2ebda..d7e009b8ceaf 100644 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation.podspec +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation.podspec @@ -13,10 +13,7 @@ A Flutter plugin to use the camera from your Flutter app. s.author = { 'Flutter Dev Team' => 'flutter-dev@googlegroups.com' } s.source = { :http => 'https://github.com/flutter/packages/tree/main/packages/camera_avfoundation' } s.documentation_url = 'https://pub.dev/packages/camera_avfoundation' - # Combine camera_avfoundation and camera_avfoundation_objc sources into a single pod, unlike - # SwiftPM, where separate Swift and Objective-C targets are required. - s.source_files = 'camera_avfoundation/Sources/camera_avfoundation*/**/*.{h,m,swift}' - s.public_header_files = 'camera_avfoundation/Sources/camera_avfoundation_objc/include/**/*.h' + s.source_files = 'camera_avfoundation/Sources/camera_avfoundation/**/*.swift' s.swift_version = '5.0' s.xcconfig = { 'LIBRARY_SEARCH_PATHS' => '$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)/ $(SDKROOT)/usr/lib/swift', diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Package.swift b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Package.swift index 48fe6b56e30b..302146b1634d 100644 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Package.swift +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Package.swift @@ -13,28 +13,16 @@ let package = Package( ], products: [ .library( - name: "camera-avfoundation", targets: ["camera_avfoundation", "camera_avfoundation_objc"]) + name: "camera-avfoundation", targets: ["camera_avfoundation"]) ], dependencies: [], targets: [ .target( name: "camera_avfoundation", - dependencies: ["camera_avfoundation_objc"], path: "Sources/camera_avfoundation", resources: [ .process("Resources") ] - ), - .target( - name: "camera_avfoundation_objc", - dependencies: [], - path: "Sources/camera_avfoundation_objc", - resources: [ - .process("Resources") - ], - cSettings: [ - .headerSearchPath("include/camera_avfoundation") - ] - ), + ) ] ) diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/AssetWriter.swift b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/AssetWriter.swift new file mode 100644 index 000000000000..d86662a9b8b3 --- /dev/null +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/AssetWriter.swift @@ -0,0 +1,45 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import AVFoundation +import Foundation + +/// A protocol that is a direct passthrough to `AVAssetWriter`. It is used to allow for mocking +/// `AVAssetWriter` in tests. +protocol AssetWriter: NSObjectProtocol { + var status: AVAssetWriter.Status { get } + var error: Error? { get } + + func startWriting() -> Bool + func finishWriting(completionHandler handler: @escaping @Sendable () -> Void) + func startSession(atSourceTime startTime: CMTime) + func add(_ input: AVAssetWriterInput) +} + +/// A protocol that is a direct passthrough to `AVAssetWriterInput`. It is used to allow for mocking +/// `AVAssetWriterInput` in tests. +protocol AssetWriterInput: NSObjectProtocol { + /// The underlying `AVAssetWriterInput` instance. This exists so that the input + /// can be extracted when adding to an AVAssetWriter. + var avInput: AVAssetWriterInput { get } + + var expectsMediaDataInRealTime: Bool { get set } + var isReadyForMoreMediaData: Bool { get } + + func append(_ sampleBuffer: CMSampleBuffer) -> Bool +} + +/// A protocol that is a direct passthrough to `AVAssetWriterInputPixelBufferAdaptor`. It is used to +/// allow for mocking `AVAssetWriterInputPixelBufferAdaptor` in tests. +protocol AssetWriterInputPixelBufferAdaptor: NSObjectProtocol { + func append(_ pixelBuffer: CVPixelBuffer, withPresentationTime presentationTime: CMTime) -> Bool +} + +extension AVAssetWriter: AssetWriter {} + +extension AVAssetWriterInput: AssetWriterInput { + var avInput: AVAssetWriterInput { self } +} + +extension AVAssetWriterInputPixelBufferAdaptor: AssetWriterInputPixelBufferAdaptor {} diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/Camera.swift b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/Camera.swift index 72eb13b81023..117fd909d32e 100644 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/Camera.swift +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/Camera.swift @@ -6,18 +6,13 @@ import AVFoundation import CoreMotion import Flutter -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - /// A class that manages camera's state and performs camera operations. protocol Camera: FlutterTexture, AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureAudioDataOutputSampleBufferDelegate { /// The API instance used to communicate with the Dart side of the plugin. /// Once initially set, this should only ever be accessed on the main thread. - var dartAPI: FCPCameraEventApi? { get set } + var dartAPI: CameraEventApi? { get set } var onFrameAvailable: (() -> Void)? { get set } @@ -54,29 +49,29 @@ protocol Camera: FlutterTexture, AVCaptureVideoDataOutputSampleBufferDelegate, /// /// @param messenger Nullable messenger for capturing each frame. func startVideoRecording( - completion: @escaping (_ error: FlutterError?) -> Void, + completion: @escaping (Result) -> Void, messengerForStreaming: FlutterBinaryMessenger? ) func pauseVideoRecording() func resumeVideoRecording() - func stopVideoRecording(completion: @escaping (_ path: String?, _ error: FlutterError?) -> Void) + func stopVideoRecording(completion: @escaping (Result) -> Void) - func captureToFile(completion: @escaping (_ path: String?, _ error: FlutterError?) -> Void) + func captureToFile(completion: @escaping (Result) -> Void) - func lockCaptureOrientation(_ orientation: FCPPlatformDeviceOrientation) + func lockCaptureOrientation(_ orientation: PlatformDeviceOrientation) func unlockCaptureOrientation() - func setImageFileFormat(_ fileFormat: FCPPlatformImageFileFormat) + func setImageFileFormat(_ fileFormat: PlatformImageFileFormat) - func setExposureMode(_ mode: FCPPlatformExposureMode) + func setExposureMode(_ mode: PlatformExposureMode) func setExposureOffset(_ offset: Double) /// Sets the exposure point, in a (0,1) coordinate system. /// /// If @c point is nil, the exposure point will reset to the center. func setExposurePoint( - _ point: FCPPlatformPoint?, - withCompletion: @escaping (_ error: FlutterError?) -> Void + _ point: PlatformPoint?, + withCompletion: @escaping (Result) -> Void ) /// Sets FocusMode on the current AVCaptureDevice. @@ -90,21 +85,27 @@ protocol Camera: FlutterTexture, AVCaptureVideoDataOutputSampleBufferDelegate, /// be set. /// /// @param mode The focus mode that should be applied. - func setFocusMode(_ mode: FCPPlatformFocusMode) + func setFocusMode(_ mode: PlatformFocusMode) /// Sets the focus point, in a (0,1) coordinate system. /// /// If @c point is nil, the focus point will reset to the center. func setFocusPoint( - _ point: FCPPlatformPoint?, - completion: @escaping (_ error: FlutterError?) -> Void + _ point: PlatformPoint?, + completion: @escaping (Result) -> Void ) - func setZoomLevel(_ zoom: CGFloat, withCompletion: @escaping (_ error: FlutterError?) -> Void) + func setZoomLevel(_ zoom: CGFloat, withCompletion: @escaping (Result) -> Void) + + func setVideoStabilizationMode( + _ mode: PlatformVideoStabilizationMode, + withCompletion: @escaping (Result) -> Void) + + func isVideoStabilizationModeSupported(_ mode: PlatformVideoStabilizationMode) -> Bool func setFlashMode( - _ mode: FCPPlatformFlashMode, - withCompletion: @escaping (_ error: FlutterError?) -> Void + _ mode: PlatformFlashMode, + withCompletion: @escaping (Result) -> Void ) func pausePreview() @@ -112,11 +113,11 @@ protocol Camera: FlutterTexture, AVCaptureVideoDataOutputSampleBufferDelegate, func setDescriptionWhileRecording( _ cameraName: String, - withCompletion: @escaping (_ error: FlutterError?) -> Void + withCompletion: @escaping (Result) -> Void ) func startImageStream( - with: FlutterBinaryMessenger, completion: @escaping (_ error: FlutterError?) -> Void) + with: FlutterBinaryMessenger, completion: @escaping (Result) -> Void) func stopImageStream() // Override to make `AVCaptureVideoDataOutputSampleBufferDelegate`/ diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CameraConfiguration.swift b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CameraConfiguration.swift index 9bac99def921..83f8d40555cf 100644 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CameraConfiguration.swift +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CameraConfiguration.swift @@ -6,11 +6,6 @@ import AVFoundation import CoreMedia import UIKit -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - /// Factory block returning an FLTCaptureDevice. /// Used in tests to inject a video capture device into DefaultCamera. typealias VideoCaptureDeviceFactory = (_ cameraName: String) -> CaptureDevice @@ -19,16 +14,16 @@ typealias AudioCaptureDeviceFactory = () -> CaptureDevice typealias CaptureSessionFactory = () -> CaptureSession -typealias AssetWriterFactory = (_ assetUrl: URL, _ fileType: AVFileType) throws -> FLTAssetWriter +typealias AssetWriterFactory = (_ assetUrl: URL, _ fileType: AVFileType) throws -> AssetWriter typealias InputPixelBufferAdaptorFactory = ( - _ input: FLTAssetWriterInput, _ settings: [String: Any]? + _ input: AssetWriterInput, _ settings: [String: Any]? ) -> - FLTAssetWriterInputPixelBufferAdaptor + AssetWriterInputPixelBufferAdaptor /// A configuration object that centralizes dependencies for `DefaultCamera`. class CameraConfiguration { - var mediaSettings: FCPPlatformMediaSettings + var mediaSettings: PlatformMediaSettings var mediaSettingsWrapper: FLTCamMediaSettingsAVWrapper var captureSessionQueue: DispatchQueue var videoCaptureSession: CaptureSession @@ -44,7 +39,7 @@ class CameraConfiguration { var orientation: UIDeviceOrientation init( - mediaSettings: FCPPlatformMediaSettings, + mediaSettings: PlatformMediaSettings, mediaSettingsWrapper: FLTCamMediaSettingsAVWrapper, captureDeviceFactory: @escaping VideoCaptureDeviceFactory, audioCaptureDeviceFactory: @escaping AudioCaptureDeviceFactory, @@ -70,22 +65,14 @@ class CameraConfiguration { } self.assetWriterFactory = { url, fileType in - var error: NSError? - let writer = FLTDefaultAssetWriter(url: url, fileType: fileType, error: &error) - - if let error = error { - throw error - } - - return writer + return try AVAssetWriter(outputURL: url, fileType: fileType) } self.inputPixelBufferAdaptorFactory = { assetWriterInput, sourcePixelBufferAttributes in - let adaptor = AVAssetWriterInputPixelBufferAdaptor( - assetWriterInput: assetWriterInput.input, + return AVAssetWriterInputPixelBufferAdaptor( + assetWriterInput: assetWriterInput.avInput, sourcePixelBufferAttributes: sourcePixelBufferAttributes ) - return FLTDefaultAssetWriterInputPixelBufferAdaptor(adaptor: adaptor) } } } diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CameraDeviceDiscoverer.swift b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CameraDeviceDiscoverer.swift index 36fe9616408e..e70ed6c62fe4 100644 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CameraDeviceDiscoverer.swift +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CameraDeviceDiscoverer.swift @@ -4,11 +4,6 @@ import AVFoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - /// A protocol which abstracts the discovery of camera devices. /// It is a thin wrapper around `AVCaptureDiscoverySession` and it exists to allow mocking in tests. protocol CameraDeviceDiscoverer { diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CameraPermissionManager.swift b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CameraPermissionManager.swift new file mode 100644 index 000000000000..733351bd0716 --- /dev/null +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CameraPermissionManager.swift @@ -0,0 +1,136 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import AVFoundation +import Flutter + +/// Completion handler for camera permission requests. +typealias CameraPermissionRequestCompletionHandler = (PigeonError?) -> Void + +private enum Permission { + case camera + case audio +} + +/// Manages camera and audio permission requests. +class CameraPermissionManager: NSObject { + let permissionService: PermissionServicing + + init(permissionService: PermissionServicing) { + self.permissionService = permissionService + super.init() + } + + /// Requests camera access permission. + /// + /// If it is the first time requesting camera access, a permission dialog will show up on the + /// screen. Otherwise AVFoundation simply returns the user's previous choice, and in this case the + /// user will have to update the choice in Settings app. + /// + /// @param handler if access permission is (or was previously) granted, completion handler will be + /// called without error; Otherwise completion handler will be called with error. Handler can be + /// called on an arbitrary dispatch queue. + func requestCameraPermission( + completionHandler handler: @escaping CameraPermissionRequestCompletionHandler + ) { + requestPermission(permission: .camera, handler: handler) + } + + /// Requests audio access permission. + /// + /// If it is the first time requesting audio access, a permission dialog will show up on the + /// screen. Otherwise AVFoundation simply returns the user's previous choice, and in this case the + /// user will have to update the choice in Settings app. + /// + /// @param handler if access permission is (or was previously) granted, completion handler will be + /// called without error; Otherwise completion handler will be called with error. Handler can be + /// called on an arbitrary dispatch queue. + func requestAudioPermission( + completionHandler handler: @escaping CameraPermissionRequestCompletionHandler + ) { + requestPermission(permission: .audio, handler: handler) + } + + private func requestPermission( + permission: Permission, + handler: @escaping CameraPermissionRequestCompletionHandler + ) { + let mediaType: AVMediaType = + switch permission { + case .audio: .audio + case .camera: .video + } + + switch permissionService.authorizationStatus(for: mediaType) { + case .authorized: + handler(nil) + + case .denied: + let flutterError = + switch permission { + case .audio: + PigeonError( + code: "AudioAccessDeniedWithoutPrompt", + message: + "User has previously denied the audio access request. Go to Settings to enable audio access.", + details: nil + ) + case .camera: + PigeonError( + code: "CameraAccessDeniedWithoutPrompt", + message: + "User has previously denied the camera access request. Go to Settings to enable camera access.", + details: nil + ) + } + handler(flutterError) + + case .restricted: + let flutterError = + switch permission { + case .audio: + PigeonError( + code: "AudioAccessRestricted", + message: "Audio access is restricted.", + details: nil + ) + case .camera: + PigeonError( + code: "CameraAccessRestricted", + message: "Camera access is restricted.", + details: nil + ) + } + handler(flutterError) + + case .notDetermined: + permissionService.requestAccess(for: mediaType) { granted in + // handler can be invoked on an arbitrary dispatch queue. + if granted { + handler(nil) + } else { + let flutterError = + switch permission { + case .audio: + PigeonError( + code: "AudioAccessDenied", + message: "User denied the audio access request.", + details: nil + ) + case .camera: + PigeonError( + code: "CameraAccessDenied", + message: "User denied the camera access request.", + details: nil + ) + } + handler(flutterError) + } + } + + @unknown default: + assertionFailure("Unknown authorization status") + } + } +} diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CameraPlugin.swift b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CameraPlugin.swift index 75687209f9e8..43ef5f48916c 100644 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CameraPlugin.swift +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CameraPlugin.swift @@ -2,20 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import AVFoundation import Flutter -import ObjectiveC - -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif public final class CameraPlugin: NSObject, FlutterPlugin { private let registry: FlutterTextureRegistry private let messenger: FlutterBinaryMessenger - private let globalEventAPI: FCPCameraGlobalEventApi + private let globalEventAPI: CameraGlobalEventApiProtocol private let deviceDiscoverer: CameraDeviceDiscoverer - private let permissionManager: FLTCameraPermissionManager + private let permissionManager: CameraPermissionManager private let captureDeviceFactory: VideoCaptureDeviceFactory private let captureSessionFactory: CaptureSessionFactory private let captureDeviceInputFactory: CaptureDeviceInputFactory @@ -30,10 +25,10 @@ public final class CameraPlugin: NSObject, FlutterPlugin { let instance = CameraPlugin( registry: registrar.textures(), messenger: registrar.messenger(), - globalAPI: FCPCameraGlobalEventApi(binaryMessenger: registrar.messenger()), + globalAPI: CameraGlobalEventApi(binaryMessenger: registrar.messenger()), deviceDiscoverer: DefaultCameraDeviceDiscoverer(), - permissionManager: FLTCameraPermissionManager( - permissionService: FLTDefaultPermissionService()), + permissionManager: CameraPermissionManager( + permissionService: DefaultPermissionService()), deviceFactory: { name in // TODO(RobertOdrowaz) Implement better error handling and remove non-null assertion AVCaptureDevice(uniqueID: name)! @@ -43,15 +38,15 @@ public final class CameraPlugin: NSObject, FlutterPlugin { captureSessionQueue: DispatchQueue(label: "io.flutter.camera.captureSessionQueue") ) - SetUpFCPCameraApi(registrar.messenger(), instance) + CameraApiSetup.setUp(binaryMessenger: registrar.messenger(), api: instance) } init( registry: FlutterTextureRegistry, messenger: FlutterBinaryMessenger, - globalAPI: FCPCameraGlobalEventApi, + globalAPI: CameraGlobalEventApiProtocol, deviceDiscoverer: CameraDeviceDiscoverer, - permissionManager: FLTCameraPermissionManager, + permissionManager: CameraPermissionManager, deviceFactory: @escaping VideoCaptureDeviceFactory, captureSessionFactory: @escaping CaptureSessionFactory, captureDeviceInputFactory: CaptureDeviceInputFactory, @@ -86,8 +81,8 @@ public final class CameraPlugin: NSObject, FlutterPlugin { UIDevice.current.endGeneratingDeviceOrientationNotifications() } - private static func flutterErrorFromNSError(_ error: NSError) -> FlutterError { - return FlutterError( + private static func pigeonErrorFromNSError(_ error: NSError) -> PigeonError { + return PigeonError( code: "Error \(error.code)", message: error.localizedDescription, details: error.domain) @@ -113,8 +108,8 @@ public final class CameraPlugin: NSObject, FlutterPlugin { func sendDeviceOrientation(_ orientation: UIDeviceOrientation) { DispatchQueue.main.async { [weak self] in - self?.globalEventAPI.deviceOrientationChangedOrientation( - FCPGetPigeonDeviceOrientationForOrientation(orientation) + self?.globalEventAPI.deviceOrientationChanged( + orientation: getPigeonDeviceOrientation(for: orientation) ) { _ in // Ignore errors; this is essentially a broadcast stream, and // it's fine if the other end doesn't receive the message @@ -124,9 +119,10 @@ public final class CameraPlugin: NSObject, FlutterPlugin { } } -extension CameraPlugin: FCPCameraApi { - public func availableCameras( - completion: @escaping ([FCPPlatformCameraDescription]?, FlutterError?) -> Void +extension CameraPlugin: CameraApi { + + func getAvailableCameras( + completion: @escaping (Result<[PlatformCameraDescription], any Error>) -> Void ) { captureSessionQueue.async { [weak self] in guard let strongSelf = self else { return } @@ -142,24 +138,24 @@ extension CameraPlugin: FCPCameraApi { mediaType: .video, position: .unspecified) - var reply: [FCPPlatformCameraDescription] = [] + var reply: [PlatformCameraDescription] = [] for device in devices { let lensFacing = strongSelf.platformLensDirection(for: device) let lensType = strongSelf.platformLensType(for: device) - let cameraDescription = FCPPlatformCameraDescription.make( - withName: device.uniqueID, + let cameraDescription = PlatformCameraDescription( + name: device.uniqueID, lensDirection: lensFacing, lensType: lensType ) reply.append(cameraDescription) } - completion(reply, nil) + completion(.success(reply)) } } - private func platformLensDirection(for device: CaptureDevice) -> FCPPlatformCameraLensDirection { + private func platformLensDirection(for device: CaptureDevice) -> PlatformCameraLensDirection { switch device.position { case .back: return .back @@ -172,7 +168,7 @@ extension CameraPlugin: FCPCameraApi { } } - private func platformLensType(for device: CaptureDevice) -> FCPPlatformCameraLensType { + private func platformLensType(for device: CaptureDevice) -> PlatformCameraLensType { switch device.deviceType { case .builtInWideAngleCamera: return .wide @@ -187,10 +183,9 @@ extension CameraPlugin: FCPCameraApi { } } - public func createCamera( - withName cameraName: String, - settings: FCPPlatformMediaSettings, - completion: @escaping (NSNumber?, FlutterError?) -> Void + func create( + cameraName: String, settings: PlatformMediaSettings, + completion: @escaping (Result) -> Void ) { // Create FLTCam only if granted camera access (and audio access if audio is enabled) captureSessionQueue.async { [weak self] in @@ -198,7 +193,7 @@ extension CameraPlugin: FCPCameraApi { guard let strongSelf = self else { return } if let error = error { - completion(nil, error) + completion(.failure(error)) return } @@ -212,7 +207,7 @@ extension CameraPlugin: FCPCameraApi { guard let strongSelf = self else { return } if let audioError = audioError { - completion(nil, audioError) + completion(.failure(audioError)) return } @@ -233,8 +228,8 @@ extension CameraPlugin: FCPCameraApi { func createCameraOnSessionQueue( withName: String, - settings: FCPPlatformMediaSettings, - completion: @escaping (NSNumber?, FlutterError?) -> Void + settings: PlatformMediaSettings, + completion: @escaping (Result) -> Void ) { captureSessionQueue.async { [weak self] in self?.sessionQueueCreateCamera(name: withName, settings: settings, completion: completion) @@ -245,8 +240,8 @@ extension CameraPlugin: FCPCameraApi { // to make it easier to reason about strong/weak self pointers. private func sessionQueueCreateCamera( name: String, - settings: FCPPlatformMediaSettings, - completion: @escaping (NSNumber?, FlutterError?) -> Void + settings: PlatformMediaSettings, + completion: @escaping (Result) -> Void ) { let mediaSettingsAVWrapper = FLTCamMediaSettingsAVWrapper() @@ -267,19 +262,18 @@ extension CameraPlugin: FCPCameraApi { camera?.close() camera = newCamera - FLTEnsureToRunOnMainQueue { [weak self] in + ensureToRunOnMainQueue { [weak self] in guard let strongSelf = self else { return } - completion(NSNumber(value: strongSelf.registry.register(newCamera)), nil) + completion(.success(strongSelf.registry.register(newCamera))) } } catch let error as NSError { - completion(nil, CameraPlugin.flutterErrorFromNSError(error)) + completion(.failure(CameraPlugin.pigeonErrorFromNSError(error))) } } - public func initializeCamera( - _ cameraId: Int, - withImageFormat imageFormat: FCPPlatformImageFormatGroup, - completion: @escaping (FlutterError?) -> Void + func initialize( + cameraId: Int64, imageFormat: PlatformImageFormatGroup, + completion: @escaping (Result) -> Void ) { captureSessionQueue.async { [weak self] in self?.sessionQueueInitializeCamera( @@ -292,24 +286,24 @@ extension CameraPlugin: FCPCameraApi { // This must be called on captureSessionQueue. It is extracted from initializeCamera to make it // easier to reason about strong/weak self pointers. private func sessionQueueInitializeCamera( - _ cameraId: Int, - withImageFormat imageFormat: FCPPlatformImageFormatGroup, - completion: @escaping (FlutterError?) -> Void + _ cameraId: Int64, + withImageFormat imageFormat: PlatformImageFormatGroup, + completion: @escaping (Result) -> Void ) { guard let camera = camera else { return } - camera.videoFormat = FCPGetPixelFormatForPigeonFormat(imageFormat) + camera.videoFormat = getPixelFormat(for: imageFormat) camera.onFrameAvailable = { [weak self] in guard let camera = self?.camera else { return } if !camera.isPreviewPaused { - FLTEnsureToRunOnMainQueue { + ensureToRunOnMainQueue { self?.registry.textureFrameAvailable(Int64(cameraId)) } } } - camera.dartAPI = FCPCameraEventApi( + camera.dartAPI = CameraEventApi( binaryMessenger: messenger, messageChannelSuffix: "\(cameraId)" ) @@ -317,77 +311,75 @@ extension CameraPlugin: FCPCameraApi { camera.reportInitializationState() sendDeviceOrientation(UIDevice.current.orientation) camera.start() - completion(nil) + completion(.success(())) } - public func startImageStream(completion: @escaping (FlutterError?) -> Void) { + func startImageStream(completion: @escaping (Result) -> Void) { captureSessionQueue.async { [weak self] in guard let strongSelf = self else { - completion(nil) + completion(.success(())) return } strongSelf.camera?.startImageStream(with: strongSelf.messenger, completion: completion) } } - public func stopImageStream(completion: @escaping (FlutterError?) -> Void) { + func stopImageStream(completion: @escaping (Result) -> Void) { captureSessionQueue.async { [weak self] in self?.camera?.stopImageStream() - completion(nil) + completion(.success(())) } } - public func receivedImageStreamData(completion: @escaping (FlutterError?) -> Void) { + func receivedImageStreamData(completion: @escaping (Result) -> Void) { captureSessionQueue.async { [weak self] in self?.camera?.receivedImageStreamData() - completion(nil) + completion(.success(())) } } - public func disposeCamera(_ cameraId: Int, completion: @escaping (FlutterError?) -> Void) { + func dispose(cameraId: Int64, completion: @escaping (Result) -> Void) { registry.unregisterTexture(Int64(cameraId)) captureSessionQueue.async { [weak self] in if let strongSelf = self { strongSelf.camera?.close() strongSelf.camera = nil } - completion(nil) + completion(.success(())) } } - public func lockCapture( - _ orientation: FCPPlatformDeviceOrientation, - completion: @escaping (FlutterError?) -> Void + func lockCaptureOrientation( + orientation: PlatformDeviceOrientation, completion: @escaping (Result) -> Void ) { captureSessionQueue.async { [weak self] in self?.camera?.lockCaptureOrientation(orientation) - completion(nil) + completion(.success(())) } } - public func unlockCaptureOrientation(completion: @escaping (FlutterError?) -> Void) { + func unlockCaptureOrientation(completion: @escaping (Result) -> Void) { captureSessionQueue.async { [weak self] in self?.camera?.unlockCaptureOrientation() - completion(nil) + completion(.success(())) } } - public func takePicture(completion: @escaping (String?, FlutterError?) -> Void) { + func takePicture(completion: @escaping (Result) -> Void) { captureSessionQueue.async { [weak self] in self?.camera?.captureToFile(completion: completion) } } - public func prepareForVideoRecording(completion: @escaping (FlutterError?) -> Void) { + func prepareForVideoRecording(completion: @escaping (Result) -> Void) { captureSessionQueue.async { [weak self] in self?.camera?.setUpCaptureSessionForAudioIfNeeded() - completion(nil) + completion(.success(())) } } - public func startVideoRecording( - withStreaming enableStream: Bool, - completion: @escaping (FlutterError?) -> Void + func startVideoRecording( + enableStream: Bool, completion: @escaping (Result) -> Void ) { captureSessionQueue.async { [weak self] in guard let strongSelf = self else { return } @@ -397,153 +389,170 @@ extension CameraPlugin: FCPCameraApi { } } - public func stopVideoRecording(completion: @escaping (String?, FlutterError?) -> Void) { + func stopVideoRecording(completion: @escaping (Result) -> Void) { captureSessionQueue.async { [weak self] in self?.camera?.stopVideoRecording(completion: completion) } } - public func pauseVideoRecording(completion: @escaping (FlutterError?) -> Void) { + func pauseVideoRecording(completion: @escaping (Result) -> Void) { captureSessionQueue.async { [weak self] in self?.camera?.pauseVideoRecording() - completion(nil) + completion(.success(())) } } - public func resumeVideoRecording(completion: @escaping (FlutterError?) -> Void) { + func resumeVideoRecording(completion: @escaping (Result) -> Void) { captureSessionQueue.async { [weak self] in self?.camera?.resumeVideoRecording() - completion(nil) + completion(.success(())) } } - public func setFlashMode( - _ mode: FCPPlatformFlashMode, - completion: @escaping (FlutterError?) -> Void + func setFlashMode( + mode: PlatformFlashMode, completion: @escaping (Result) -> Void ) { captureSessionQueue.async { [weak self] in self?.camera?.setFlashMode(mode, withCompletion: completion) } } - public func setExposureMode( - _ mode: FCPPlatformExposureMode, - completion: @escaping (FlutterError?) -> Void + func setExposureMode( + mode: PlatformExposureMode, completion: @escaping (Result) -> Void ) { captureSessionQueue.async { [weak self] in self?.camera?.setExposureMode(mode) - completion(nil) + completion(.success(())) } } - public func setExposurePoint( - _ point: FCPPlatformPoint?, - completion: @escaping (FlutterError?) -> Void + func setExposurePoint( + point: PlatformPoint?, completion: @escaping (Result) -> Void ) { captureSessionQueue.async { [weak self] in self?.camera?.setExposurePoint(point, withCompletion: completion) } } - public func getMinimumExposureOffset(_ completion: @escaping (NSNumber?, FlutterError?) -> Void) { + func getMinExposureOffset(completion: @escaping (Result) -> Void) { captureSessionQueue.async { [weak self] in if let minOffset = self?.camera?.minimumExposureOffset { - completion(NSNumber(value: minOffset), nil) + completion(.success(minOffset)) } else { - completion(nil, nil) + completion(.success(0)) } } } - public func getMaximumExposureOffset(_ completion: @escaping (NSNumber?, FlutterError?) -> Void) { + func getMaxExposureOffset(completion: @escaping (Result) -> Void) { captureSessionQueue.async { [weak self] in if let maxOffset = self?.camera?.maximumExposureOffset { - completion(NSNumber(value: maxOffset), nil) + completion(.success(maxOffset)) } else { - completion(nil, nil) + completion(.success(0)) } } } - public func setExposureOffset(_ offset: Double, completion: @escaping (FlutterError?) -> Void) { + func setExposureOffset(offset: Double, completion: @escaping (Result) -> Void) { captureSessionQueue.async { [weak self] in self?.camera?.setExposureOffset(offset) - completion(nil) + completion(.success(())) } } - public func setFocusMode( - _ mode: FCPPlatformFocusMode, - completion: @escaping (FlutterError?) -> Void + func setFocusMode( + mode: PlatformFocusMode, completion: @escaping (Result) -> Void ) { captureSessionQueue.async { [weak self] in self?.camera?.setFocusMode(mode) - completion(nil) + completion(.success(())) } } - public func setFocus(_ point: FCPPlatformPoint?, completion: @escaping (FlutterError?) -> Void) { + func setFocusPoint(point: PlatformPoint?, completion: @escaping (Result) -> Void) + { captureSessionQueue.async { [weak self] in self?.camera?.setFocusPoint(point, completion: completion) } } - public func getMinimumZoomLevel(_ completion: @escaping (NSNumber?, FlutterError?) -> Void) { + func getMinZoomLevel(completion: @escaping (Result) -> Void) { captureSessionQueue.async { [weak self] in if let minZoom = self?.camera?.minimumAvailableZoomFactor { - completion(NSNumber(value: minZoom), nil) + completion(.success(minZoom)) } else { - completion(nil, nil) + completion(.success(0)) } } } - public func getMaximumZoomLevel(_ completion: @escaping (NSNumber?, FlutterError?) -> Void) { + func getMaxZoomLevel(completion: @escaping (Result) -> Void) { captureSessionQueue.async { [weak self] in if let maxZoom = self?.camera?.maximumAvailableZoomFactor { - completion(NSNumber(value: maxZoom), nil) + completion(.success(maxZoom)) } else { - completion(nil, nil) + completion(.success(0)) } } } - public func setZoomLevel(_ zoom: Double, completion: @escaping (FlutterError?) -> Void) { + func setZoomLevel(zoom: Double, completion: @escaping (Result) -> Void) { captureSessionQueue.async { [weak self] in self?.camera?.setZoomLevel(zoom, withCompletion: completion) } } - public func pausePreview(completion: @escaping (FlutterError?) -> Void) { + func setVideoStabilizationMode( + mode: PlatformVideoStabilizationMode, completion: @escaping (Result) -> Void + ) { + captureSessionQueue.async { [weak self] in + self?.camera?.setVideoStabilizationMode(mode, withCompletion: completion) + } + } + + func isVideoStabilizationModeSupported( + mode: PlatformVideoStabilizationMode, + completion: @escaping (Result) -> Void + ) { + captureSessionQueue.async { [weak self] in + if let camera = self?.camera { + let isSupported = camera.isVideoStabilizationModeSupported(mode) + completion(.success(isSupported)) + } else { + completion(.success(false)) + } + } + } + + func pausePreview(completion: @escaping (Result) -> Void) { captureSessionQueue.async { [weak self] in self?.camera?.pausePreview() - completion(nil) + completion(.success(())) } } - public func resumePreview(completion: @escaping (FlutterError?) -> Void) { + func resumePreview(completion: @escaping (Result) -> Void) { captureSessionQueue.async { [weak self] in self?.camera?.resumePreview() - completion(nil) + completion(.success(())) } } - public func updateDescriptionWhileRecordingCameraName( - _ cameraName: String, - completion: @escaping (FlutterError?) -> Void + func updateDescriptionWhileRecording( + cameraName: String, completion: @escaping (Result) -> Void ) { captureSessionQueue.async { [weak self] in self?.camera?.setDescriptionWhileRecording(cameraName, withCompletion: completion) } } - public func setImageFileFormat( - _ format: FCPPlatformImageFileFormat, - completion: @escaping (FlutterError?) -> Void + func setImageFileFormat( + format: PlatformImageFileFormat, completion: @escaping (Result) -> Void ) { captureSessionQueue.async { [weak self] in self?.camera?.setImageFileFormat(format) - completion(nil) + completion(.success(())) } } } diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CameraProperties.swift b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CameraProperties.swift new file mode 100644 index 000000000000..a7dfd4551048 --- /dev/null +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CameraProperties.swift @@ -0,0 +1,102 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import AVFoundation +import UIKit + +/// Gets AVCaptureFlashMode from PlatformFlashMode. +/// mode - flash mode. +func getAVCaptureFlashMode(for mode: PlatformFlashMode) -> AVCaptureDevice.FlashMode { + switch mode { + case .off: + return .off + case .auto: + return .auto + case .always: + return .on + case .torch: + assertionFailure("This mode cannot be converted, and requires custom handling.") + return .off + @unknown default: + assertionFailure("Unknown flash mode") + return .off + } +} + +/// Gets UIDeviceOrientation from its Pigeon representation. +/// orientation - the Pigeon device orientation. +func getUIDeviceOrientation( + for orientation: PlatformDeviceOrientation +) -> UIDeviceOrientation { + switch orientation { + case .portraitDown: + return .portraitUpsideDown + case .landscapeLeft: + return .landscapeLeft + case .landscapeRight: + return .landscapeRight + case .portraitUp: + return .portrait + @unknown default: + assertionFailure("Unknown device orientation") + return .portrait + } +} + +/// Gets a Pigeon representation of UIDeviceOrientation. +/// orientation - the UIDeviceOrientation. +func getPigeonDeviceOrientation( + for orientation: UIDeviceOrientation +) -> PlatformDeviceOrientation { + switch orientation { + case .portraitUpsideDown: + return .portraitDown + case .landscapeLeft: + return .landscapeLeft + case .landscapeRight: + return .landscapeRight + case .portrait: + return .portraitUp + default: + return .portraitUp + } +} + +/// Gets pixel format from its Pigeon representation. +/// imageFormat - the Pigeon image format. +func getPixelFormat(for imageFormat: PlatformImageFormatGroup) -> OSType { + switch imageFormat { + case .bgra8888: + return kCVPixelFormatType_32BGRA + case .yuv420: + return kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange + @unknown default: + assertionFailure("Unknown image format") + return kCVPixelFormatType_32BGRA + } +} + +/// Gets video stabilization mode from its Pigeon representation. +/// videoStabilizationMode - the Pigeon video stabilization mode. +func getAvCaptureVideoStabilizationMode( + _ videoStabilizationMode: PlatformVideoStabilizationMode +) -> AVCaptureVideoStabilizationMode { + + switch videoStabilizationMode { + case .off: + return .off + case .standard: + return .standard + case .cinematic: + return .cinematic + case .cinematicExtended: + if #available(iOS 13.0, *) { + return .cinematicExtended + } else { + return .cinematic + } + @unknown default: + return .off + } +} diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CaptureConnection.swift b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CaptureConnection.swift new file mode 100644 index 000000000000..d119afb9474a --- /dev/null +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CaptureConnection.swift @@ -0,0 +1,30 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import AVFoundation + +/// A protocol which is a direct passthrough to `AVCaptureConnection`. It exists to allow replacing +/// `AVCaptureConnection` in tests. +protocol CaptureConnection: NSObjectProtocol { + /// Corresponds to the `isVideoMirrored` property of `AVCaptureConnection` + var isVideoMirrored: Bool { get set } + + /// Corresponds to the `videoOrientation` property of `AVCaptureConnection` + var videoOrientation: AVCaptureVideoOrientation { get set } + + /// Corresponds to the `inputPorts` property of `AVCaptureConnection` + var inputPorts: [AVCaptureInput.Port] { get } + + /// Corresponds to the `supportsVideoMirroring` property of `AVCaptureConnection` + var isVideoMirroringSupported: Bool { get } + + /// Corresponds to the `supportsVideoOrientation` property of `AVCaptureConnection` + var isVideoOrientationSupported: Bool { get } + + /// Corresponds to the preferredVideoStabilizationMode property of `AVCaptureConnection` + var preferredVideoStabilizationMode: AVCaptureVideoStabilizationMode { get set } + +} + +extension AVCaptureConnection: CaptureConnection {} diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CaptureDevice.swift b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CaptureDevice.swift index c8d6437ceef8..b007cb39b4d1 100644 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CaptureDevice.swift +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CaptureDevice.swift @@ -4,11 +4,6 @@ import AVFoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - /// A protocol which is a direct passthrough to AVCaptureDevice. /// It exists to allow replacing AVCaptureDevice in tests. protocol CaptureDevice: NSObjectProtocol { @@ -27,8 +22,8 @@ protocol CaptureDevice: NSObjectProtocol { var deviceType: AVCaptureDevice.DeviceType { get } // Format/Configuration - var flutterActiveFormat: FLTCaptureDeviceFormat { get set } - var flutterFormats: [FLTCaptureDeviceFormat] { get } + var flutterActiveFormat: CaptureDeviceFormat { get set } + var flutterFormats: [CaptureDeviceFormat] { get } // Flash/Torch var hasFlash: Bool { get } @@ -58,6 +53,10 @@ protocol CaptureDevice: NSObjectProtocol { var minAvailableVideoZoomFactor: CGFloat { get } var videoZoomFactor: CGFloat { get set } + // Video Stabilization + func isVideoStabilizationModeSupported(_ videoStabilizationMode: AVCaptureVideoStabilizationMode) + -> Bool + // Camera Properties var lensAperture: Float { get } var exposureDuration: CMTime { get } @@ -91,14 +90,19 @@ protocol CaptureDeviceInputFactory: NSObjectProtocol { extension AVCaptureDevice: CaptureDevice { var avDevice: AVCaptureDevice { self } - var flutterActiveFormat: FLTCaptureDeviceFormat { - get { FLTDefaultCaptureDeviceFormat.init(format: activeFormat) } - set { activeFormat = newValue.format } + var flutterActiveFormat: CaptureDeviceFormat { + get { activeFormat } + set { activeFormat = newValue.avFormat } } - var flutterFormats: [FLTCaptureDeviceFormat] { - return self.formats.map { FLTDefaultCaptureDeviceFormat.init(format: $0) } + var flutterFormats: [CaptureDeviceFormat] { formats } + + func isVideoStabilizationModeSupported(_ videoStabilizationMode: AVCaptureVideoStabilizationMode) + -> Bool + { + return self.activeFormat.isVideoStabilizationModeSupported(videoStabilizationMode) } + } extension AVCaptureInput: CaptureInput { diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CaptureDeviceFormat.swift b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CaptureDeviceFormat.swift new file mode 100644 index 000000000000..6905e36a9533 --- /dev/null +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CaptureDeviceFormat.swift @@ -0,0 +1,31 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import AVFoundation + +/// A protocol which is a direct passthrough to `AVFrameRateRange`. It exists to allow replacing +/// `AVFrameRateRange` in tests as it has no public initializer. +protocol FrameRateRange: NSObjectProtocol { + var minFrameRate: Float64 { get } + var maxFrameRate: Float64 { get } +} + +/// A protocol which is a direct passthrough to `AVCaptureDeviceFormat`. It exists to allow +/// replacing `AVCaptureDeviceFormat` in tests as it has no public initializer. +protocol CaptureDeviceFormat: NSObjectProtocol { + /// The underlying `AVCaptureDeviceFormat` instance. This exists so that the format + /// can be extracted when setting the active format on a device. + var avFormat: AVCaptureDevice.Format { get } + + var formatDescription: CMFormatDescription { get } + var flutterVideoSupportedFrameRateRanges: [FrameRateRange] { get } +} + +extension AVFrameRateRange: FrameRateRange {} + +extension AVCaptureDevice.Format: CaptureDeviceFormat { + var avFormat: AVCaptureDevice.Format { self } + + var flutterVideoSupportedFrameRateRanges: [FrameRateRange] { videoSupportedFrameRateRanges } +} diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CaptureOutput.swift b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CaptureOutput.swift index fba320728d60..5506c017d25e 100644 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CaptureOutput.swift +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CaptureOutput.swift @@ -3,18 +3,12 @@ // found in the LICENSE file. import AVFoundation -import Foundation - -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif /// A protocol which is a direct passthrough to `AVCaptureOutput`. It exists to allow mocking /// `AVCaptureOutput` in tests. protocol CaptureOutput { /// Returns a connection with the specified media type, or nil if no such connection exists. - func connection(with mediaType: AVMediaType) -> FLTCaptureConnection? + func connection(with mediaType: AVMediaType) -> CaptureConnection? } /// A protocol which is a direct passthrough to `AVCaptureVideoDataOutput`. It exists to allow @@ -26,6 +20,9 @@ protocol CaptureVideoDataOutput: CaptureOutput { /// Corresponds to the `alwaysDiscardsLateVideoFrames` property of `AVCaptureVideoDataOutput` var alwaysDiscardsLateVideoFrames: Bool { get set } + /// Corresponds to the `availableVideoPixelFormatTypes` property of `AVCaptureVideoDataOutput` + var availableVideoPixelFormatTypes: [FourCharCode] { get } + /// Corresponds to the `videoSettings` property of `AVCaptureVideoDataOutput` var videoSettings: [String: Any]! { get set } @@ -41,9 +38,9 @@ extension AVCaptureVideoDataOutput: CaptureVideoDataOutput { return self } - func connection(with mediaType: AVMediaType) -> FLTCaptureConnection? { - guard let connection: AVCaptureConnection = connection(with: mediaType) else { return nil } - return FLTDefaultCaptureConnection(connection: connection) + func connection(with mediaType: AVMediaType) -> CaptureConnection? { + let connection: AVCaptureConnection? = connection(with: mediaType) + return connection } } @@ -72,8 +69,9 @@ extension AVCapturePhotoOutput: CapturePhotoOutput { return self } - func connection(with mediaType: AVMediaType) -> FLTCaptureConnection? { - guard let connection: AVCaptureConnection = connection(with: mediaType) else { return nil } - return FLTDefaultCaptureConnection(connection: connection) + func connection(with mediaType: AVMediaType) -> CaptureConnection? { + // Explicit type is required to access the underlying AVCapturePhotoOutput.connection method + let connection: AVCaptureConnection? = connection(with: mediaType) + return connection } } diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CaptureSession.swift b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CaptureSession.swift index 253abdabc0c4..b93d2c93b10e 100644 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CaptureSession.swift +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/CaptureSession.swift @@ -4,11 +4,6 @@ import AVFoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - /// A protocol which is a direct passthrough to AVCaptureSession. /// It exists to allow replacing AVCaptureSession in tests. protocol CaptureSession: NSObjectProtocol { @@ -16,6 +11,7 @@ protocol CaptureSession: NSObjectProtocol { var inputs: [AVCaptureInput] { get } var outputs: [AVCaptureOutput] { get } var automaticallyConfiguresApplicationAudioSession: Bool { get set } + var isRunning: Bool { get } func beginConfiguration() func commitConfiguration() diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/DefaultCamera.swift b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/DefaultCamera.swift index 29a3afd9d5b4..16d1637d23fa 100644 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/DefaultCamera.swift +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/DefaultCamera.swift @@ -2,15 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +import AVFoundation import CoreMotion - -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif +import Flutter final class DefaultCamera: NSObject, Camera { - var dartAPI: FCPCameraEventApi? + var dartAPI: CameraEventApi? var onFrameAvailable: (() -> Void)? var videoFormat: FourCharCode = kCVPixelFormatType_32BGRA { @@ -40,11 +37,12 @@ final class DefaultCamera: NSObject, Camera { /// All DefaultCamera's state access and capture session related operations should be run on this queue. private let captureSessionQueue: DispatchQueue - private let mediaSettings: FCPPlatformMediaSettings + private let mediaSettings: PlatformMediaSettings + private var framesPerSecond: Double? private let mediaSettingsAVWrapper: FLTCamMediaSettingsAVWrapper - private let videoCaptureSession: CaptureSession - private let audioCaptureSession: CaptureSession + let videoCaptureSession: CaptureSession + let audioCaptureSession: CaptureSession /// A wrapper for AVCaptureDevice creation to allow for dependency injection in tests. private let videoCaptureDeviceFactory: VideoCaptureDeviceFactory @@ -67,20 +65,20 @@ final class DefaultCamera: NSObject, Camera { var capturePhotoOutput: CapturePhotoOutput private var captureVideoInput: CaptureInput - private var videoWriter: FLTAssetWriter? - private var videoWriterInput: FLTAssetWriterInput? - private var audioWriterInput: FLTAssetWriterInput? - private var assetWriterPixelBufferAdaptor: FLTAssetWriterInputPixelBufferAdaptor? - private var videoAdaptor: FLTAssetWriterInputPixelBufferAdaptor? + private var videoWriter: AssetWriter? + private var videoWriterInput: AssetWriterInput? + private var audioWriterInput: AssetWriterInput? + private var assetWriterPixelBufferAdaptor: AssetWriterInputPixelBufferAdaptor? + private var videoAdaptor: AssetWriterInputPixelBufferAdaptor? - /// A dictionary to retain all in-progress FLTSavePhotoDelegates. The key of the dictionary is the + /// A dictionary to retain all in-progress SavePhotoDelegates. The key of the dictionary is the /// AVCapturePhotoSettings's uniqueID for each photo capture operation, and the value is the - /// FLTSavePhotoDelegate that handles the result of each photo capture operation. Note that photo + /// SavePhotoDelegate that handles the result of each photo capture operation. Note that photo /// capture operations may overlap, so FLTCam has to keep track of multiple delegates in progress, /// instead of just a single delegate reference. - private(set) var inProgressSavePhotoDelegates = [Int64: FLTSavePhotoDelegate]() + private(set) var inProgressSavePhotoDelegates = [Int64: SavePhotoDelegate]() - private var imageStreamHandler: FLTImageStreamHandler? + private var imageStreamHandler: ImageStreamHandler? private var previewSize: CGSize? var deviceOrientation: UIDeviceOrientation { @@ -95,16 +93,20 @@ final class DefaultCamera: NSObject, Camera { private var latestPixelBuffer: CVPixelBuffer? private var videoRecordingPath: String? - private var isRecording = false + private(set) var isRecording = false private var isRecordingPaused = false private var isFirstVideoSample = false - private var videoIsDisconnected = false - private var audioIsDisconnected = false private var isAudioSetup = false - private var lastVideoSampleTime = CMTime.zero - private var lastAudioSampleTime = CMTime.zero - private var videoTimeOffset = CMTime.zero - private var audioTimeOffset = CMTime.zero + /// Time of the end of the last sample. + private var lastSampleEndTime = CMTime.invalid + /// Whether the recording is disconnected. + private var isRecordingDisconnected = false + /// Represents sum of all pauses/interruptions during recording. + private var recordingTimeOffset = CMTime.invalid + /// Output to use for adjusting of recording time offset. + private var outputForOffsetAdjusting: AVCaptureOutput? + /// Time of the last appended video sample. + private var lastAppendedVideoSampleTime = CMTime.invalid /// True when images from the camera are being streamed. private(set) var isStreamingImages = false @@ -118,14 +120,14 @@ final class DefaultCamera: NSObject, Camera { /// https://github.com/flutter/plugins/pull/4520#discussion_r766335637 private var maxStreamingPendingFramesCount = 4 - private var fileFormat = FCPPlatformImageFileFormat.jpeg + private var fileFormat = PlatformImageFileFormat.jpeg private var lockedCaptureOrientation = UIDeviceOrientation.unknown - private var exposureMode = FCPPlatformExposureMode.auto - private var focusMode = FCPPlatformFocusMode.auto - private var flashMode: FCPPlatformFlashMode + private var exposureMode = PlatformExposureMode.auto + private var focusMode = PlatformFocusMode.auto + private var flashMode: PlatformFlashMode - private static func flutterErrorFromNSError(_ error: NSError) -> FlutterError { - return FlutterError( + private static func pigeonErrorFromNSError(_ error: NSError) -> PigeonError { + return PigeonError( code: "Error \(error.code)", message: error.localizedDescription, details: error.domain) @@ -201,7 +203,7 @@ final class DefaultCamera: NSObject, Camera { motionManager.startAccelerometerUpdates() - if mediaSettings.framesPerSecond != nil { + if configuration.mediaSettings.framesPerSecond != nil { // The frame rate can be changed only on a locked for configuration device. try mediaSettingsAVWrapper.lockDevice(captureDevice) defer { mediaSettingsAVWrapper.unlockDevice(captureDevice) } @@ -211,14 +213,14 @@ final class DefaultCamera: NSObject, Camera { try setCaptureSessionPreset(mediaSettings.resolutionPreset) - FormatUtils.selectBestFormat( + (captureDevice.flutterActiveFormat, framesPerSecond) = FormatUtils.findBestFormat( for: captureDevice, mediaSettings: mediaSettings, videoDimensionsConverter: videoDimensionsConverter) - if let framesPerSecond = mediaSettings.framesPerSecond { + if let framesPerSecond = framesPerSecond { // Set frame rate with 1/10 precision allowing non-integral values. - let fpsNominator = floor(framesPerSecond.doubleValue * 10.0) + let fpsNominator = floor(framesPerSecond * 10.0) let duration = CMTimeMake(value: 10, timescale: Int32(fpsNominator)) mediaSettingsAVWrapper.setMinFrameDuration(duration, on: captureDevice) @@ -231,6 +233,33 @@ final class DefaultCamera: NSObject, Camera { } updateOrientation() + + // Handle video and audio interruptions and errors. Interruption can happen for example by + // an incoming call during video recording. Error can happen for example when recording starts + // during an incoming call. + // https://github.com/flutter/flutter/issues/151253 + for session in [videoCaptureSession, audioCaptureSession] { + NotificationCenter.default.addObserver( + self, + selector: #selector(captureSessionWasInterrupted), + name: AVCaptureSession.wasInterruptedNotification, + object: session) + + NotificationCenter.default.addObserver( + self, + selector: #selector(captureSessionRuntimeError), + name: AVCaptureSession.runtimeErrorNotification, + object: session) + } + } + + @objc private func captureSessionWasInterrupted(notification: NSNotification) { + isRecordingDisconnected = true + } + + @objc private func captureSessionRuntimeError(notification: NSNotification) { + reportErrorMessage( + "\(String(describing: notification.userInfo?[AVCaptureSessionErrorKey] as? Error))") } // Possible values for presets are hard-coded in FLT interface having @@ -239,7 +268,7 @@ final class DefaultCamera: NSObject, Camera { // fallback to lower resolution presets. // If none can be selected there is error condition. private func setCaptureSessionPreset( - _ resolutionPreset: FCPPlatformResolutionPreset + _ resolutionPreset: PlatformResolutionPreset ) throws { switch resolutionPreset { case .max: @@ -306,23 +335,40 @@ final class DefaultCamera: NSObject, Camera { audioCaptureSession.sessionPreset = videoCaptureSession.sessionPreset } - /// Finds the highest available resolution in terms of pixel count for the given device. + /// Finds the highest available non-square resolution in terms of pixel count for the given device. /// Preferred are formats with the same subtype as current activeFormat. private func highestResolutionFormat(forCaptureDevice captureDevice: CaptureDevice) - -> FLTCaptureDeviceFormat? + -> CaptureDeviceFormat? { let preferredSubType = CMFormatDescriptionGetMediaSubType( captureDevice.flutterActiveFormat.formatDescription) - var bestFormat: FLTCaptureDeviceFormat? = nil + var bestFormat: CaptureDeviceFormat? = nil var maxPixelCount: UInt = 0 var isBestSubTypePreferred = false + // These formats are compressed and lossy, and unsupported by the Flutter Engine. + let unsupportedSubTypes: [FourCharCode] = [ + 1_651_798_066 // Hex for 'btp2', or kCVPixelFormatType_96VersatileBayerPacked12 + ] + for format in captureDevice.flutterFormats { + let subType = CMFormatDescriptionGetMediaSubType(format.formatDescription) + + // Skip formats that will crash the Flutter Engine + if unsupportedSubTypes.contains(subType) { + continue + } + let resolution = videoDimensionsConverter(format) let height = UInt(resolution.height) let width = UInt(resolution.width) + + // Guard against 1:1 resolutions provided by the iPhone 17 centre stage sensor. + if height == width { + continue + } + let pixelCount = height * width - let subType = CMFormatDescriptionGetMediaSubType(format.formatDescription) let isSubTypePreferred = subType == preferredSubType if pixelCount > maxPixelCount @@ -333,7 +379,6 @@ final class DefaultCamera: NSObject, Camera { isBestSubTypePreferred = isSubTypePreferred } } - return bestFormat } @@ -425,10 +470,10 @@ final class DefaultCamera: NSObject, Camera { func reportInitializationState() { // Get all the state on the current thread, not the main thread. - let state = FCPPlatformCameraState.make( - withPreviewSize: FCPPlatformSize.make( + let state = PlatformCameraState( + previewSize: PlatformSize( // previewSize is set during init, so it will never be nil. - withWidth: previewSize!.width, + width: previewSize!.width, height: previewSize!.height ), exposureMode: exposureMode, @@ -437,8 +482,8 @@ final class DefaultCamera: NSObject, Camera { focusPointSupported: captureDevice.isFocusPointOfInterestSupported ) - FLTEnsureToRunOnMainQueue { [weak self] in - self?.dartAPI?.initialized(with: state) { _ in + ensureToRunOnMainQueue { [weak self] in + self?.dartAPI?.initialized(initialState: state) { _ in // Ignore any errors, as this is just an event broadcast. } } @@ -459,15 +504,16 @@ final class DefaultCamera: NSObject, Camera { } func startVideoRecording( - completion: @escaping (FlutterError?) -> Void, + completion: @escaping (Result) -> Void, messengerForStreaming messenger: FlutterBinaryMessenger? ) { guard !isRecording else { completion( - FlutterError( - code: "Error", - message: "Video is already recording", - details: nil)) + .failure( + PigeonError( + code: "Error", + message: "Video is already recording", + details: nil))) return } @@ -482,7 +528,7 @@ final class DefaultCamera: NSObject, Camera { } /// Main logic to setup the video recording. - private func setUpVideoRecording(completion: @escaping (FlutterError?) -> Void) { + private func setUpVideoRecording(completion: @escaping (Result) -> Void) { let videoRecordingPath: String do { videoRecordingPath = try getTemporaryFilePath( @@ -491,16 +537,17 @@ final class DefaultCamera: NSObject, Camera { prefix: "REC_") self.videoRecordingPath = videoRecordingPath } catch let error as NSError { - completion(DefaultCamera.flutterErrorFromNSError(error)) + completion(.failure(DefaultCamera.pigeonErrorFromNSError(error))) return } guard setupWriter(forPath: videoRecordingPath) else { completion( - FlutterError( - code: "IOError", - message: "Setup Writer Failed", - details: nil)) + .failure( + PigeonError( + code: "IOError", + message: "Setup Writer Failed", + details: nil))) return } @@ -510,21 +557,29 @@ final class DefaultCamera: NSObject, Camera { // didOutputSampleBuffer had chance to call startWriting and lag at start of video // https://github.com/flutter/flutter/issues/132016 // https://github.com/flutter/flutter/issues/151319 - videoWriter?.startWriting() + guard let videoWriter = videoWriter, videoWriter.startWriting() else { + completion( + .failure( + PigeonError( + code: "IOError", + message: "AVAssetWriter failed to start writing", + details: videoWriter?.error?.localizedDescription))) + return + } isFirstVideoSample = true isRecording = true isRecordingPaused = false - videoTimeOffset = CMTime.zero - audioTimeOffset = CMTime.zero - videoIsDisconnected = false - audioIsDisconnected = false - completion(nil) + isRecordingDisconnected = false + recordingTimeOffset = CMTime.zero + outputForOffsetAdjusting = captureVideoOutput.avOutput + lastAppendedVideoSampleTime = CMTime.negativeInfinity + completion(.success(())) } private func setupWriter(forPath path: String) -> Bool { setUpCaptureSessionForAudioIfNeeded() - let videoWriter: FLTAssetWriter + let videoWriter: AssetWriter do { videoWriter = try assetWriterFactory(URL(fileURLWithPath: path), .mp4) @@ -540,14 +595,14 @@ final class DefaultCamera: NSObject, Camera { for: captureVideoOutput ) - if mediaSettings.videoBitrate != nil || mediaSettings.framesPerSecond != nil { + if mediaSettings.videoBitrate != nil || framesPerSecond != nil { var compressionProperties: [String: Any] = [:] if let videoBitrate = mediaSettings.videoBitrate { - compressionProperties[AVVideoAverageBitRateKey] = videoBitrate + compressionProperties[AVVideoAverageBitRateKey] = Int(videoBitrate) } - if let framesPerSecond = mediaSettings.framesPerSecond { + if let framesPerSecond = framesPerSecond { compressionProperties[AVVideoExpectedSourceFrameRateKey] = framesPerSecond } @@ -581,7 +636,7 @@ final class DefaultCamera: NSObject, Camera { ] if let audioBitrate = mediaSettings.audioBitrate { - audioSettings[AVEncoderBitRateKey] = audioBitrate + audioSettings[AVEncoderBitRateKey] = Int(audioBitrate) } let newAudioWriterInput = mediaSettingsAVWrapper.assetWriterAudioInput( @@ -606,22 +661,21 @@ final class DefaultCamera: NSObject, Camera { func pauseVideoRecording() { isRecordingPaused = true - videoIsDisconnected = true - audioIsDisconnected = true + isRecordingDisconnected = true } func resumeVideoRecording() { isRecordingPaused = false } - func stopVideoRecording(completion: @escaping (String?, FlutterError?) -> Void) { + func stopVideoRecording(completion: @escaping (Result) -> Void) { guard isRecording else { let error = NSError( domain: NSCocoaErrorDomain, code: URLError.resourceUnavailable.rawValue, userInfo: [NSLocalizedDescriptionKey: "Video is not recording!"] ) - completion(nil, DefaultCamera.flutterErrorFromNSError(error)) + completion(.failure(DefaultCamera.pigeonErrorFromNSError(error))) return } @@ -635,20 +689,20 @@ final class DefaultCamera: NSObject, Camera { if strongSelf.videoWriter?.status == .completed { strongSelf.updateOrientation() - completion(strongSelf.videoRecordingPath, nil) + completion(.success(strongSelf.videoRecordingPath!)) strongSelf.videoRecordingPath = nil } else { completion( - nil, - FlutterError( - code: "IOError", - message: "AVAssetWriter could not finish writing!", - details: nil)) + .failure( + PigeonError( + code: "IOError", + message: "AVAssetWriter could not finish writing!", + details: nil))) } } } - func captureToFile(completion: @escaping (String?, FlutterError?) -> Void) { + func captureToFile(completion: @escaping (Result) -> Void) { var settings = AVCapturePhotoSettings() if mediaSettings.resolutionPreset == .max { @@ -668,7 +722,7 @@ final class DefaultCamera: NSObject, Camera { } if flashMode != .torch { - settings.flashMode = FCPGetAVCaptureFlashModeForPigeonFlashMode(flashMode) + settings.flashMode = getAVCaptureFlashMode(for: flashMode) } let path: String @@ -678,11 +732,11 @@ final class DefaultCamera: NSObject, Camera { subfolder: "pictures", prefix: "CAP_") } catch let error as NSError { - completion(nil, DefaultCamera.flutterErrorFromNSError(error)) + completion(.failure(DefaultCamera.pigeonErrorFromNSError(error))) return } - let savePhotoDelegate = FLTSavePhotoDelegate( + let savePhotoDelegate = SavePhotoDelegate( path: path, ioQueue: photoIOQueue, completionHandler: { [weak self] path, error in @@ -693,10 +747,10 @@ final class DefaultCamera: NSObject, Camera { } if let error = error { - completion(nil, DefaultCamera.flutterErrorFromNSError(error as NSError)) + completion(.failure(DefaultCamera.pigeonErrorFromNSError(error as NSError))) } else { assert(path != nil, "Path must not be nil if no error.") - completion(path, nil) + completion(.success(path!)) } } ) @@ -714,11 +768,9 @@ final class DefaultCamera: NSObject, Camera { subfolder: String, prefix: String ) throws -> String { - let documentDirectory = FileManager.default.urls( - for: .documentDirectory, - in: .userDomainMask)[0] + let temporaryDirectory = FileManager.default.temporaryDirectory - let fileDirectory = documentDirectory.appendingPathComponent("camera").appendingPathComponent( + let fileDirectory = temporaryDirectory.appendingPathComponent("camera").appendingPathComponent( subfolder) let fileName = prefix + UUID().uuidString let file = fileDirectory.appendingPathComponent(fileName).appendingPathExtension(ext).path @@ -773,8 +825,8 @@ final class DefaultCamera: NSObject, Camera { } } - func lockCaptureOrientation(_ pigeonOrientation: FCPPlatformDeviceOrientation) { - let orientation = FCPGetUIDeviceOrientationForPigeonDeviceOrientation(pigeonOrientation) + func lockCaptureOrientation(_ pigeonOrientation: PlatformDeviceOrientation) { + let orientation = getUIDeviceOrientation(for: pigeonOrientation) if lockedCaptureOrientation != orientation { lockedCaptureOrientation = orientation updateOrientation() @@ -786,11 +838,11 @@ final class DefaultCamera: NSObject, Camera { updateOrientation() } - func setImageFileFormat(_ fileFormat: FCPPlatformImageFileFormat) { + func setImageFileFormat(_ fileFormat: PlatformImageFileFormat) { self.fileFormat = fileFormat } - func setExposureMode(_ mode: FCPPlatformExposureMode) { + func setExposureMode(_ mode: PlatformExposureMode) { exposureMode = mode applyExposureMode() } @@ -820,14 +872,15 @@ final class DefaultCamera: NSObject, Camera { } func setExposurePoint( - _ point: FCPPlatformPoint?, withCompletion completion: @escaping (FlutterError?) -> Void + _ point: PlatformPoint?, withCompletion completion: @escaping (Result) -> Void ) { guard captureDevice.isExposurePointOfInterestSupported else { completion( - FlutterError( - code: "setExposurePointFailed", - message: "Device does not have exposure point capabilities", - details: nil)) + .failure( + PigeonError( + code: "setExposurePointFailed", + message: "Device does not have exposure point capabilities", + details: nil))) return } @@ -835,26 +888,29 @@ final class DefaultCamera: NSObject, Camera { try? captureDevice.lockForConfiguration() // A nil point resets to the center. let exposurePoint = cgPoint( - for: point ?? FCPPlatformPoint.makeWith(x: 0.5, y: 0.5), withOrientation: orientation) + for: point ?? PlatformPoint(x: 0.5, y: 0.5), withOrientation: orientation) captureDevice.exposurePointOfInterest = exposurePoint captureDevice.unlockForConfiguration() // Retrigger auto exposure applyExposureMode() - completion(nil) + completion(.success(())) } - func setFocusMode(_ mode: FCPPlatformFocusMode) { + func setFocusMode(_ mode: PlatformFocusMode) { focusMode = mode applyFocusMode() } - func setFocusPoint(_ point: FCPPlatformPoint?, completion: @escaping (FlutterError?) -> Void) { + func setFocusPoint( + _ point: PlatformPoint?, completion: @escaping (Result) -> Void + ) { guard captureDevice.isFocusPointOfInterestSupported else { completion( - FlutterError( - code: "setFocusPointFailed", - message: "Device does not have focus point capabilities", - details: nil)) + .failure( + PigeonError( + code: "setFocusPointFailed", + message: "Device does not have focus point capabilities", + details: nil))) return } @@ -863,13 +919,13 @@ final class DefaultCamera: NSObject, Camera { // A nil point resets to the center. captureDevice.focusPointOfInterest = cgPoint( - for: point ?? .makeWith(x: 0.5, y: 0.5), + for: point ?? PlatformPoint(x: 0.5, y: 0.5), withOrientation: orientation) captureDevice.unlockForConfiguration() // Retrigger auto focus applyFocusMode() - completion(nil) + completion(.success(())) } private func applyFocusMode() { @@ -877,7 +933,7 @@ final class DefaultCamera: NSObject, Camera { } private func applyFocusMode( - _ focusMode: FCPPlatformFocusMode, onDevice captureDevice: CaptureDevice + _ focusMode: PlatformFocusMode, onDevice captureDevice: CaptureDevice ) { try? captureDevice.lockForConfiguration() switch focusMode { @@ -899,7 +955,7 @@ final class DefaultCamera: NSObject, Camera { } private func cgPoint( - for point: FCPPlatformPoint, withOrientation orientation: UIDeviceOrientation + for point: PlatformPoint, withOrientation orientation: UIDeviceOrientation ) -> CGPoint { @@ -925,52 +981,87 @@ final class DefaultCamera: NSObject, Camera { return CGPoint(x: x, y: y) } - func setZoomLevel(_ zoom: CGFloat, withCompletion completion: @escaping (FlutterError?) -> Void) { + func setZoomLevel( + _ zoom: CGFloat, withCompletion completion: @escaping (Result) -> Void + ) { if zoom < captureDevice.minAvailableVideoZoomFactor || zoom > captureDevice.maxAvailableVideoZoomFactor { completion( - FlutterError( - code: "ZOOM_ERROR", - message: - "Zoom level out of bounds (zoom level should be between \(captureDevice.minAvailableVideoZoomFactor) and \(captureDevice.maxAvailableVideoZoomFactor).", - details: nil)) + .failure( + PigeonError( + code: "ZOOM_ERROR", + message: + "Zoom level out of bounds (zoom level should be between \(captureDevice.minAvailableVideoZoomFactor) and \(captureDevice.maxAvailableVideoZoomFactor).", + details: nil))) return } do { try captureDevice.lockForConfiguration() } catch let error as NSError { - completion(DefaultCamera.flutterErrorFromNSError(error)) + completion(.failure(DefaultCamera.pigeonErrorFromNSError(error))) return } captureDevice.videoZoomFactor = zoom captureDevice.unlockForConfiguration() - completion(nil) + completion(.success(())) + } + + func setVideoStabilizationMode( + _ mode: PlatformVideoStabilizationMode, + withCompletion completion: @escaping (Result) -> Void + ) { + let stabilizationMode = getAvCaptureVideoStabilizationMode(mode) + + guard captureDevice.isVideoStabilizationModeSupported(stabilizationMode) else { + completion( + .failure( + PigeonError( + code: "VIDEO_STABILIZATION_ERROR", + message: "Unavailable video stabilization mode.", + details: [ + "requested_mode": stabilizationMode.rawValue + ] + )) + ) + return + } + if let connection = captureVideoOutput.connection(with: .video) { + connection.preferredVideoStabilizationMode = stabilizationMode + } + completion(.success(())) + } + + func isVideoStabilizationModeSupported(_ mode: PlatformVideoStabilizationMode) -> Bool { + let stabilizationMode = getAvCaptureVideoStabilizationMode(mode) + return captureDevice.isVideoStabilizationModeSupported(stabilizationMode) } func setFlashMode( - _ mode: FCPPlatformFlashMode, - withCompletion completion: @escaping (FlutterError?) -> Void + _ mode: PlatformFlashMode, + withCompletion completion: @escaping (Result) -> Void ) { switch mode { case .torch: guard captureDevice.hasTorch else { completion( - FlutterError( - code: "setFlashModeFailed", - message: "Device does not support torch mode", - details: nil) + .failure( + PigeonError( + code: "setFlashModeFailed", + message: "Device does not support torch mode", + details: nil)) ) return } guard captureDevice.isTorchAvailable else { completion( - FlutterError( - code: "setFlashModeFailed", - message: "Torch mode is currently not available", - details: nil)) + .failure( + PigeonError( + code: "setFlashModeFailed", + message: "Torch mode is currently not available", + details: nil))) return } if captureDevice.torchMode != .on { @@ -981,20 +1072,22 @@ final class DefaultCamera: NSObject, Camera { case .off, .auto, .always: guard captureDevice.hasFlash else { completion( - FlutterError( - code: "setFlashModeFailed", - message: "Device does not have flash capabilities", - details: nil)) + .failure( + PigeonError( + code: "setFlashModeFailed", + message: "Device does not have flash capabilities", + details: nil))) return } - let avFlashMode = FCPGetAVCaptureFlashModeForPigeonFlashMode(mode) + let avFlashMode = getAVCaptureFlashMode(for: mode) guard capturePhotoOutput.supportedFlashModes.contains(avFlashMode) else { completion( - FlutterError( - code: "setFlashModeFailed", - message: "Device does not support this specific flash mode", - details: nil)) + .failure( + PigeonError( + code: "setFlashModeFailed", + message: "Device does not support this specific flash mode", + details: nil))) return } if captureDevice.torchMode != .off { @@ -1007,7 +1100,7 @@ final class DefaultCamera: NSObject, Camera { } flashMode = mode - completion(nil) + completion(.success(())) } func pausePreview() { @@ -1019,14 +1112,15 @@ final class DefaultCamera: NSObject, Camera { } func setDescriptionWhileRecording( - _ cameraName: String, withCompletion completion: @escaping (FlutterError?) -> Void + _ cameraName: String, withCompletion completion: @escaping (Result) -> Void ) { guard isRecording else { completion( - FlutterError( - code: "setDescriptionWhileRecordingFailed", - message: "Device was not recording", - details: nil)) + .failure( + PigeonError( + code: "setDescriptionWhileRecordingFailed", + message: "Device was not recording", + details: nil))) return } @@ -1053,10 +1147,11 @@ final class DefaultCamera: NSObject, Camera { captureVideoOutput.setSampleBufferDelegate(self, queue: captureSessionQueue) } catch { completion( - FlutterError( - code: "VideoError", - message: "Unable to create video connection", - details: nil)) + .failure( + PigeonError( + code: "VideoError", + message: "Unable to create video connection", + details: nil))) return } @@ -1068,78 +1163,73 @@ final class DefaultCamera: NSObject, Camera { // Add the new connections to the session. if !videoCaptureSession.canAddInput(captureVideoInput) { completion( - FlutterError( - code: "VideoError", - message: "Unable to switch video input", - details: nil)) + .failure( + PigeonError( + code: "VideoError", + message: "Unable to switch video input", + details: nil))) } videoCaptureSession.addInputWithNoConnections(captureVideoInput) if !videoCaptureSession.canAddOutput(captureVideoOutput.avOutput) { completion( - FlutterError( - code: "VideoError", - message: "Unable to switch video output", - details: nil)) + .failure( + PigeonError( + code: "VideoError", + message: "Unable to switch video output", + details: nil))) } videoCaptureSession.addOutputWithNoConnections(captureVideoOutput.avOutput) if !videoCaptureSession.canAddConnection(newConnection) { completion( - FlutterError( - code: "VideoError", - message: "Unable to switch video connection", - details: nil)) + .failure( + PigeonError( + code: "VideoError", + message: "Unable to switch video connection", + details: nil))) } videoCaptureSession.addConnection(newConnection) videoCaptureSession.commitConfiguration() - completion(nil) + completion(.success(())) } func startImageStream( - with messenger: any FlutterBinaryMessenger, completion: @escaping (FlutterError?) -> Void + with messenger: any FlutterBinaryMessenger, + completion: @escaping (Result) -> Void ) { startImageStream( with: messenger, - imageStreamHandler: FLTImageStreamHandler(captureSessionQueue: captureSessionQueue), + imageStreamHandler: DefaultImageStreamHandler(captureSessionQueue: captureSessionQueue), completion: completion ) } func startImageStream( with messenger: FlutterBinaryMessenger, - imageStreamHandler: FLTImageStreamHandler, - completion: @escaping (FlutterError?) -> Void + imageStreamHandler: ImageStreamHandler, + completion: @escaping (Result) -> Void ) { if isStreamingImages { reportErrorMessage("Images from camera are already streaming!") - completion(nil) + completion(.success(())) return } - let eventChannel = FlutterEventChannel( - name: "plugins.flutter.io/camera_avfoundation/imageStream", - binaryMessenger: messenger - ) - let threadSafeEventChannel = FLTThreadSafeEventChannel(eventChannel: eventChannel) - - self.imageStreamHandler = imageStreamHandler - threadSafeEventChannel.setStreamHandler(imageStreamHandler) { [weak self] in - guard let strongSelf = self else { - completion(nil) + ensureToRunOnMainQueue { [weak self] in + guard let self else { + completion(.success(())) return } - - strongSelf.captureSessionQueue.async { [weak self] in - guard let strongSelf = self else { - completion(nil) - return + ImageDataStreamStreamHandler.register(with: messenger, streamHandler: imageStreamHandler) + self.imageStreamHandler = imageStreamHandler + self.captureSessionQueue.async { [weak self] in + if let self { + self.isStreamingImages = true + self.streamingPendingFramesCount = 0 } - - strongSelf.isStreamingImages = true - strongSelf.streamingPendingFramesCount = 0 - completion(nil) + completion(.success(())) } } } @@ -1176,75 +1266,74 @@ final class DefaultCamera: NSObject, Camera { handleSampleBufferStreaming(sampleBuffer) - if isRecording && !isRecordingPaused { + if isRecording && !isRecordingPaused && videoCaptureSession.isRunning + && audioCaptureSession.isRunning + { if videoWriter?.status == .failed, let error = videoWriter?.error { reportErrorMessage("\(error)") return } - // ignore audio samples until the first video sample arrives to avoid black frames - // https://github.com/flutter/flutter/issues/57831 - if isFirstVideoSample && output != captureVideoOutput.avOutput { - return + // do not append sample buffer when readyForMoreMediaData is NO to avoid crash + // https://github.com/flutter/flutter/issues/132073 + if output == captureVideoOutput.avOutput { + if !(videoWriterInput?.isReadyForMoreMediaData ?? false) { + return + } + } else { + // ignore audio samples until the first video sample arrives to avoid black frames + // https://github.com/flutter/flutter/issues/57831 + if isFirstVideoSample || !(audioWriterInput?.isReadyForMoreMediaData ?? false) { + return + } + outputForOffsetAdjusting = output } - var currentSampleTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer) + let sampleTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer) if isFirstVideoSample { - videoWriter?.startSession(atSourceTime: currentSampleTime) + videoWriter?.startSession(atSourceTime: sampleTime) // fix sample times not being numeric when pause/resume happens before first sample buffer // arrives // https://github.com/flutter/flutter/issues/132014 - lastVideoSampleTime = currentSampleTime - lastAudioSampleTime = currentSampleTime + isRecordingDisconnected = false isFirstVideoSample = false } - if output == captureVideoOutput.avOutput { - if videoIsDisconnected { - videoIsDisconnected = false - - videoTimeOffset = - videoTimeOffset.value == 0 - ? CMTimeSubtract(currentSampleTime, lastVideoSampleTime) - : CMTimeAdd(videoTimeOffset, CMTimeSubtract(currentSampleTime, lastVideoSampleTime)) + var currentSampleEndTime = sampleTime + let duration = CMSampleBufferGetDuration(sampleBuffer) + if CMTIME_IS_NUMERIC(duration) { + currentSampleEndTime = CMTimeAdd(currentSampleEndTime, duration) + } - return + // Use a single time offset for both video and audio to avoid desync. + // https://github.com/flutter/flutter/issues/149978 + if isRecordingDisconnected { + if output == outputForOffsetAdjusting { + let offset = CMTimeSubtract(currentSampleEndTime, lastSampleEndTime) + recordingTimeOffset = CMTimeAdd(recordingTimeOffset, offset) + lastSampleEndTime = currentSampleEndTime + isRecordingDisconnected = false } + return + } - lastVideoSampleTime = currentSampleTime + if output == outputForOffsetAdjusting { + lastSampleEndTime = currentSampleEndTime + } + if output == captureVideoOutput.avOutput { let nextBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) - let nextSampleTime = CMTimeSubtract(lastVideoSampleTime, videoTimeOffset) - // do not append sample buffer when readyForMoreMediaData is NO to avoid crash - // https://github.com/flutter/flutter/issues/132073 - if videoWriterInput?.readyForMoreMediaData ?? false { - videoAdaptor?.append(nextBuffer!, withPresentationTime: nextSampleTime) + let nextSampleTime = CMTimeSubtract(sampleTime, recordingTimeOffset) + if nextSampleTime > lastAppendedVideoSampleTime { + let _ = videoAdaptor?.append(nextBuffer!, withPresentationTime: nextSampleTime) + lastAppendedVideoSampleTime = nextSampleTime } } else { - let dur = CMSampleBufferGetDuration(sampleBuffer) - - if dur.value > 0 { - currentSampleTime = CMTimeAdd(currentSampleTime, dur) - } - - if audioIsDisconnected { - audioIsDisconnected = false - - audioTimeOffset = - audioTimeOffset.value == 0 - ? CMTimeSubtract(currentSampleTime, lastAudioSampleTime) - : CMTimeAdd(audioTimeOffset, CMTimeSubtract(currentSampleTime, lastAudioSampleTime)) - - return - } - - lastAudioSampleTime = currentSampleTime - - if audioTimeOffset.value != 0 { + if recordingTimeOffset.value != 0 { if let adjustedSampleBuffer = copySampleBufferWithAdjustedTime( sampleBuffer, - by: audioTimeOffset) + by: recordingTimeOffset) { newAudioSample(adjustedSampleBuffer) } @@ -1276,7 +1365,7 @@ final class DefaultCamera: NSObject, Camera { let imageWidth = CVPixelBufferGetWidth(pixelBuffer) let imageHeight = CVPixelBufferGetHeight(pixelBuffer) - var planes: [[String: Any]] = [] + var planes: [PlatformCameraImagePlane] = [] let isPlanar = CVPixelBufferIsPlanar(pixelBuffer) let planeCount = isPlanar ? CVPixelBufferGetPlaneCount(pixelBuffer) : 1 @@ -1302,12 +1391,12 @@ final class DefaultCamera: NSObject, Camera { let length = bytesPerRow * height let bytes = Data(bytes: planeAddress!, count: length) - let planeBuffer: [String: Any] = [ - "bytesPerRow": bytesPerRow, - "width": width, - "height": height, - "bytes": FlutterStandardTypedData(bytes: bytes), - ] + let planeBuffer = PlatformCameraImagePlane( + bytes: FlutterStandardTypedData(bytes: bytes), + bytesPerRow: Int64(bytesPerRow), + width: Int64(width), + height: Int64(height) + ) planes.append(planeBuffer) } @@ -1315,18 +1404,18 @@ final class DefaultCamera: NSObject, Camera { // Done accessing the `pixelBuffer` at this point. CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly) - let imageBuffer: [String: Any] = [ - "width": imageWidth, - "height": imageHeight, - "format": videoFormat, - "planes": planes, - "lensAperture": Double(captureDevice.lensAperture), - "sensorExposureTime": Int(captureDevice.exposureDuration.seconds * 1_000_000_000), - "sensorSensitivity": Double(captureDevice.iso), - ] + let imageBuffer = PlatformCameraImageData( + formatCode: Int64(videoFormat), + width: Int64(imageWidth), + height: Int64(imageHeight), + planes: planes, + lensAperture: Double(captureDevice.lensAperture), + sensorExposureTimeNanoseconds: Int64(captureDevice.exposureDuration.seconds * 1_000_000_000), + sensorSensitivity: Double(captureDevice.iso) + ) DispatchQueue.main.async { - eventSink(imageBuffer) + eventSink.success(imageBuffer) } } @@ -1368,10 +1457,8 @@ final class DefaultCamera: NSObject, Camera { } return } - if audioWriterInput?.readyForMoreMediaData ?? false { - if !(audioWriterInput?.append(sampleBuffer) ?? false) { - reportErrorMessage("Unable to write to audio input") - } + if !(audioWriterInput?.append(sampleBuffer) ?? false) { + reportErrorMessage("Unable to write to audio input") } } @@ -1409,8 +1496,8 @@ final class DefaultCamera: NSObject, Camera { /// /// Can be called from any thread. private func reportErrorMessage(_ errorMessage: String) { - FLTEnsureToRunOnMainQueue { [weak self] in - self?.dartAPI?.reportError(errorMessage) { _ in + ensureToRunOnMainQueue { [weak self] in + self?.dartAPI?.error(message: errorMessage) { _ in // Ignore any errors, as this is just an event broadcast. } } diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/FormatUtils.swift b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/FormatUtils.swift index 98e7f90f0547..0f351d4f5dbd 100644 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/FormatUtils.swift +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/FormatUtils.swift @@ -4,24 +4,19 @@ import AVFoundation -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif - /// Determines the video dimensions (width and height) for a given capture device format. /// Used in tests to mock CMVideoFormatDescriptionGetDimensions. -typealias VideoDimensionsConverter = (FLTCaptureDeviceFormat) -> CMVideoDimensions +typealias VideoDimensionsConverter = (CaptureDeviceFormat) -> CMVideoDimensions enum FormatUtils { /// Returns frame rate supported by format closest to targetFrameRate. - static private func bestFrameRate(for format: FLTCaptureDeviceFormat, targetFrameRate: Double) + static private func bestFrameRate(for format: CaptureDeviceFormat, targetFrameRate: Double) -> Double { var bestFrameRate: Double = 0 var minDistance: Double = Double.greatestFiniteMagnitude - for range in format.videoSupportedFrameRateRanges { + for range in format.flutterVideoSupportedFrameRateRanges { let frameRate = min( max(targetFrameRate, Double(range.minFrameRate)), Double(range.maxFrameRate)) let distance = abs(frameRate - targetFrameRate) @@ -36,22 +31,21 @@ enum FormatUtils { /// Finds format with same resolution as current activeFormat in captureDevice for which /// bestFrameRate returned frame rate closest to mediaSettings.framesPerSecond. - /// Preferred are formats with the same subtype as current activeFormat. Sets this format - /// as activeFormat and also updates mediaSettings.framesPerSecond to value which - /// bestFrameRate returned for that format. - static func selectBestFormat( + /// Preferred are formats with the same subtype as current activeFormat. Returns this format + /// and frame rate which bestFrameRate returned for that format. + static func findBestFormat( for captureDevice: CaptureDevice, - mediaSettings: FCPPlatformMediaSettings, + mediaSettings: PlatformMediaSettings, videoDimensionsConverter: VideoDimensionsConverter - ) { + ) -> (format: CaptureDeviceFormat, frameRate: Double) { let targetResolution = videoDimensionsConverter(captureDevice.flutterActiveFormat) - let targetFrameRate = mediaSettings.framesPerSecond?.doubleValue ?? 0 + let targetFrameRate = Double(mediaSettings.framesPerSecond ?? 0) let preferredSubType = CMFormatDescriptionGetMediaSubType( captureDevice.flutterActiveFormat.formatDescription) var bestFormat = captureDevice.flutterActiveFormat - var resolvedBastFrameRate = bestFrameRate(for: bestFormat, targetFrameRate: targetFrameRate) - var minDistance = abs(resolvedBastFrameRate - targetFrameRate) + var resolvedBestFrameRate = bestFrameRate(for: bestFormat, targetFrameRate: targetFrameRate) + var minDistance = abs(resolvedBestFrameRate - targetFrameRate) var isBestSubTypePreferred = true for format in captureDevice.flutterFormats { @@ -70,13 +64,12 @@ enum FormatUtils { || (distance == minDistance && isSubTypePreferred && !isBestSubTypePreferred) { bestFormat = format - resolvedBastFrameRate = frameRate + resolvedBestFrameRate = frameRate minDistance = distance isBestSubTypePreferred = isSubTypePreferred } } - captureDevice.flutterActiveFormat = bestFormat - mediaSettings.framesPerSecond = NSNumber(value: resolvedBastFrameRate) + return (bestFormat, resolvedBestFrameRate) } } diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/ImageStreamHandler.swift b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/ImageStreamHandler.swift new file mode 100644 index 000000000000..3a877851a1dd --- /dev/null +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/ImageStreamHandler.swift @@ -0,0 +1,44 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import Flutter + +/// Handles streaming of camera image data to Dart via Flutter event channels. +protocol ImageStreamHandler: ImageDataStreamStreamHandler { + /// The queue on which `eventSink` property should be accessed. + var captureSessionQueue: DispatchQueue { get } + + /// The event sink to stream camera events to Dart. + /// + /// The property should only be accessed on `captureSessionQueue`. + /// The block itself should be invoked on the main queue. + var eventSink: PigeonEventSink? { get set } +} + +/// Default implementation of ImageStreamHandler. +class DefaultImageStreamHandler: ImageDataStreamStreamHandler, ImageStreamHandler { + let captureSessionQueue: DispatchQueue + var eventSink: PigeonEventSink? + + /// Initialize an image stream handler. + /// captureSessionQueue - the queue on which the event sink should be accessed. + init(captureSessionQueue: DispatchQueue) { + self.captureSessionQueue = captureSessionQueue + super.init() + } + + override func onListen( + withArguments arguments: Any?, sink: PigeonEventSink + ) { + captureSessionQueue.async { [weak self] in + self?.eventSink = sink + } + } + + override func onCancel(withArguments arguments: Any?) { + captureSessionQueue.async { [weak self] in + self?.eventSink = nil + } + } +} diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/MediaSettingsAVWrapper.swift b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/MediaSettingsAVWrapper.swift index b74557c0af83..cd812961bb64 100644 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/MediaSettingsAVWrapper.swift +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/MediaSettingsAVWrapper.swift @@ -4,12 +4,6 @@ import AVFoundation import CoreMedia -import Foundation - -// Import Objective-C part of the implementation when SwiftPM is used. -#if canImport(camera_avfoundation_objc) - import camera_avfoundation_objc -#endif /// An interface for performing media settings operations. /// @@ -65,31 +59,29 @@ class FLTCamMediaSettingsAVWrapper { /// Creates a new input of the audio media type to receive sample buffers for writing to /// the output file. /// - Parameter outputSettings: The settings used for encoding the audio appended to the output. - /// - Returns: An instance of `FLTAssetWriterInput`. + /// - Returns: An instance of `AssetWriterInput`. func assetWriterAudioInput(withOutputSettings outputSettings: [String: Any]?) - -> FLTAssetWriterInput + -> AssetWriterInput { - let input = AVAssetWriterInput(mediaType: .audio, outputSettings: outputSettings) - return FLTDefaultAssetWriterInput(input: input) + return AVAssetWriterInput(mediaType: .audio, outputSettings: outputSettings) } /// Creates a new input of the video media type to receive sample buffers for writing to /// the output file. /// - Parameter outputSettings: The settings used for encoding the video appended to the output. - /// - Returns: An instance of `FLTAssetWriterInput`. + /// - Returns: An instance of `AssetWriterInput`. func assetWriterVideoInput(withOutputSettings outputSettings: [String: Any]?) - -> FLTAssetWriterInput + -> AssetWriterInput { - let input = AVAssetWriterInput(mediaType: .video, outputSettings: outputSettings) - return FLTDefaultAssetWriterInput(input: input) + return AVAssetWriterInput(mediaType: .video, outputSettings: outputSettings) } /// Adds an input to the asset writer. /// - Parameters: - /// - writerInput: The `FLTAssetWriterInput` object to be added. - /// - writer: The `FLTAssetWriter` object. - func addInput(_ writerInput: FLTAssetWriterInput, to writer: FLTAssetWriter) { - writer.add(writerInput.input) + /// - writerInput: The `AssetWriterInput` object to be added. + /// - writer: The `AssetWriter` object. + func addInput(_ writerInput: AssetWriterInput, to writer: AssetWriter) { + writer.add(writerInput.avInput) } /// Specifies the recommended video settings for `FLTCaptureVideoDataOutput`. diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/Messages.swift b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/Messages.swift new file mode 100644 index 000000000000..47e6abbbe750 --- /dev/null +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/Messages.swift @@ -0,0 +1,1555 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +// Autogenerated from Pigeon (v26.1.5), do not edit directly. +// See also: https://pub.dev/packages/pigeon + +import Foundation + +#if os(iOS) + import Flutter +#elseif os(macOS) + import FlutterMacOS +#else + #error("Unsupported platform.") +#endif + +/// Error class for passing custom error details to Dart side. +final class PigeonError: Error { + let code: String + let message: String? + let details: Sendable? + + init(code: String, message: String?, details: Sendable?) { + self.code = code + self.message = message + self.details = details + } + + var localizedDescription: String { + return + "PigeonError(code: \(code), message: \(message ?? ""), details: \(details ?? "")" + } +} + +private func wrapResult(_ result: Any?) -> [Any?] { + return [result] +} + +private func wrapError(_ error: Any) -> [Any?] { + if let pigeonError = error as? PigeonError { + return [ + pigeonError.code, + pigeonError.message, + pigeonError.details, + ] + } + if let flutterError = error as? FlutterError { + return [ + flutterError.code, + flutterError.message, + flutterError.details, + ] + } + return [ + "\(error)", + "\(type(of: error))", + "Stacktrace: \(Thread.callStackSymbols)", + ] +} + +private func createConnectionError(withChannelName channelName: String) -> PigeonError { + return PigeonError( + code: "channel-error", message: "Unable to establish connection on channel: '\(channelName)'.", + details: "") +} + +private func isNullish(_ value: Any?) -> Bool { + return value is NSNull || value == nil +} + +private func nilOrValue(_ value: Any?) -> T? { + if value is NSNull { return nil } + return value as! T? +} + +func deepEqualsMessages(_ lhs: Any?, _ rhs: Any?) -> Bool { + let cleanLhs = nilOrValue(lhs) as Any? + let cleanRhs = nilOrValue(rhs) as Any? + switch (cleanLhs, cleanRhs) { + case (nil, nil): + return true + + case (nil, _), (_, nil): + return false + + case is (Void, Void): + return true + + case let (cleanLhsHashable, cleanRhsHashable) as (AnyHashable, AnyHashable): + return cleanLhsHashable == cleanRhsHashable + + case let (cleanLhsArray, cleanRhsArray) as ([Any?], [Any?]): + guard cleanLhsArray.count == cleanRhsArray.count else { return false } + for (index, element) in cleanLhsArray.enumerated() { + if !deepEqualsMessages(element, cleanRhsArray[index]) { + return false + } + } + return true + + case let (cleanLhsDictionary, cleanRhsDictionary) as ([AnyHashable: Any?], [AnyHashable: Any?]): + guard cleanLhsDictionary.count == cleanRhsDictionary.count else { return false } + for (key, cleanLhsValue) in cleanLhsDictionary { + guard cleanRhsDictionary.index(forKey: key) != nil else { return false } + if !deepEqualsMessages(cleanLhsValue, cleanRhsDictionary[key]!) { + return false + } + } + return true + + default: + // Any other type shouldn't be able to be used with pigeon. File an issue if you find this to be untrue. + return false + } +} + +func deepHashMessages(value: Any?, hasher: inout Hasher) { + if let valueList = value as? [AnyHashable] { + for item in valueList { deepHashMessages(value: item, hasher: &hasher) } + return + } + + if let valueDict = value as? [AnyHashable: AnyHashable] { + for key in valueDict.keys { + hasher.combine(key) + deepHashMessages(value: valueDict[key]!, hasher: &hasher) + } + return + } + + if let hashableValue = value as? AnyHashable { + hasher.combine(hashableValue.hashValue) + } + + return hasher.combine(String(describing: value)) +} + +enum PlatformCameraLensDirection: Int { + /// Front facing camera (a user looking at the screen is seen by the camera). + case front = 0 + /// Back facing camera (a user looking at the screen is not seen by the camera). + case back = 1 + /// External camera which may not be mounted to the device. + case external = 2 +} + +enum PlatformCameraLensType: Int { + /// A built-in wide-angle camera device type. + case wide = 0 + /// A built-in camera device type with a longer focal length than a wide-angle camera. + case telephoto = 1 + /// A built-in camera device type with a shorter focal length than a wide-angle camera. + case ultraWide = 2 + /// Unknown camera device type. + case unknown = 3 +} + +enum PlatformDeviceOrientation: Int { + case portraitUp = 0 + case landscapeLeft = 1 + case portraitDown = 2 + case landscapeRight = 3 +} + +enum PlatformExposureMode: Int { + case auto = 0 + case locked = 1 +} + +enum PlatformFlashMode: Int { + case off = 0 + case auto = 1 + case always = 2 + case torch = 3 +} + +enum PlatformFocusMode: Int { + case auto = 0 + case locked = 1 +} + +/// Pigeon version of ImageFileFormat. +enum PlatformImageFileFormat: Int { + case jpeg = 0 + case heif = 1 +} + +enum PlatformImageFormatGroup: Int { + case bgra8888 = 0 + case yuv420 = 1 +} + +enum PlatformResolutionPreset: Int { + case low = 0 + case medium = 1 + case high = 2 + case veryHigh = 3 + case ultraHigh = 4 + case max = 5 +} + +enum PlatformVideoStabilizationMode: Int { + case off = 0 + case standard = 1 + case cinematic = 2 + case cinematicExtended = 3 +} + +/// Generated class from Pigeon that represents data sent in messages. +struct PlatformCameraDescription: Hashable { + /// The name of the camera device. + var name: String + /// The direction the camera is facing. + var lensDirection: PlatformCameraLensDirection + /// The type of the camera lens. + var lensType: PlatformCameraLensType + + // swift-format-ignore: AlwaysUseLowerCamelCase + static func fromList(_ pigeonVar_list: [Any?]) -> PlatformCameraDescription? { + let name = pigeonVar_list[0] as! String + let lensDirection = pigeonVar_list[1] as! PlatformCameraLensDirection + let lensType = pigeonVar_list[2] as! PlatformCameraLensType + + return PlatformCameraDescription( + name: name, + lensDirection: lensDirection, + lensType: lensType + ) + } + func toList() -> [Any?] { + return [ + name, + lensDirection, + lensType, + ] + } + static func == (lhs: PlatformCameraDescription, rhs: PlatformCameraDescription) -> Bool { + return deepEqualsMessages(lhs.toList(), rhs.toList()) + } + func hash(into hasher: inout Hasher) { + deepHashMessages(value: toList(), hasher: &hasher) + } +} + +/// Generated class from Pigeon that represents data sent in messages. +struct PlatformCameraState: Hashable { + /// The size of the preview, in pixels. + var previewSize: PlatformSize + /// The default exposure mode + var exposureMode: PlatformExposureMode + /// The default focus mode + var focusMode: PlatformFocusMode + /// Whether setting exposure points is supported. + var exposurePointSupported: Bool + /// Whether setting focus points is supported. + var focusPointSupported: Bool + + // swift-format-ignore: AlwaysUseLowerCamelCase + static func fromList(_ pigeonVar_list: [Any?]) -> PlatformCameraState? { + let previewSize = pigeonVar_list[0] as! PlatformSize + let exposureMode = pigeonVar_list[1] as! PlatformExposureMode + let focusMode = pigeonVar_list[2] as! PlatformFocusMode + let exposurePointSupported = pigeonVar_list[3] as! Bool + let focusPointSupported = pigeonVar_list[4] as! Bool + + return PlatformCameraState( + previewSize: previewSize, + exposureMode: exposureMode, + focusMode: focusMode, + exposurePointSupported: exposurePointSupported, + focusPointSupported: focusPointSupported + ) + } + func toList() -> [Any?] { + return [ + previewSize, + exposureMode, + focusMode, + exposurePointSupported, + focusPointSupported, + ] + } + static func == (lhs: PlatformCameraState, rhs: PlatformCameraState) -> Bool { + return deepEqualsMessages(lhs.toList(), rhs.toList()) + } + func hash(into hasher: inout Hasher) { + deepHashMessages(value: toList(), hasher: &hasher) + } +} + +/// Generated class from Pigeon that represents data sent in messages. +struct PlatformCameraImageData: Hashable { + /// The FourCharCode of the image format. + var formatCode: Int64 + var width: Int64 + var height: Int64 + var planes: [PlatformCameraImagePlane] + var lensAperture: Double + var sensorExposureTimeNanoseconds: Int64 + var sensorSensitivity: Double + + // swift-format-ignore: AlwaysUseLowerCamelCase + static func fromList(_ pigeonVar_list: [Any?]) -> PlatformCameraImageData? { + let formatCode = pigeonVar_list[0] as! Int64 + let width = pigeonVar_list[1] as! Int64 + let height = pigeonVar_list[2] as! Int64 + let planes = pigeonVar_list[3] as! [PlatformCameraImagePlane] + let lensAperture = pigeonVar_list[4] as! Double + let sensorExposureTimeNanoseconds = pigeonVar_list[5] as! Int64 + let sensorSensitivity = pigeonVar_list[6] as! Double + + return PlatformCameraImageData( + formatCode: formatCode, + width: width, + height: height, + planes: planes, + lensAperture: lensAperture, + sensorExposureTimeNanoseconds: sensorExposureTimeNanoseconds, + sensorSensitivity: sensorSensitivity + ) + } + func toList() -> [Any?] { + return [ + formatCode, + width, + height, + planes, + lensAperture, + sensorExposureTimeNanoseconds, + sensorSensitivity, + ] + } + static func == (lhs: PlatformCameraImageData, rhs: PlatformCameraImageData) -> Bool { + return deepEqualsMessages(lhs.toList(), rhs.toList()) + } + func hash(into hasher: inout Hasher) { + deepHashMessages(value: toList(), hasher: &hasher) + } +} + +/// Generated class from Pigeon that represents data sent in messages. +struct PlatformCameraImagePlane: Hashable { + var bytes: FlutterStandardTypedData + var bytesPerRow: Int64 + var width: Int64 + var height: Int64 + + // swift-format-ignore: AlwaysUseLowerCamelCase + static func fromList(_ pigeonVar_list: [Any?]) -> PlatformCameraImagePlane? { + let bytes = pigeonVar_list[0] as! FlutterStandardTypedData + let bytesPerRow = pigeonVar_list[1] as! Int64 + let width = pigeonVar_list[2] as! Int64 + let height = pigeonVar_list[3] as! Int64 + + return PlatformCameraImagePlane( + bytes: bytes, + bytesPerRow: bytesPerRow, + width: width, + height: height + ) + } + func toList() -> [Any?] { + return [ + bytes, + bytesPerRow, + width, + height, + ] + } + static func == (lhs: PlatformCameraImagePlane, rhs: PlatformCameraImagePlane) -> Bool { + return deepEqualsMessages(lhs.toList(), rhs.toList()) + } + func hash(into hasher: inout Hasher) { + deepHashMessages(value: toList(), hasher: &hasher) + } +} + +/// Generated class from Pigeon that represents data sent in messages. +struct PlatformMediaSettings: Hashable { + var resolutionPreset: PlatformResolutionPreset + var framesPerSecond: Int64? = nil + var videoBitrate: Int64? = nil + var audioBitrate: Int64? = nil + var enableAudio: Bool + + // swift-format-ignore: AlwaysUseLowerCamelCase + static func fromList(_ pigeonVar_list: [Any?]) -> PlatformMediaSettings? { + let resolutionPreset = pigeonVar_list[0] as! PlatformResolutionPreset + let framesPerSecond: Int64? = nilOrValue(pigeonVar_list[1]) + let videoBitrate: Int64? = nilOrValue(pigeonVar_list[2]) + let audioBitrate: Int64? = nilOrValue(pigeonVar_list[3]) + let enableAudio = pigeonVar_list[4] as! Bool + + return PlatformMediaSettings( + resolutionPreset: resolutionPreset, + framesPerSecond: framesPerSecond, + videoBitrate: videoBitrate, + audioBitrate: audioBitrate, + enableAudio: enableAudio + ) + } + func toList() -> [Any?] { + return [ + resolutionPreset, + framesPerSecond, + videoBitrate, + audioBitrate, + enableAudio, + ] + } + static func == (lhs: PlatformMediaSettings, rhs: PlatformMediaSettings) -> Bool { + return deepEqualsMessages(lhs.toList(), rhs.toList()) + } + func hash(into hasher: inout Hasher) { + deepHashMessages(value: toList(), hasher: &hasher) + } +} + +/// Generated class from Pigeon that represents data sent in messages. +struct PlatformPoint: Hashable { + var x: Double + var y: Double + + // swift-format-ignore: AlwaysUseLowerCamelCase + static func fromList(_ pigeonVar_list: [Any?]) -> PlatformPoint? { + let x = pigeonVar_list[0] as! Double + let y = pigeonVar_list[1] as! Double + + return PlatformPoint( + x: x, + y: y + ) + } + func toList() -> [Any?] { + return [ + x, + y, + ] + } + static func == (lhs: PlatformPoint, rhs: PlatformPoint) -> Bool { + return deepEqualsMessages(lhs.toList(), rhs.toList()) + } + func hash(into hasher: inout Hasher) { + deepHashMessages(value: toList(), hasher: &hasher) + } +} + +/// Generated class from Pigeon that represents data sent in messages. +struct PlatformSize: Hashable { + var width: Double + var height: Double + + // swift-format-ignore: AlwaysUseLowerCamelCase + static func fromList(_ pigeonVar_list: [Any?]) -> PlatformSize? { + let width = pigeonVar_list[0] as! Double + let height = pigeonVar_list[1] as! Double + + return PlatformSize( + width: width, + height: height + ) + } + func toList() -> [Any?] { + return [ + width, + height, + ] + } + static func == (lhs: PlatformSize, rhs: PlatformSize) -> Bool { + return deepEqualsMessages(lhs.toList(), rhs.toList()) + } + func hash(into hasher: inout Hasher) { + deepHashMessages(value: toList(), hasher: &hasher) + } +} + +private class MessagesPigeonCodecReader: FlutterStandardReader { + override func readValue(ofType type: UInt8) -> Any? { + switch type { + case 129: + let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?) + if let enumResultAsInt = enumResultAsInt { + return PlatformCameraLensDirection(rawValue: enumResultAsInt) + } + return nil + case 130: + let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?) + if let enumResultAsInt = enumResultAsInt { + return PlatformCameraLensType(rawValue: enumResultAsInt) + } + return nil + case 131: + let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?) + if let enumResultAsInt = enumResultAsInt { + return PlatformDeviceOrientation(rawValue: enumResultAsInt) + } + return nil + case 132: + let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?) + if let enumResultAsInt = enumResultAsInt { + return PlatformExposureMode(rawValue: enumResultAsInt) + } + return nil + case 133: + let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?) + if let enumResultAsInt = enumResultAsInt { + return PlatformFlashMode(rawValue: enumResultAsInt) + } + return nil + case 134: + let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?) + if let enumResultAsInt = enumResultAsInt { + return PlatformFocusMode(rawValue: enumResultAsInt) + } + return nil + case 135: + let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?) + if let enumResultAsInt = enumResultAsInt { + return PlatformImageFileFormat(rawValue: enumResultAsInt) + } + return nil + case 136: + let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?) + if let enumResultAsInt = enumResultAsInt { + return PlatformImageFormatGroup(rawValue: enumResultAsInt) + } + return nil + case 137: + let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?) + if let enumResultAsInt = enumResultAsInt { + return PlatformResolutionPreset(rawValue: enumResultAsInt) + } + return nil + case 138: + let enumResultAsInt: Int? = nilOrValue(self.readValue() as! Int?) + if let enumResultAsInt = enumResultAsInt { + return PlatformVideoStabilizationMode(rawValue: enumResultAsInt) + } + return nil + case 139: + return PlatformCameraDescription.fromList(self.readValue() as! [Any?]) + case 140: + return PlatformCameraState.fromList(self.readValue() as! [Any?]) + case 141: + return PlatformCameraImageData.fromList(self.readValue() as! [Any?]) + case 142: + return PlatformCameraImagePlane.fromList(self.readValue() as! [Any?]) + case 143: + return PlatformMediaSettings.fromList(self.readValue() as! [Any?]) + case 144: + return PlatformPoint.fromList(self.readValue() as! [Any?]) + case 145: + return PlatformSize.fromList(self.readValue() as! [Any?]) + default: + return super.readValue(ofType: type) + } + } +} + +private class MessagesPigeonCodecWriter: FlutterStandardWriter { + override func writeValue(_ value: Any) { + if let value = value as? PlatformCameraLensDirection { + super.writeByte(129) + super.writeValue(value.rawValue) + } else if let value = value as? PlatformCameraLensType { + super.writeByte(130) + super.writeValue(value.rawValue) + } else if let value = value as? PlatformDeviceOrientation { + super.writeByte(131) + super.writeValue(value.rawValue) + } else if let value = value as? PlatformExposureMode { + super.writeByte(132) + super.writeValue(value.rawValue) + } else if let value = value as? PlatformFlashMode { + super.writeByte(133) + super.writeValue(value.rawValue) + } else if let value = value as? PlatformFocusMode { + super.writeByte(134) + super.writeValue(value.rawValue) + } else if let value = value as? PlatformImageFileFormat { + super.writeByte(135) + super.writeValue(value.rawValue) + } else if let value = value as? PlatformImageFormatGroup { + super.writeByte(136) + super.writeValue(value.rawValue) + } else if let value = value as? PlatformResolutionPreset { + super.writeByte(137) + super.writeValue(value.rawValue) + } else if let value = value as? PlatformVideoStabilizationMode { + super.writeByte(138) + super.writeValue(value.rawValue) + } else if let value = value as? PlatformCameraDescription { + super.writeByte(139) + super.writeValue(value.toList()) + } else if let value = value as? PlatformCameraState { + super.writeByte(140) + super.writeValue(value.toList()) + } else if let value = value as? PlatformCameraImageData { + super.writeByte(141) + super.writeValue(value.toList()) + } else if let value = value as? PlatformCameraImagePlane { + super.writeByte(142) + super.writeValue(value.toList()) + } else if let value = value as? PlatformMediaSettings { + super.writeByte(143) + super.writeValue(value.toList()) + } else if let value = value as? PlatformPoint { + super.writeByte(144) + super.writeValue(value.toList()) + } else if let value = value as? PlatformSize { + super.writeByte(145) + super.writeValue(value.toList()) + } else { + super.writeValue(value) + } + } +} + +private class MessagesPigeonCodecReaderWriter: FlutterStandardReaderWriter { + override func reader(with data: Data) -> FlutterStandardReader { + return MessagesPigeonCodecReader(data: data) + } + + override func writer(with data: NSMutableData) -> FlutterStandardWriter { + return MessagesPigeonCodecWriter(data: data) + } +} + +class MessagesPigeonCodec: FlutterStandardMessageCodec, @unchecked Sendable { + static let shared = MessagesPigeonCodec(readerWriter: MessagesPigeonCodecReaderWriter()) +} + +var messagesPigeonMethodCodec = FlutterStandardMethodCodec( + readerWriter: MessagesPigeonCodecReaderWriter()) + +/// Generated protocol from Pigeon that represents a handler of messages from Flutter. +protocol CameraApi { + /// Returns the list of available cameras. + func getAvailableCameras( + completion: @escaping (Result<[PlatformCameraDescription], Error>) -> Void) + /// Create a new camera with the given settings, and returns its ID. + func create( + cameraName: String, settings: PlatformMediaSettings, + completion: @escaping (Result) -> Void) + /// Initializes the camera with the given ID. + func initialize( + cameraId: Int64, imageFormat: PlatformImageFormatGroup, + completion: @escaping (Result) -> Void) + /// Begins streaming frames from the camera. + func startImageStream(completion: @escaping (Result) -> Void) + /// Stops streaming frames from the camera. + func stopImageStream(completion: @escaping (Result) -> Void) + /// Called by the Dart side of the plugin when it has received the last image + /// frame sent. + /// + /// This is used to throttle sending frames across the channel. + func receivedImageStreamData(completion: @escaping (Result) -> Void) + /// Indicates that the given camera is no longer being used on the Dart side, + /// and any associated resources can be cleaned up. + func dispose(cameraId: Int64, completion: @escaping (Result) -> Void) + /// Locks the camera capture to the current device orientation. + func lockCaptureOrientation( + orientation: PlatformDeviceOrientation, completion: @escaping (Result) -> Void) + /// Unlocks camera capture orientation, allowing it to automatically adapt to + /// device orientation. + func unlockCaptureOrientation(completion: @escaping (Result) -> Void) + /// Takes a picture with the current settings, and returns the path to the + /// resulting file. + func takePicture(completion: @escaping (Result) -> Void) + /// Does any preprocessing necessary before beginning to record video. + func prepareForVideoRecording(completion: @escaping (Result) -> Void) + /// Begins recording video, optionally enabling streaming to Dart at the same + /// time. + func startVideoRecording(enableStream: Bool, completion: @escaping (Result) -> Void) + /// Stops recording video, and results the path to the resulting file. + func stopVideoRecording(completion: @escaping (Result) -> Void) + /// Pauses video recording. + func pauseVideoRecording(completion: @escaping (Result) -> Void) + /// Resumes a previously paused video recording. + func resumeVideoRecording(completion: @escaping (Result) -> Void) + /// Switches the camera to the given flash mode. + func setFlashMode(mode: PlatformFlashMode, completion: @escaping (Result) -> Void) + /// Switches the camera to the given exposure mode. + func setExposureMode( + mode: PlatformExposureMode, completion: @escaping (Result) -> Void) + /// Anchors auto-exposure to the given point in (0,1) coordinate space. + /// + /// A null value resets to the default exposure point. + func setExposurePoint(point: PlatformPoint?, completion: @escaping (Result) -> Void) + /// Returns the minimum exposure offset supported by the camera. + func getMinExposureOffset(completion: @escaping (Result) -> Void) + /// Returns the maximum exposure offset supported by the camera. + func getMaxExposureOffset(completion: @escaping (Result) -> Void) + /// Sets the exposure offset manually to the given value. + func setExposureOffset(offset: Double, completion: @escaping (Result) -> Void) + /// Switches the camera to the given focus mode. + func setFocusMode(mode: PlatformFocusMode, completion: @escaping (Result) -> Void) + /// Anchors auto-focus to the given point in (0,1) coordinate space. + /// + /// A null value resets to the default focus point. + func setFocusPoint(point: PlatformPoint?, completion: @escaping (Result) -> Void) + /// Returns the minimum zoom level supported by the camera. + func getMinZoomLevel(completion: @escaping (Result) -> Void) + /// Returns the maximum zoom level supported by the camera. + func getMaxZoomLevel(completion: @escaping (Result) -> Void) + /// Sets the zoom factor. + func setZoomLevel(zoom: Double, completion: @escaping (Result) -> Void) + /// Sets the video stabilization mode. + func setVideoStabilizationMode( + mode: PlatformVideoStabilizationMode, completion: @escaping (Result) -> Void) + /// Gets if the given video stabilization mode is supported. + func isVideoStabilizationModeSupported( + mode: PlatformVideoStabilizationMode, completion: @escaping (Result) -> Void) + /// Pauses streaming of preview frames. + func pausePreview(completion: @escaping (Result) -> Void) + /// Resumes a previously paused preview stream. + func resumePreview(completion: @escaping (Result) -> Void) + /// Changes the camera used while recording video. + /// + /// This should only be called while video recording is active. + func updateDescriptionWhileRecording( + cameraName: String, completion: @escaping (Result) -> Void) + /// Sets the file format used for taking pictures. + func setImageFileFormat( + format: PlatformImageFileFormat, completion: @escaping (Result) -> Void) +} + +/// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. +class CameraApiSetup { + static var codec: FlutterStandardMessageCodec { MessagesPigeonCodec.shared } + /// Sets up an instance of `CameraApi` to handle messages through the `binaryMessenger`. + static func setUp( + binaryMessenger: FlutterBinaryMessenger, api: CameraApi?, messageChannelSuffix: String = "" + ) { + let channelSuffix = messageChannelSuffix.count > 0 ? ".\(messageChannelSuffix)" : "" + /// Returns the list of available cameras. + let getAvailableCamerasChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.getAvailableCameras\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + getAvailableCamerasChannel.setMessageHandler { _, reply in + api.getAvailableCameras { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + getAvailableCamerasChannel.setMessageHandler(nil) + } + /// Create a new camera with the given settings, and returns its ID. + let createChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.create\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + createChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let cameraNameArg = args[0] as! String + let settingsArg = args[1] as! PlatformMediaSettings + api.create(cameraName: cameraNameArg, settings: settingsArg) { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + createChannel.setMessageHandler(nil) + } + /// Initializes the camera with the given ID. + let initializeChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.initialize\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + initializeChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let cameraIdArg = args[0] as! Int64 + let imageFormatArg = args[1] as! PlatformImageFormatGroup + api.initialize(cameraId: cameraIdArg, imageFormat: imageFormatArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + initializeChannel.setMessageHandler(nil) + } + /// Begins streaming frames from the camera. + let startImageStreamChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.startImageStream\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + startImageStreamChannel.setMessageHandler { _, reply in + api.startImageStream { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + startImageStreamChannel.setMessageHandler(nil) + } + /// Stops streaming frames from the camera. + let stopImageStreamChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.stopImageStream\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + stopImageStreamChannel.setMessageHandler { _, reply in + api.stopImageStream { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + stopImageStreamChannel.setMessageHandler(nil) + } + /// Called by the Dart side of the plugin when it has received the last image + /// frame sent. + /// + /// This is used to throttle sending frames across the channel. + let receivedImageStreamDataChannel = FlutterBasicMessageChannel( + name: + "dev.flutter.pigeon.camera_avfoundation.CameraApi.receivedImageStreamData\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + receivedImageStreamDataChannel.setMessageHandler { _, reply in + api.receivedImageStreamData { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + receivedImageStreamDataChannel.setMessageHandler(nil) + } + /// Indicates that the given camera is no longer being used on the Dart side, + /// and any associated resources can be cleaned up. + let disposeChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.dispose\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + disposeChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let cameraIdArg = args[0] as! Int64 + api.dispose(cameraId: cameraIdArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + disposeChannel.setMessageHandler(nil) + } + /// Locks the camera capture to the current device orientation. + let lockCaptureOrientationChannel = FlutterBasicMessageChannel( + name: + "dev.flutter.pigeon.camera_avfoundation.CameraApi.lockCaptureOrientation\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + lockCaptureOrientationChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let orientationArg = args[0] as! PlatformDeviceOrientation + api.lockCaptureOrientation(orientation: orientationArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + lockCaptureOrientationChannel.setMessageHandler(nil) + } + /// Unlocks camera capture orientation, allowing it to automatically adapt to + /// device orientation. + let unlockCaptureOrientationChannel = FlutterBasicMessageChannel( + name: + "dev.flutter.pigeon.camera_avfoundation.CameraApi.unlockCaptureOrientation\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + unlockCaptureOrientationChannel.setMessageHandler { _, reply in + api.unlockCaptureOrientation { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + unlockCaptureOrientationChannel.setMessageHandler(nil) + } + /// Takes a picture with the current settings, and returns the path to the + /// resulting file. + let takePictureChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.takePicture\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + takePictureChannel.setMessageHandler { _, reply in + api.takePicture { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + takePictureChannel.setMessageHandler(nil) + } + /// Does any preprocessing necessary before beginning to record video. + let prepareForVideoRecordingChannel = FlutterBasicMessageChannel( + name: + "dev.flutter.pigeon.camera_avfoundation.CameraApi.prepareForVideoRecording\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + prepareForVideoRecordingChannel.setMessageHandler { _, reply in + api.prepareForVideoRecording { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + prepareForVideoRecordingChannel.setMessageHandler(nil) + } + /// Begins recording video, optionally enabling streaming to Dart at the same + /// time. + let startVideoRecordingChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.startVideoRecording\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + startVideoRecordingChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let enableStreamArg = args[0] as! Bool + api.startVideoRecording(enableStream: enableStreamArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + startVideoRecordingChannel.setMessageHandler(nil) + } + /// Stops recording video, and results the path to the resulting file. + let stopVideoRecordingChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.stopVideoRecording\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + stopVideoRecordingChannel.setMessageHandler { _, reply in + api.stopVideoRecording { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + stopVideoRecordingChannel.setMessageHandler(nil) + } + /// Pauses video recording. + let pauseVideoRecordingChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.pauseVideoRecording\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + pauseVideoRecordingChannel.setMessageHandler { _, reply in + api.pauseVideoRecording { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + pauseVideoRecordingChannel.setMessageHandler(nil) + } + /// Resumes a previously paused video recording. + let resumeVideoRecordingChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.resumeVideoRecording\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + resumeVideoRecordingChannel.setMessageHandler { _, reply in + api.resumeVideoRecording { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + resumeVideoRecordingChannel.setMessageHandler(nil) + } + /// Switches the camera to the given flash mode. + let setFlashModeChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.setFlashMode\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + setFlashModeChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let modeArg = args[0] as! PlatformFlashMode + api.setFlashMode(mode: modeArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + setFlashModeChannel.setMessageHandler(nil) + } + /// Switches the camera to the given exposure mode. + let setExposureModeChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.setExposureMode\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + setExposureModeChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let modeArg = args[0] as! PlatformExposureMode + api.setExposureMode(mode: modeArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + setExposureModeChannel.setMessageHandler(nil) + } + /// Anchors auto-exposure to the given point in (0,1) coordinate space. + /// + /// A null value resets to the default exposure point. + let setExposurePointChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.setExposurePoint\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + setExposurePointChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let pointArg: PlatformPoint? = nilOrValue(args[0]) + api.setExposurePoint(point: pointArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + setExposurePointChannel.setMessageHandler(nil) + } + /// Returns the minimum exposure offset supported by the camera. + let getMinExposureOffsetChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.getMinExposureOffset\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + getMinExposureOffsetChannel.setMessageHandler { _, reply in + api.getMinExposureOffset { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + getMinExposureOffsetChannel.setMessageHandler(nil) + } + /// Returns the maximum exposure offset supported by the camera. + let getMaxExposureOffsetChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.getMaxExposureOffset\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + getMaxExposureOffsetChannel.setMessageHandler { _, reply in + api.getMaxExposureOffset { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + getMaxExposureOffsetChannel.setMessageHandler(nil) + } + /// Sets the exposure offset manually to the given value. + let setExposureOffsetChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.setExposureOffset\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + setExposureOffsetChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let offsetArg = args[0] as! Double + api.setExposureOffset(offset: offsetArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + setExposureOffsetChannel.setMessageHandler(nil) + } + /// Switches the camera to the given focus mode. + let setFocusModeChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.setFocusMode\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + setFocusModeChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let modeArg = args[0] as! PlatformFocusMode + api.setFocusMode(mode: modeArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + setFocusModeChannel.setMessageHandler(nil) + } + /// Anchors auto-focus to the given point in (0,1) coordinate space. + /// + /// A null value resets to the default focus point. + let setFocusPointChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.setFocusPoint\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + setFocusPointChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let pointArg: PlatformPoint? = nilOrValue(args[0]) + api.setFocusPoint(point: pointArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + setFocusPointChannel.setMessageHandler(nil) + } + /// Returns the minimum zoom level supported by the camera. + let getMinZoomLevelChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.getMinZoomLevel\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + getMinZoomLevelChannel.setMessageHandler { _, reply in + api.getMinZoomLevel { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + getMinZoomLevelChannel.setMessageHandler(nil) + } + /// Returns the maximum zoom level supported by the camera. + let getMaxZoomLevelChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.getMaxZoomLevel\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + getMaxZoomLevelChannel.setMessageHandler { _, reply in + api.getMaxZoomLevel { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + getMaxZoomLevelChannel.setMessageHandler(nil) + } + /// Sets the zoom factor. + let setZoomLevelChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.setZoomLevel\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + setZoomLevelChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let zoomArg = args[0] as! Double + api.setZoomLevel(zoom: zoomArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + setZoomLevelChannel.setMessageHandler(nil) + } + /// Sets the video stabilization mode. + let setVideoStabilizationModeChannel = FlutterBasicMessageChannel( + name: + "dev.flutter.pigeon.camera_avfoundation.CameraApi.setVideoStabilizationMode\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + setVideoStabilizationModeChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let modeArg = args[0] as! PlatformVideoStabilizationMode + api.setVideoStabilizationMode(mode: modeArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + setVideoStabilizationModeChannel.setMessageHandler(nil) + } + /// Gets if the given video stabilization mode is supported. + let isVideoStabilizationModeSupportedChannel = FlutterBasicMessageChannel( + name: + "dev.flutter.pigeon.camera_avfoundation.CameraApi.isVideoStabilizationModeSupported\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + isVideoStabilizationModeSupportedChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let modeArg = args[0] as! PlatformVideoStabilizationMode + api.isVideoStabilizationModeSupported(mode: modeArg) { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + isVideoStabilizationModeSupportedChannel.setMessageHandler(nil) + } + /// Pauses streaming of preview frames. + let pausePreviewChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.pausePreview\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + pausePreviewChannel.setMessageHandler { _, reply in + api.pausePreview { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + pausePreviewChannel.setMessageHandler(nil) + } + /// Resumes a previously paused preview stream. + let resumePreviewChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.resumePreview\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + resumePreviewChannel.setMessageHandler { _, reply in + api.resumePreview { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + resumePreviewChannel.setMessageHandler(nil) + } + /// Changes the camera used while recording video. + /// + /// This should only be called while video recording is active. + let updateDescriptionWhileRecordingChannel = FlutterBasicMessageChannel( + name: + "dev.flutter.pigeon.camera_avfoundation.CameraApi.updateDescriptionWhileRecording\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + updateDescriptionWhileRecordingChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let cameraNameArg = args[0] as! String + api.updateDescriptionWhileRecording(cameraName: cameraNameArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + updateDescriptionWhileRecordingChannel.setMessageHandler(nil) + } + /// Sets the file format used for taking pictures. + let setImageFileFormatChannel = FlutterBasicMessageChannel( + name: "dev.flutter.pigeon.camera_avfoundation.CameraApi.setImageFileFormat\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + setImageFileFormatChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let formatArg = args[0] as! PlatformImageFileFormat + api.setImageFileFormat(format: formatArg) { result in + switch result { + case .success: + reply(wrapResult(nil)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + setImageFileFormatChannel.setMessageHandler(nil) + } + } +} + +private class PigeonStreamHandler: NSObject, FlutterStreamHandler { + private let wrapper: PigeonEventChannelWrapper + private var pigeonSink: PigeonEventSink? = nil + + init(wrapper: PigeonEventChannelWrapper) { + self.wrapper = wrapper + } + + func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) + -> FlutterError? + { + pigeonSink = PigeonEventSink(events) + wrapper.onListen(withArguments: arguments, sink: pigeonSink!) + return nil + } + + func onCancel(withArguments arguments: Any?) -> FlutterError? { + pigeonSink = nil + wrapper.onCancel(withArguments: arguments) + return nil + } +} + +class PigeonEventChannelWrapper { + func onListen(withArguments arguments: Any?, sink: PigeonEventSink) {} + func onCancel(withArguments arguments: Any?) {} +} + +class PigeonEventSink { + private let sink: FlutterEventSink + + init(_ sink: @escaping FlutterEventSink) { + self.sink = sink + } + + func success(_ value: ReturnType) { + sink(value) + } + + func error(code: String, message: String?, details: Any?) { + sink(FlutterError(code: code, message: message, details: details)) + } + + func endOfStream() { + sink(FlutterEndOfEventStream) + } + +} + +class ImageDataStreamStreamHandler: PigeonEventChannelWrapper { + static func register( + with messenger: FlutterBinaryMessenger, + instanceName: String = "", + streamHandler: ImageDataStreamStreamHandler + ) { + var channelName = + "dev.flutter.pigeon.camera_avfoundation.CameraImageStreamEventApi.imageDataStream" + if !instanceName.isEmpty { + channelName += ".\(instanceName)" + } + let internalStreamHandler = PigeonStreamHandler(wrapper: streamHandler) + let channel = FlutterEventChannel( + name: channelName, binaryMessenger: messenger, codec: messagesPigeonMethodCodec) + channel.setStreamHandler(internalStreamHandler) + } +} + +/// Handler for native callbacks that are not tied to a specific camera ID. +/// +/// Generated protocol from Pigeon that represents Flutter messages that can be called from Swift. +protocol CameraGlobalEventApiProtocol { + /// Called when the device's physical orientation changes. + func deviceOrientationChanged( + orientation orientationArg: PlatformDeviceOrientation, + completion: @escaping (Result) -> Void) +} +class CameraGlobalEventApi: CameraGlobalEventApiProtocol { + private let binaryMessenger: FlutterBinaryMessenger + private let messageChannelSuffix: String + init(binaryMessenger: FlutterBinaryMessenger, messageChannelSuffix: String = "") { + self.binaryMessenger = binaryMessenger + self.messageChannelSuffix = messageChannelSuffix.count > 0 ? ".\(messageChannelSuffix)" : "" + } + var codec: MessagesPigeonCodec { + return MessagesPigeonCodec.shared + } + /// Called when the device's physical orientation changes. + func deviceOrientationChanged( + orientation orientationArg: PlatformDeviceOrientation, + completion: @escaping (Result) -> Void + ) { + let channelName: String = + "dev.flutter.pigeon.camera_avfoundation.CameraGlobalEventApi.deviceOrientationChanged\(messageChannelSuffix)" + let channel = FlutterBasicMessageChannel( + name: channelName, binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage([orientationArg] 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(())) + } + } + } +} +/// Handler for native callbacks that are tied to a specific camera ID. +/// +/// This is intended to be initialized with the camera ID as a suffix. +/// +/// Generated protocol from Pigeon that represents Flutter messages that can be called from Swift. +protocol CameraEventApiProtocol { + /// Called when the camera is inialitized for use. + func initialized( + initialState initialStateArg: PlatformCameraState, + completion: @escaping (Result) -> Void) + /// Called when an error occurs in the camera. + /// + /// This should be used for errors that occur outside of the context of + /// handling a specific HostApi call, such as during streaming. + func error(message messageArg: String, completion: @escaping (Result) -> Void) +} +class CameraEventApi: CameraEventApiProtocol { + private let binaryMessenger: FlutterBinaryMessenger + private let messageChannelSuffix: String + init(binaryMessenger: FlutterBinaryMessenger, messageChannelSuffix: String = "") { + self.binaryMessenger = binaryMessenger + self.messageChannelSuffix = messageChannelSuffix.count > 0 ? ".\(messageChannelSuffix)" : "" + } + var codec: MessagesPigeonCodec { + return MessagesPigeonCodec.shared + } + /// Called when the camera is inialitized for use. + func initialized( + initialState initialStateArg: PlatformCameraState, + completion: @escaping (Result) -> Void + ) { + let channelName: String = + "dev.flutter.pigeon.camera_avfoundation.CameraEventApi.initialized\(messageChannelSuffix)" + let channel = FlutterBasicMessageChannel( + name: channelName, binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage([initialStateArg] 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(())) + } + } + } + /// Called when an error occurs in the camera. + /// + /// This should be used for errors that occur outside of the context of + /// handling a specific HostApi call, such as during streaming. + func error(message messageArg: String, completion: @escaping (Result) -> Void) + { + let channelName: String = + "dev.flutter.pigeon.camera_avfoundation.CameraEventApi.error\(messageChannelSuffix)" + let channel = FlutterBasicMessageChannel( + name: channelName, binaryMessenger: binaryMessenger, codec: codec) + channel.sendMessage([messageArg] 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/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/PermissionServicing.swift b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/PermissionServicing.swift new file mode 100644 index 000000000000..b0c72d9bfea0 --- /dev/null +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/PermissionServicing.swift @@ -0,0 +1,29 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import AVFoundation + +/// A protocol for permission-related operations on AVCaptureDevice. +/// It exists to allow mocking permission checks in tests. +protocol PermissionServicing: NSObjectProtocol { + func authorizationStatus(for mediaType: AVMediaType) -> AVAuthorizationStatus + func requestAccess( + for mediaType: AVMediaType, + completion handler: @escaping @Sendable (Bool) -> Void + ) +} + +/// Default implementation of PermissionServicing that forwards calls to AVCaptureDevice. +class DefaultPermissionService: NSObject, PermissionServicing { + func authorizationStatus(for mediaType: AVMediaType) -> AVAuthorizationStatus { + return AVCaptureDevice.authorizationStatus(for: mediaType) + } + + func requestAccess( + for mediaType: AVMediaType, + completion handler: @escaping @Sendable (Bool) -> Void + ) { + AVCaptureDevice.requestAccess(for: mediaType, completionHandler: handler) + } +} diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/QueueUtils.swift b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/QueueUtils.swift index faefd0e931ef..99fe22515d1b 100644 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/QueueUtils.swift +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/QueueUtils.swift @@ -3,7 +3,23 @@ // found in the LICENSE file. import Dispatch +import Foundation /// Queue-specific context data to be associated with the capture session queue. let captureSessionQueueSpecificKey = DispatchSpecificKey() let captureSessionQueueSpecificValue = "capture_session_queue" + +/// Ensures the given block to be run on the main queue. +/// If caller site is already on the main queue, the block will be run +/// synchronously. Otherwise, the block will be dispatched asynchronously to the +/// main queue. +/// block - the block to be run on the main queue. +func ensureToRunOnMainQueue(_ block: @escaping () -> Void) { + if Thread.isMainThread { + block() + } else { + DispatchQueue.main.async { + block() + } + } +} diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/SavePhotoDelegate.swift b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/SavePhotoDelegate.swift new file mode 100644 index 000000000000..35050120e118 --- /dev/null +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/SavePhotoDelegate.swift @@ -0,0 +1,85 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import AVFoundation +import Flutter +import Foundation + +/// The completion handler block for save photo operations. +/// Can be called from either main queue or IO queue. +/// If success, `path` will be present and `error` will be nil. Otherwise, `path` will be nil and +/// `error` will be present. +/// path - the path for successfully saved photo file. +/// error - photo capture error or IO error. +typealias SavePhotoDelegateCompletionHandler = (String?, Error?) -> Void + +/// Delegate object that handles photo capture results. +class SavePhotoDelegate: NSObject, AVCapturePhotoCaptureDelegate { + /// The file path for the captured photo. + private let path: String + + /// The queue on which captured photos are written to disk. + private let ioQueue: DispatchQueue + + /// The completion handler block for capture and save photo operations. + let completionHandler: SavePhotoDelegateCompletionHandler + + /// The path for captured photo file. + /// Exposed for unit tests to verify the captured photo file path. + var filePath: String { + path + } + + /// Initialize a photo capture delegate. + /// path - the path for captured photo file. + /// ioQueue - the queue on which captured photos are written to disk. + /// completionHandler - The completion handler block for save photo operations. Can + /// be called from either main queue or IO queue. + init( + path: String, + ioQueue: DispatchQueue, + completionHandler: @escaping SavePhotoDelegateCompletionHandler + ) { + self.path = path + self.ioQueue = ioQueue + self.completionHandler = completionHandler + super.init() + } + + /// Handler to write captured photo data into a file. + /// - Parameters: + /// - error: The capture error + /// - photoDataProvider: A closure that provides photo data + func handlePhotoCaptureResult( + error: Error?, + photoDataProvider: @escaping () -> WritableData? + ) { + if let error = error { + completionHandler(nil, error) + return + } + + ioQueue.async { [weak self] in + guard let strongSelf = self else { return } + + do { + let data = photoDataProvider() + try data?.writeToPath(strongSelf.path, options: .atomic) + strongSelf.completionHandler(strongSelf.path, nil) + } catch { + strongSelf.completionHandler(nil, error) + } + } + } + + func photoOutput( + _ output: AVCapturePhotoOutput, + didFinishProcessingPhoto photo: AVCapturePhoto, + error: Error? + ) { + handlePhotoCaptureResult(error: error) { + photo.fileDataRepresentation() + } + } +} diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/WritableData.swift b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/WritableData.swift new file mode 100644 index 000000000000..ffc30094a5e5 --- /dev/null +++ b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation/WritableData.swift @@ -0,0 +1,20 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import Foundation + +/// A protocol which abstracts the file writing operation implemented in `Data`. +/// It exists to allow replacing `Data` in tests. +protocol WritableData { + func writeToPath( + _ path: String, + options: Data.WritingOptions + ) throws +} + +extension Data: WritableData { + func writeToPath(_ path: String, options: Data.WritingOptions) throws { + try write(to: URL(fileURLWithPath: path), options: options) + } +} diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/CameraProperties.m b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/CameraProperties.m deleted file mode 100644 index e16f238829bd..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/CameraProperties.m +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "./include/camera_avfoundation/CameraProperties.h" - -AVCaptureFlashMode FCPGetAVCaptureFlashModeForPigeonFlashMode(FCPPlatformFlashMode mode) { - switch (mode) { - case FCPPlatformFlashModeOff: - return AVCaptureFlashModeOff; - case FCPPlatformFlashModeAuto: - return AVCaptureFlashModeAuto; - case FCPPlatformFlashModeAlways: - return AVCaptureFlashModeOn; - case FCPPlatformFlashModeTorch: - NSCAssert(false, @"This mode cannot be converted, and requires custom handling."); - return -1; - } -} - -UIDeviceOrientation FCPGetUIDeviceOrientationForPigeonDeviceOrientation( - FCPPlatformDeviceOrientation orientation) { - switch (orientation) { - case FCPPlatformDeviceOrientationPortraitDown: - return UIDeviceOrientationPortraitUpsideDown; - case FCPPlatformDeviceOrientationLandscapeLeft: - return UIDeviceOrientationLandscapeLeft; - case FCPPlatformDeviceOrientationLandscapeRight: - return UIDeviceOrientationLandscapeRight; - case FCPPlatformDeviceOrientationPortraitUp: - return UIDeviceOrientationPortrait; - }; -} - -FCPPlatformDeviceOrientation FCPGetPigeonDeviceOrientationForOrientation( - UIDeviceOrientation orientation) { - switch (orientation) { - case UIDeviceOrientationPortraitUpsideDown: - return FCPPlatformDeviceOrientationPortraitDown; - case UIDeviceOrientationLandscapeLeft: - return FCPPlatformDeviceOrientationLandscapeLeft; - case UIDeviceOrientationLandscapeRight: - return FCPPlatformDeviceOrientationLandscapeRight; - case UIDeviceOrientationPortrait: - default: - return FCPPlatformDeviceOrientationPortraitUp; - }; -} - -OSType FCPGetPixelFormatForPigeonFormat(FCPPlatformImageFormatGroup imageFormat) { - switch (imageFormat) { - case FCPPlatformImageFormatGroupBgra8888: - return kCVPixelFormatType_32BGRA; - case FCPPlatformImageFormatGroupYuv420: - return kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange; - } -} diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTAssetWriter.m b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTAssetWriter.m deleted file mode 100644 index ce81673d8068..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTAssetWriter.m +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "./include/camera_avfoundation/FLTAssetWriter.h" - -@interface FLTDefaultAssetWriter () -@property(nonatomic, strong) AVAssetWriter *writer; -@end - -@implementation FLTDefaultAssetWriter - -- (instancetype)initWithURL:(NSURL *)url fileType:(AVFileType)fileType error:(NSError **)error { - self = [super init]; - if (self) { - _writer = [[AVAssetWriter alloc] initWithURL:url fileType:fileType error:error]; - } - return self; -} - -- (BOOL)startWriting { - return [_writer startWriting]; -} - -- (void)finishWritingWithCompletionHandler:(void (^)(void))handler { - [_writer finishWritingWithCompletionHandler:handler]; -} - -- (AVAssetWriterStatus)status { - return _writer.status; -} - -- (NSError *)error { - return _writer.error; -} - -- (void)startSessionAtSourceTime:(CMTime)startTime { - return [_writer startSessionAtSourceTime:startTime]; -} - -- (void)addInput:(AVAssetWriterInput *)input { - return [_writer addInput:input]; -} - -@end - -@interface FLTDefaultAssetWriterInput () -@property(nonatomic, strong) AVAssetWriterInput *input; -@end - -@implementation FLTDefaultAssetWriterInput - -- (instancetype)initWithInput:(AVAssetWriterInput *)input { - self = [super init]; - if (self) { - _input = input; - } - return self; -} - -- (BOOL)appendSampleBuffer:(CMSampleBufferRef)sampleBuffer { - return [_input appendSampleBuffer:sampleBuffer]; -} - -- (BOOL)expectsMediaDataInRealTime { - return [_input expectsMediaDataInRealTime]; -} - -- (void)setExpectsMediaDataInRealTime:(BOOL)expectsMediaDataInRealTime { - _input.expectsMediaDataInRealTime = expectsMediaDataInRealTime; -} - -- (BOOL)readyForMoreMediaData { - return _input.readyForMoreMediaData; -} - -@end - -@interface FLTDefaultAssetWriterInputPixelBufferAdaptor () -@property(nonatomic, strong) AVAssetWriterInputPixelBufferAdaptor *adaptor; -@end - -@implementation FLTDefaultAssetWriterInputPixelBufferAdaptor - -- (instancetype)initWithAdaptor:(AVAssetWriterInputPixelBufferAdaptor *)adaptor { - self = [super init]; - if (self) { - _adaptor = adaptor; - } - return self; -} - -- (BOOL)appendPixelBuffer:(CVPixelBufferRef)pixelBuffer - withPresentationTime:(CMTime)presentationTime { - return [_adaptor appendPixelBuffer:pixelBuffer withPresentationTime:presentationTime]; -} - -@end diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTCameraPermissionManager.m b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTCameraPermissionManager.m deleted file mode 100644 index 0f60ae2a475e..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTCameraPermissionManager.m +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -@import AVFoundation; -#import "./include/camera_avfoundation/FLTCameraPermissionManager.h" -#import "./include/camera_avfoundation/FLTPermissionServicing.h" - -@implementation FLTCameraPermissionManager - -- (instancetype)initWithPermissionService:(id)service { - self = [super init]; - if (self) { - _permissionService = service ?: [[FLTDefaultPermissionService alloc] init]; - } - return self; -} - -- (void)requestAudioPermissionWithCompletionHandler: - (__strong FLTCameraPermissionRequestCompletionHandler)handler { - [self requestPermissionForAudio:YES handler:handler]; -} - -- (void)requestCameraPermissionWithCompletionHandler: - (__strong FLTCameraPermissionRequestCompletionHandler)handler { - [self requestPermissionForAudio:NO handler:handler]; -} - -- (void)requestPermissionForAudio:(BOOL)forAudio - handler:(FLTCameraPermissionRequestCompletionHandler)handler { - AVMediaType mediaType; - if (forAudio) { - mediaType = AVMediaTypeAudio; - } else { - mediaType = AVMediaTypeVideo; - } - - switch ([_permissionService authorizationStatusForMediaType:mediaType]) { - case AVAuthorizationStatusAuthorized: - handler(nil); - break; - case AVAuthorizationStatusDenied: { - FlutterError *flutterError; - if (forAudio) { - flutterError = - [FlutterError errorWithCode:@"AudioAccessDeniedWithoutPrompt" - message:@"User has previously denied the audio access request. " - @"Go to Settings to enable audio access." - details:nil]; - } else { - flutterError = - [FlutterError errorWithCode:@"CameraAccessDeniedWithoutPrompt" - message:@"User has previously denied the camera access request. " - @"Go to Settings to enable camera access." - details:nil]; - } - handler(flutterError); - break; - } - case AVAuthorizationStatusRestricted: { - FlutterError *flutterError; - if (forAudio) { - flutterError = [FlutterError errorWithCode:@"AudioAccessRestricted" - message:@"Audio access is restricted." - details:nil]; - } else { - flutterError = [FlutterError errorWithCode:@"CameraAccessRestricted" - message:@"Camera access is restricted." - details:nil]; - } - handler(flutterError); - break; - } - case AVAuthorizationStatusNotDetermined: { - [_permissionService requestAccessForMediaType:mediaType - completionHandler:^(BOOL granted) { - // handler can be invoked on an arbitrary dispatch queue. - if (granted) { - handler(nil); - } else { - FlutterError *flutterError; - if (forAudio) { - flutterError = [FlutterError - errorWithCode:@"AudioAccessDenied" - message:@"User denied the audio access request." - details:nil]; - } else { - flutterError = [FlutterError - errorWithCode:@"CameraAccessDenied" - message:@"User denied the camera access request." - details:nil]; - } - handler(flutterError); - } - }]; - break; - } - } -} - -@end diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTCaptureConnection.m b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTCaptureConnection.m deleted file mode 100644 index 3a3eef81caf8..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTCaptureConnection.m +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "./include/camera_avfoundation/FLTCaptureConnection.h" - -@interface FLTDefaultCaptureConnection () -@property(nonatomic, strong) AVCaptureConnection *connection; -@end - -@implementation FLTDefaultCaptureConnection - -- (instancetype)initWithConnection:(AVCaptureConnection *)connection { - self = [super init]; - if (self) { - _connection = connection; - } - return self; -} - -- (BOOL)isVideoMirroringSupported { - return self.connection.isVideoMirroringSupported; -} - -- (BOOL)isVideoOrientationSupported { - return self.connection.isVideoOrientationSupported; -} - -- (void)setVideoMirrored:(BOOL)videoMirrored { - self.connection.videoMirrored = videoMirrored; -} - -- (BOOL)isVideoMirrored { - return self.connection.isVideoMirrored; -} - -- (void)setVideoOrientation:(AVCaptureVideoOrientation)videoOrientation { - self.connection.videoOrientation = videoOrientation; -} - -- (AVCaptureVideoOrientation)videoOrientation { - return self.connection.videoOrientation; -} - -- (NSArray *)inputPorts { - return self.connection.inputPorts; -} - -@end diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTCaptureDeviceFormat.m b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTCaptureDeviceFormat.m deleted file mode 100644 index 315b68809732..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTCaptureDeviceFormat.m +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "FLTCaptureDeviceFormat.h" - -@interface FLTDefaultFrameRateRange () -@property(nonatomic, strong) AVFrameRateRange *range; -@end - -@implementation FLTDefaultFrameRateRange - -- (instancetype)initWithRange:(AVFrameRateRange *)range { - self = [super init]; - if (self) { - _range = range; - } - return self; -} - -- (float)minFrameRate { - return _range.minFrameRate; -} - -- (float)maxFrameRate { - return _range.maxFrameRate; -} - -@end - -@interface FLTDefaultCaptureDeviceFormat () -@property(nonatomic, strong) AVCaptureDeviceFormat *format; -@end - -@implementation FLTDefaultCaptureDeviceFormat - -- (instancetype)initWithFormat:(AVCaptureDeviceFormat *)format { - self = [super init]; - if (self) { - _format = format; - } - return self; -} - -- (CMFormatDescriptionRef)formatDescription { - return _format.formatDescription; -} - -- (NSArray *> *)videoSupportedFrameRateRanges { - NSMutableArray> *ranges = - [NSMutableArray arrayWithCapacity:_format.videoSupportedFrameRateRanges.count]; - for (AVFrameRateRange *range in _format.videoSupportedFrameRateRanges) { - FLTDefaultFrameRateRange *wrapper = [[FLTDefaultFrameRateRange alloc] initWithRange:range]; - [ranges addObject:wrapper]; - } - return ranges; -} - -@end diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTImageStreamHandler.m b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTImageStreamHandler.m deleted file mode 100644 index 530bee3696db..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTImageStreamHandler.m +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -@import Flutter; - -#import "./include/camera_avfoundation/FLTImageStreamHandler.h" - -@implementation FLTImageStreamHandler - -- (instancetype)initWithCaptureSessionQueue:(dispatch_queue_t)captureSessionQueue { - self = [super init]; - NSAssert(self, @"super init cannot be nil"); - _captureSessionQueue = captureSessionQueue; - return self; -} - -- (FlutterError *_Nullable)onCancelWithArguments:(id _Nullable)arguments { - __weak typeof(self) weakSelf = self; - dispatch_async(self.captureSessionQueue, ^{ - weakSelf.eventSink = nil; - }); - return nil; -} - -- (FlutterError *_Nullable)onListenWithArguments:(id _Nullable)arguments - eventSink:(nonnull FlutterEventSink)events { - __weak typeof(self) weakSelf = self; - dispatch_async(self.captureSessionQueue, ^{ - weakSelf.eventSink = events; - }); - return nil; -} -@end diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTPermissionServicing.m b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTPermissionServicing.m deleted file mode 100644 index 83126c204ee8..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTPermissionServicing.m +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "./include/camera_avfoundation/FLTPermissionServicing.h" - -@implementation FLTDefaultPermissionService -- (AVAuthorizationStatus)authorizationStatusForMediaType:(AVMediaType)mediaType { - return [AVCaptureDevice authorizationStatusForMediaType:mediaType]; -} - -- (void)requestAccessForMediaType:(AVMediaType)mediaType - completionHandler:(void (^)(BOOL granted))handler { - [AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:handler]; -} -@end diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTSavePhotoDelegate.m b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTSavePhotoDelegate.m deleted file mode 100644 index 3cbf76201b90..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTSavePhotoDelegate.m +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "./include/camera_avfoundation/FLTSavePhotoDelegate.h" -#import "./include/camera_avfoundation/FLTSavePhotoDelegate_Test.h" - -@interface FLTSavePhotoDelegate () -/// The file path for the captured photo. -@property(readonly, nonatomic) NSString *path; -/// The queue on which captured photos are written to disk. -@property(readonly, nonatomic) dispatch_queue_t ioQueue; -@end - -@implementation FLTSavePhotoDelegate - -- (instancetype)initWithPath:(NSString *)path - ioQueue:(dispatch_queue_t)ioQueue - completionHandler:(FLTSavePhotoDelegateCompletionHandler)completionHandler { - self = [super init]; - NSAssert(self, @"super init cannot be nil"); - _path = path; - _ioQueue = ioQueue; - _completionHandler = completionHandler; - return self; -} - -- (void)handlePhotoCaptureResultWithError:(NSError *)error - photoDataProvider:(NSObject * (^)(void))photoDataProvider { - if (error) { - self.completionHandler(nil, error); - return; - } - __weak typeof(self) weakSelf = self; - dispatch_async(self.ioQueue, ^{ - typeof(self) strongSelf = weakSelf; - if (!strongSelf) return; - - NSObject *data = photoDataProvider(); - NSError *ioError; - if ([data writeToFile:strongSelf.path options:NSDataWritingAtomic error:&ioError]) { - strongSelf.completionHandler(self.path, nil); - } else { - strongSelf.completionHandler(nil, ioError); - } - }); -} - -- (void)captureOutput:(AVCapturePhotoOutput *)output - didFinishProcessingPhoto:(AVCapturePhoto *)photo - error:(NSError *)error { - [self handlePhotoCaptureResultWithError:error - photoDataProvider:^NSData * { - return [photo fileDataRepresentation]; - }]; -} - -- (NSString *)filePath { - return self.path; -} -@end diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTThreadSafeEventChannel.m b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTThreadSafeEventChannel.m deleted file mode 100644 index 9c7d4722552a..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTThreadSafeEventChannel.m +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "./include/camera_avfoundation/FLTThreadSafeEventChannel.h" -#import "./include/camera_avfoundation/FLTEventChannel.h" -#import "./include/camera_avfoundation/QueueUtils.h" - -@interface FLTThreadSafeEventChannel () -@property(nonatomic, strong) id channel; -@end - -@implementation FLTThreadSafeEventChannel - -- (instancetype)initWithEventChannel:(id)channel { - self = [super init]; - if (self) { - _channel = channel; - } - return self; -} - -- (void)setStreamHandler:(NSObject *)handler - completion:(void (^)(void))completion { - // WARNING: Should not use weak self, because FLTThreadSafeEventChannel is a local variable - // (retained within call stack, but not in the heap). FLTEnsureToRunOnMainQueue may trigger a - // context switch (when calling from background thread), in which case using weak self will always - // result in a nil self. Alternative to using strong self, we can also create a local strong - // variable to be captured by this block. - FLTEnsureToRunOnMainQueue(^{ - [self.channel setStreamHandler:handler]; - completion(); - }); -} - -@end diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTWritableData.m b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTWritableData.m deleted file mode 100644 index 180e3d70a3dd..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/FLTWritableData.m +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "./include/camera_avfoundation/FLTWritableData.h" - -@implementation FLTDefaultWritableData - -- (instancetype)initWithData:(NSData *)data { - self = [super init]; - if (self) { - _data = data; - } - return self; -} - -- (BOOL)writeToFile:(NSString *)path - options:(NSDataWritingOptions)writeOptionsMask - error:(NSError **)errorPtr { - return [self.data writeToFile:path options:writeOptionsMask error:errorPtr]; -} - -@end diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/QueueUtils.m b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/QueueUtils.m deleted file mode 100644 index 2cfca52a2993..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/QueueUtils.m +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "./include/camera_avfoundation/QueueUtils.h" - -void FLTEnsureToRunOnMainQueue(dispatch_block_t block) { - if (!NSThread.isMainThread) { - dispatch_async(dispatch_get_main_queue(), block); - } else { - block(); - } -} diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/Resources/PrivacyInfo.xcprivacy b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/Resources/PrivacyInfo.xcprivacy deleted file mode 100644 index a34b7e2e60cc..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/Resources/PrivacyInfo.xcprivacy +++ /dev/null @@ -1,14 +0,0 @@ - - - - - NSPrivacyTrackingDomains - - NSPrivacyAccessedAPITypes - - NSPrivacyCollectedDataTypes - - NSPrivacyTracking - - - diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/CameraProperties.h b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/CameraProperties.h deleted file mode 100644 index 6645cf7bb062..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/CameraProperties.h +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -@import AVFoundation; -@import Foundation; -@import UIKit; - -#import "messages.g.h" - -NS_ASSUME_NONNULL_BEGIN - -/// Gets AVCaptureFlashMode from FLTFlashMode. -/// @param mode flash mode. -extern AVCaptureFlashMode FCPGetAVCaptureFlashModeForPigeonFlashMode(FCPPlatformFlashMode mode); - -/// Gets UIDeviceOrientation from its Pigeon representation. -extern UIDeviceOrientation FCPGetUIDeviceOrientationForPigeonDeviceOrientation( - FCPPlatformDeviceOrientation orientation); - -/// Gets a Pigeon representation of UIDeviceOrientation. -extern FCPPlatformDeviceOrientation FCPGetPigeonDeviceOrientationForOrientation( - UIDeviceOrientation orientation); - -/// Gets VideoFormat from its Pigeon representation. -extern OSType FCPGetPixelFormatForPigeonFormat(FCPPlatformImageFormatGroup imageFormat); - -NS_ASSUME_NONNULL_END diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTAssetWriter.h b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTAssetWriter.h deleted file mode 100644 index b4d913964c8b..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTAssetWriter.h +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -@import Foundation; -@import AVFoundation; - -NS_ASSUME_NONNULL_BEGIN - -/// A protocol that is a direct passthrough to `AVAssetWriter`. It is used to allow for mocking -/// `AVAssetWriter` in tests. -@protocol FLTAssetWriter - -@property(nonatomic, readonly) AVAssetWriterStatus status; -@property(readonly, nullable) NSError *error; - -- (BOOL)startWriting; -- (void)finishWritingWithCompletionHandler:(void (^)(void))handler; -- (void)startSessionAtSourceTime:(CMTime)startTime; -- (void)addInput:(AVAssetWriterInput *)input; - -@end - -/// A protocol that is a direct passthrough to `AVAssetWriterInput`. It is used to allow for mocking -/// `AVAssetWriterInput` in tests. -@protocol FLTAssetWriterInput - -/// The underlying `AVAssetWriterInput` instance. All method and property calls will be forwarded -/// to this instance. -@property(nonatomic, readonly) AVAssetWriterInput *input; - -@property(nonatomic, assign) BOOL expectsMediaDataInRealTime; -@property(nonatomic, readonly) BOOL readyForMoreMediaData; - -- (BOOL)appendSampleBuffer:(CMSampleBufferRef)sampleBuffer; - -@end - -/// A protocol that is a direct passthrough to `AVAssetWriterInputPixelBufferAdaptor`. It is used to -/// allow for mocking `AVAssetWriterInputPixelBufferAdaptor` in tests. -@protocol FLTAssetWriterInputPixelBufferAdaptor -- (BOOL)appendPixelBuffer:(CVPixelBufferRef)pixelBuffer - withPresentationTime:(CMTime)presentationTime; -@end - -/// A default implementation of `FLTAssetWriter` which creates an `AVAssetWriter` instance and -/// forwards calls to it. -@interface FLTDefaultAssetWriter : NSObject - -/// Creates an `AVAssetWriter` instance with the given URL and file type. It takes the same params -/// as the `AVAssetWriter`'s initializer. -- (instancetype)initWithURL:(NSURL *)url fileType:(AVFileType)fileType error:(NSError **)error; - -@end - -/// A default implementation of `FLTAssetWriterInput` which forwards calls to the -/// underlying `AVAssetWriterInput`. -@interface FLTDefaultAssetWriterInput : NSObject - -/// Creates a wrapper around the `input` which will forward calls to it. -- (instancetype)initWithInput:(AVAssetWriterInput *)input; - -@end - -/// A default implementation of `FLTAssetWriterInputPixelBufferAdaptor` which forwards calls to the -/// underlying `AVAssetWriterInputPixelBufferAdaptor`. -@interface FLTDefaultAssetWriterInputPixelBufferAdaptor - : NSObject - -/// Creates a wrapper around the `adaptor` which will forward calls to it. -- (instancetype)initWithAdaptor:(AVAssetWriterInputPixelBufferAdaptor *)adaptor; - -@end - -NS_ASSUME_NONNULL_END diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTCameraPermissionManager.h b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTCameraPermissionManager.h deleted file mode 100644 index 7728ef9c1913..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTCameraPermissionManager.h +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -@import Foundation; -#import - -#import "FLTPermissionServicing.h" - -NS_ASSUME_NONNULL_BEGIN - -typedef void (^FLTCameraPermissionRequestCompletionHandler)(FlutterError *_Nullable); - -@interface FLTCameraPermissionManager : NSObject -@property(nonatomic, strong) id permissionService; - -- (instancetype)initWithPermissionService:(id)service; - -/// Requests camera access permission. -/// -/// If it is the first time requesting camera access, a permission dialog will show up on the -/// screen. Otherwise AVFoundation simply returns the user's previous choice, and in this case the -/// user will have to update the choice in Settings app. -/// -/// @param handler if access permission is (or was previously) granted, completion handler will be -/// called without error; Otherwise completion handler will be called with error. Handler can be -/// called on an arbitrary dispatch queue. -- (void)requestCameraPermissionWithCompletionHandler: - (FLTCameraPermissionRequestCompletionHandler)handler; - -/// Requests audio access permission. -/// -/// If it is the first time requesting audio access, a permission dialog will show up on the -/// screen. Otherwise AVFoundation simply returns the user's previous choice, and in this case the -/// user will have to update the choice in Settings app. -/// -/// @param handler if access permission is (or was previously) granted, completion handler will be -/// called without error; Otherwise completion handler will be called with error. Handler can be -/// called on an arbitrary dispatch queue. -- (void)requestAudioPermissionWithCompletionHandler: - (FLTCameraPermissionRequestCompletionHandler)handler; - -@end - -NS_ASSUME_NONNULL_END diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTCaptureConnection.h b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTCaptureConnection.h deleted file mode 100644 index 3fd5d1c084e9..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTCaptureConnection.h +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -@import AVFoundation; - -NS_ASSUME_NONNULL_BEGIN - -/// A protocol which is a direct passthrough to `AVCaptureConnection`. It exists to allow replacing -/// `AVCaptureConnection` in tests. -@protocol FLTCaptureConnection - -/// Corresponds to the `videoMirrored` property of `AVCaptureConnection` -@property(nonatomic, getter=isVideoMirrored) BOOL videoMirrored; - -/// Corresponds to the `videoOrientation` property of `AVCaptureConnection` -@property(nonatomic) AVCaptureVideoOrientation videoOrientation; - -/// Corresponds to the `inputPorts` property of `AVCaptureConnection` -@property(nonatomic, readonly) NSArray *inputPorts; - -/// Corresponds to the `supportsVideoMirroring` property of `AVCaptureConnection` -@property(nonatomic, readonly, getter=isVideoMirroringSupported) BOOL supportsVideoMirroring; - -/// Corresponds to the `supportsVideoOrientation` property of `AVCaptureConnection` -@property(nonatomic, readonly, getter=isVideoOrientationSupported) BOOL supportsVideoOrientation; - -@end - -/// A default implementation of the `FLTCaptureConnection` protocol. It wraps an instance -/// of `AVCaptureConnection`. -@interface FLTDefaultCaptureConnection : NSObject - -/// Initializes a `FLTDefaultCaptureConnection` with the given `AVCaptureConnection`. -/// All methods and property calls are passed through to this connection. -- (instancetype)initWithConnection:(AVCaptureConnection *)connection; - -@end - -NS_ASSUME_NONNULL_END diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTCaptureDeviceFormat.h b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTCaptureDeviceFormat.h deleted file mode 100644 index 08a7d1bfedc0..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTCaptureDeviceFormat.h +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -@import AVFoundation; -@import Foundation; - -NS_ASSUME_NONNULL_BEGIN - -/// A protocol which is a direct passthrough to `FLTFrameRateRange`. It exists to allow replacing -/// `AVFrameRateRange` in tests as it has no public initializer. -@protocol FLTFrameRateRange - -@property(readonly, nonatomic) float minFrameRate; -@property(readonly, nonatomic) float maxFrameRate; - -@end - -/// A protocol which is a direct passthrough to `AVCaptureDeviceFormat`. It exists to allow -/// replacing `AVCaptureDeviceFormat` in tests as it has no public initializer. -@protocol FLTCaptureDeviceFormat - -/// The underlying `AVCaptureDeviceFormat` instance that this object wraps. -@property(nonatomic, readonly) AVCaptureDeviceFormat *format; - -@property(nonatomic, readonly) CMFormatDescriptionRef formatDescription; -@property(nonatomic, readonly) - NSArray *> *videoSupportedFrameRateRanges; - -@end - -/// A default implementation of `FLTFrameRateRange` that wraps an `AVFrameRateRange` instance. -@interface FLTDefaultFrameRateRange : NSObject - -/// Initializes the object with an `AVFrameRateRange` instance. All method and property calls are -/// forwarded to this wrapped instance. -- (instancetype)initWithRange:(AVFrameRateRange *)range; - -@end - -/// A default implementation of `FLTCaptureDeviceFormat` that wraps an `AVCaptureDeviceFormat` -/// instance. -@interface FLTDefaultCaptureDeviceFormat : NSObject - -/// Initializes the object with an `AVCaptureDeviceFormat` instance. All method and property calls -/// are forwarded to this wrapped instance. -- (instancetype)initWithFormat:(AVCaptureDeviceFormat *)format; - -@end - -NS_ASSUME_NONNULL_END diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTEventChannel.h b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTEventChannel.h deleted file mode 100644 index cdadc34d5ca4..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTEventChannel.h +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -@import Flutter; - -NS_ASSUME_NONNULL_BEGIN - -/// A protocol which is a direct passthrough to FlutterStreamHandler. -/// It exists to allow replacing FlutterStreamHandler in tests. -@protocol FLTEventChannel -- (void)setStreamHandler:(nullable NSObject *)handler; -@end - -@interface FlutterEventChannel (FLTEventChannel) -@end - -NS_ASSUME_NONNULL_END diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTImageStreamHandler.h b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTImageStreamHandler.h deleted file mode 100644 index be058e98dc0b..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTImageStreamHandler.h +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -@interface FLTImageStreamHandler : NSObject - -- (instancetype)initWithCaptureSessionQueue:(dispatch_queue_t)captureSessionQueue; - -/// The queue on which `eventSink` property should be accessed. -@property(nonatomic, strong) dispatch_queue_t captureSessionQueue; - -/// The event sink to stream camera events to Dart. -/// -/// The property should only be accessed on `captureSessionQueue`. -/// The block itself should be invoked on the main queue. -@property FlutterEventSink eventSink; - -@end diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTPermissionServicing.h b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTPermissionServicing.h deleted file mode 100644 index 2a377fa2c022..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTPermissionServicing.h +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -@import AVFoundation; -@import Foundation; - -NS_ASSUME_NONNULL_BEGIN - -@protocol FLTPermissionServicing -- (AVAuthorizationStatus)authorizationStatusForMediaType:(AVMediaType)mediaType - NS_SWIFT_NAME(authorizationStatus(for:)); -- (void)requestAccessForMediaType:(AVMediaType)mediaType - completionHandler:(void (^)(BOOL granted))handler - NS_SWIFT_NAME(requestAccess(for:completion:)); -@end - -@interface FLTDefaultPermissionService : NSObject -@end - -NS_ASSUME_NONNULL_END diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTSavePhotoDelegate.h b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTSavePhotoDelegate.h deleted file mode 100644 index a6616256d878..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTSavePhotoDelegate.h +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -@import AVFoundation; -@import Flutter; -@import Foundation; - -NS_ASSUME_NONNULL_BEGIN - -/// The completion handler block for save photo operations. -/// Can be called from either main queue or IO queue. -/// If success, `error` will be present and `path` will be nil. Otherewise, `error` will be nil and -/// `path` will be present. -/// @param path the path for successfully saved photo file. -/// @param error photo capture error or IO error. -typedef void (^FLTSavePhotoDelegateCompletionHandler)(NSString *_Nullable path, - NSError *_Nullable error); - -/// Delegate object that handles photo capture results. -@interface FLTSavePhotoDelegate : NSObject - -/// Initialize a photo capture delegate. -/// @param path the path for captured photo file. -/// @param ioQueue the queue on which captured photos are written to disk. -/// @param completionHandler The completion handler block for save photo operations. Can -/// be called from either main queue or IO queue. -- (instancetype)initWithPath:(NSString *)path - ioQueue:(dispatch_queue_t)ioQueue - completionHandler:(FLTSavePhotoDelegateCompletionHandler)completionHandler; -@end - -NS_ASSUME_NONNULL_END diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTSavePhotoDelegate_Test.h b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTSavePhotoDelegate_Test.h deleted file mode 100644 index 0158f7e482ab..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTSavePhotoDelegate_Test.h +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "FLTSavePhotoDelegate.h" - -#import "FLTWritableData.h" - -/// API exposed for unit tests. -@interface FLTSavePhotoDelegate () - -/// The completion handler block for capture and save photo operations. -/// Can be called from either main queue or IO queue. -/// Exposed for unit tests to manually trigger the completion. -@property(readonly, nonatomic) FLTSavePhotoDelegateCompletionHandler completionHandler; - -/// The path for captured photo file. -/// Exposed for unit tests to verify the captured photo file path. -@property(readwrite, nonatomic) NSString *filePath; - -/// Handler to write captured photo data into a file. -/// @param error the capture error. -/// @param photoDataProvider a closure that provides photo data. -- (void)handlePhotoCaptureResultWithError:(NSError *)error - photoDataProvider:(NSObject * (^)(void))photoDataProvider - NS_SWIFT_NAME(handlePhotoCaptureResult(error:photoDataProvider:)); -@end diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTThreadSafeEventChannel.h b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTThreadSafeEventChannel.h deleted file mode 100644 index 6faa29af5d69..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTThreadSafeEventChannel.h +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import - -#import "FLTEventChannel.h" - -NS_ASSUME_NONNULL_BEGIN - -/// A thread safe wrapper for FlutterEventChannel that can be called from any thread, by dispatching -/// its underlying engine calls to the main thread. -@interface FLTThreadSafeEventChannel : NSObject - -/// Creates a FLTThreadSafeEventChannel by wrapping a FlutterEventChannel object. -/// @param channel The FlutterEventChannel object to be wrapped. -- (instancetype)initWithEventChannel:(NSObject *)channel; - -/// Registers a handler on the main thread for stream setup requests from the Flutter side. -/// The completion block runs on the main thread. -- (void)setStreamHandler:(nullable NSObject *)handler - completion:(void (^)(void))completion; - -@end - -NS_ASSUME_NONNULL_END diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTWritableData.h b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTWritableData.h deleted file mode 100644 index 019b6ad2896d..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/FLTWritableData.h +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -@import Foundation; - -NS_ASSUME_NONNULL_BEGIN - -/// A protocol which abstracts the file writing operation implemented in `NSData`. -/// It exists to allow replacing `NSData` in tests. -@protocol FLTWritableData -- (BOOL)writeToFile:(NSString *)path - options:(NSDataWritingOptions)writeOptionsMask - error:(NSError **)errorPtr; -@end - -/// A default implementation of the `FLTWritableData` protocol which operates on -/// an `NSData` instance. -@interface FLTDefaultWritableData : NSObject -@property(nonatomic, strong, readonly) NSData *data; -- (instancetype)initWithData:(NSData *)data; -@end - -NS_ASSUME_NONNULL_END diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/QueueUtils.h b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/QueueUtils.h deleted file mode 100644 index 7dcb3b948a76..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/QueueUtils.h +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import - -NS_ASSUME_NONNULL_BEGIN - -/// Ensures the given block to be run on the main queue. -/// If caller site is already on the main queue, the block will be run -/// synchronously. Otherwise, the block will be dispatched asynchronously to the -/// main queue. -/// @param block the block to be run on the main queue. -extern void FLTEnsureToRunOnMainQueue(dispatch_block_t block); - -NS_ASSUME_NONNULL_END diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/camera_avfoundation.h b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/camera_avfoundation.h deleted file mode 100644 index 77fa73867ab1..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/camera_avfoundation.h +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "FLTCameraPermissionManager.h" -#import "QueueUtils.h" -#import "messages.g.h" diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/messages.g.h b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/messages.g.h deleted file mode 100644 index 7064a15caac7..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/messages.g.h +++ /dev/null @@ -1,334 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -// Autogenerated from Pigeon (v26.1.0), do not edit directly. -// See also: https://pub.dev/packages/pigeon - -#import - -@protocol FlutterBinaryMessenger; -@protocol FlutterMessageCodec; -@class FlutterError; -@class FlutterStandardTypedData; - -NS_ASSUME_NONNULL_BEGIN - -typedef NS_ENUM(NSUInteger, FCPPlatformCameraLensDirection) { - /// Front facing camera (a user looking at the screen is seen by the camera). - FCPPlatformCameraLensDirectionFront = 0, - /// Back facing camera (a user looking at the screen is not seen by the camera). - FCPPlatformCameraLensDirectionBack = 1, - /// External camera which may not be mounted to the device. - FCPPlatformCameraLensDirectionExternal = 2, -}; - -/// Wrapper for FCPPlatformCameraLensDirection to allow for nullability. -@interface FCPPlatformCameraLensDirectionBox : NSObject -@property(nonatomic, assign) FCPPlatformCameraLensDirection value; -- (instancetype)initWithValue:(FCPPlatformCameraLensDirection)value; -@end - -typedef NS_ENUM(NSUInteger, FCPPlatformCameraLensType) { - /// A built-in wide-angle camera device type. - FCPPlatformCameraLensTypeWide = 0, - /// A built-in camera device type with a longer focal length than a wide-angle camera. - FCPPlatformCameraLensTypeTelephoto = 1, - /// A built-in camera device type with a shorter focal length than a wide-angle camera. - FCPPlatformCameraLensTypeUltraWide = 2, - /// Unknown camera device type. - FCPPlatformCameraLensTypeUnknown = 3, -}; - -/// Wrapper for FCPPlatformCameraLensType to allow for nullability. -@interface FCPPlatformCameraLensTypeBox : NSObject -@property(nonatomic, assign) FCPPlatformCameraLensType value; -- (instancetype)initWithValue:(FCPPlatformCameraLensType)value; -@end - -typedef NS_ENUM(NSUInteger, FCPPlatformDeviceOrientation) { - FCPPlatformDeviceOrientationPortraitUp = 0, - FCPPlatformDeviceOrientationLandscapeLeft = 1, - FCPPlatformDeviceOrientationPortraitDown = 2, - FCPPlatformDeviceOrientationLandscapeRight = 3, -}; - -/// Wrapper for FCPPlatformDeviceOrientation to allow for nullability. -@interface FCPPlatformDeviceOrientationBox : NSObject -@property(nonatomic, assign) FCPPlatformDeviceOrientation value; -- (instancetype)initWithValue:(FCPPlatformDeviceOrientation)value; -@end - -typedef NS_ENUM(NSUInteger, FCPPlatformExposureMode) { - FCPPlatformExposureModeAuto = 0, - FCPPlatformExposureModeLocked = 1, -}; - -/// Wrapper for FCPPlatformExposureMode to allow for nullability. -@interface FCPPlatformExposureModeBox : NSObject -@property(nonatomic, assign) FCPPlatformExposureMode value; -- (instancetype)initWithValue:(FCPPlatformExposureMode)value; -@end - -typedef NS_ENUM(NSUInteger, FCPPlatformFlashMode) { - FCPPlatformFlashModeOff = 0, - FCPPlatformFlashModeAuto = 1, - FCPPlatformFlashModeAlways = 2, - FCPPlatformFlashModeTorch = 3, -}; - -/// Wrapper for FCPPlatformFlashMode to allow for nullability. -@interface FCPPlatformFlashModeBox : NSObject -@property(nonatomic, assign) FCPPlatformFlashMode value; -- (instancetype)initWithValue:(FCPPlatformFlashMode)value; -@end - -typedef NS_ENUM(NSUInteger, FCPPlatformFocusMode) { - FCPPlatformFocusModeAuto = 0, - FCPPlatformFocusModeLocked = 1, -}; - -/// Wrapper for FCPPlatformFocusMode to allow for nullability. -@interface FCPPlatformFocusModeBox : NSObject -@property(nonatomic, assign) FCPPlatformFocusMode value; -- (instancetype)initWithValue:(FCPPlatformFocusMode)value; -@end - -/// Pigeon version of ImageFileFormat. -typedef NS_ENUM(NSUInteger, FCPPlatformImageFileFormat) { - FCPPlatformImageFileFormatJpeg = 0, - FCPPlatformImageFileFormatHeif = 1, -}; - -/// Wrapper for FCPPlatformImageFileFormat to allow for nullability. -@interface FCPPlatformImageFileFormatBox : NSObject -@property(nonatomic, assign) FCPPlatformImageFileFormat value; -- (instancetype)initWithValue:(FCPPlatformImageFileFormat)value; -@end - -typedef NS_ENUM(NSUInteger, FCPPlatformImageFormatGroup) { - FCPPlatformImageFormatGroupBgra8888 = 0, - FCPPlatformImageFormatGroupYuv420 = 1, -}; - -/// Wrapper for FCPPlatformImageFormatGroup to allow for nullability. -@interface FCPPlatformImageFormatGroupBox : NSObject -@property(nonatomic, assign) FCPPlatformImageFormatGroup value; -- (instancetype)initWithValue:(FCPPlatformImageFormatGroup)value; -@end - -typedef NS_ENUM(NSUInteger, FCPPlatformResolutionPreset) { - FCPPlatformResolutionPresetLow = 0, - FCPPlatformResolutionPresetMedium = 1, - FCPPlatformResolutionPresetHigh = 2, - FCPPlatformResolutionPresetVeryHigh = 3, - FCPPlatformResolutionPresetUltraHigh = 4, - FCPPlatformResolutionPresetMax = 5, -}; - -/// Wrapper for FCPPlatformResolutionPreset to allow for nullability. -@interface FCPPlatformResolutionPresetBox : NSObject -@property(nonatomic, assign) FCPPlatformResolutionPreset value; -- (instancetype)initWithValue:(FCPPlatformResolutionPreset)value; -@end - -@class FCPPlatformCameraDescription; -@class FCPPlatformCameraState; -@class FCPPlatformMediaSettings; -@class FCPPlatformPoint; -@class FCPPlatformSize; - -@interface FCPPlatformCameraDescription : NSObject -/// `init` unavailable to enforce nonnull fields, see the `make` class method. -- (instancetype)init NS_UNAVAILABLE; -+ (instancetype)makeWithName:(NSString *)name - lensDirection:(FCPPlatformCameraLensDirection)lensDirection - lensType:(FCPPlatformCameraLensType)lensType; -/// The name of the camera device. -@property(nonatomic, copy) NSString *name; -/// The direction the camera is facing. -@property(nonatomic, assign) FCPPlatformCameraLensDirection lensDirection; -/// The type of the camera lens. -@property(nonatomic, assign) FCPPlatformCameraLensType lensType; -@end - -@interface FCPPlatformCameraState : NSObject -/// `init` unavailable to enforce nonnull fields, see the `make` class method. -- (instancetype)init NS_UNAVAILABLE; -+ (instancetype)makeWithPreviewSize:(FCPPlatformSize *)previewSize - exposureMode:(FCPPlatformExposureMode)exposureMode - focusMode:(FCPPlatformFocusMode)focusMode - exposurePointSupported:(BOOL)exposurePointSupported - focusPointSupported:(BOOL)focusPointSupported; -/// The size of the preview, in pixels. -@property(nonatomic, strong) FCPPlatformSize *previewSize; -/// The default exposure mode -@property(nonatomic, assign) FCPPlatformExposureMode exposureMode; -/// The default focus mode -@property(nonatomic, assign) FCPPlatformFocusMode focusMode; -/// Whether setting exposure points is supported. -@property(nonatomic, assign) BOOL exposurePointSupported; -/// Whether setting focus points is supported. -@property(nonatomic, assign) BOOL focusPointSupported; -@end - -@interface FCPPlatformMediaSettings : NSObject -/// `init` unavailable to enforce nonnull fields, see the `make` class method. -- (instancetype)init NS_UNAVAILABLE; -+ (instancetype)makeWithResolutionPreset:(FCPPlatformResolutionPreset)resolutionPreset - framesPerSecond:(nullable NSNumber *)framesPerSecond - videoBitrate:(nullable NSNumber *)videoBitrate - audioBitrate:(nullable NSNumber *)audioBitrate - enableAudio:(BOOL)enableAudio; -@property(nonatomic, assign) FCPPlatformResolutionPreset resolutionPreset; -@property(nonatomic, strong, nullable) NSNumber *framesPerSecond; -@property(nonatomic, strong, nullable) NSNumber *videoBitrate; -@property(nonatomic, strong, nullable) NSNumber *audioBitrate; -@property(nonatomic, assign) BOOL enableAudio; -@end - -@interface FCPPlatformPoint : NSObject -/// `init` unavailable to enforce nonnull fields, see the `make` class method. -- (instancetype)init NS_UNAVAILABLE; -+ (instancetype)makeWithX:(double)x y:(double)y; -@property(nonatomic, assign) double x; -@property(nonatomic, assign) double y; -@end - -@interface FCPPlatformSize : NSObject -/// `init` unavailable to enforce nonnull fields, see the `make` class method. -- (instancetype)init NS_UNAVAILABLE; -+ (instancetype)makeWithWidth:(double)width height:(double)height; -@property(nonatomic, assign) double width; -@property(nonatomic, assign) double height; -@end - -/// The codec used by all APIs. -NSObject *FCPGetMessagesCodec(void); - -@protocol FCPCameraApi -/// Returns the list of available cameras. -- (void)availableCamerasWithCompletion:(void (^)(NSArray *_Nullable, - FlutterError *_Nullable))completion; -/// Create a new camera with the given settings, and returns its ID. -- (void)createCameraWithName:(NSString *)cameraName - settings:(FCPPlatformMediaSettings *)settings - completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; -/// Initializes the camera with the given ID. -- (void)initializeCamera:(NSInteger)cameraId - withImageFormat:(FCPPlatformImageFormatGroup)imageFormat - completion:(void (^)(FlutterError *_Nullable))completion; -/// Begins streaming frames from the camera. -- (void)startImageStreamWithCompletion:(void (^)(FlutterError *_Nullable))completion; -/// Stops streaming frames from the camera. -- (void)stopImageStreamWithCompletion:(void (^)(FlutterError *_Nullable))completion; -/// Called by the Dart side of the plugin when it has received the last image -/// frame sent. -/// -/// This is used to throttle sending frames across the channel. -- (void)receivedImageStreamDataWithCompletion:(void (^)(FlutterError *_Nullable))completion; -/// Indicates that the given camera is no longer being used on the Dart side, -/// and any associated resources can be cleaned up. -- (void)disposeCamera:(NSInteger)cameraId completion:(void (^)(FlutterError *_Nullable))completion; -/// Locks the camera capture to the current device orientation. -- (void)lockCaptureOrientation:(FCPPlatformDeviceOrientation)orientation - completion:(void (^)(FlutterError *_Nullable))completion; -/// Unlocks camera capture orientation, allowing it to automatically adapt to -/// device orientation. -- (void)unlockCaptureOrientationWithCompletion:(void (^)(FlutterError *_Nullable))completion; -/// Takes a picture with the current settings, and returns the path to the -/// resulting file. -- (void)takePictureWithCompletion:(void (^)(NSString *_Nullable, - FlutterError *_Nullable))completion; -/// Does any preprocessing necessary before beginning to record video. -- (void)prepareForVideoRecordingWithCompletion:(void (^)(FlutterError *_Nullable))completion; -/// Begins recording video, optionally enabling streaming to Dart at the same -/// time. -- (void)startVideoRecordingWithStreaming:(BOOL)enableStream - completion:(void (^)(FlutterError *_Nullable))completion; -/// Stops recording video, and results the path to the resulting file. -- (void)stopVideoRecordingWithCompletion:(void (^)(NSString *_Nullable, - FlutterError *_Nullable))completion; -/// Pauses video recording. -- (void)pauseVideoRecordingWithCompletion:(void (^)(FlutterError *_Nullable))completion; -/// Resumes a previously paused video recording. -- (void)resumeVideoRecordingWithCompletion:(void (^)(FlutterError *_Nullable))completion; -/// Switches the camera to the given flash mode. -- (void)setFlashMode:(FCPPlatformFlashMode)mode - completion:(void (^)(FlutterError *_Nullable))completion; -/// Switches the camera to the given exposure mode. -- (void)setExposureMode:(FCPPlatformExposureMode)mode - completion:(void (^)(FlutterError *_Nullable))completion; -/// Anchors auto-exposure to the given point in (0,1) coordinate space. -/// -/// A null value resets to the default exposure point. -- (void)setExposurePoint:(nullable FCPPlatformPoint *)point - completion:(void (^)(FlutterError *_Nullable))completion; -/// Returns the minimum exposure offset supported by the camera. -- (void)getMinimumExposureOffset:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; -/// Returns the maximum exposure offset supported by the camera. -- (void)getMaximumExposureOffset:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; -/// Sets the exposure offset manually to the given value. -- (void)setExposureOffset:(double)offset completion:(void (^)(FlutterError *_Nullable))completion; -/// Switches the camera to the given focus mode. -- (void)setFocusMode:(FCPPlatformFocusMode)mode - completion:(void (^)(FlutterError *_Nullable))completion; -/// Anchors auto-focus to the given point in (0,1) coordinate space. -/// -/// A null value resets to the default focus point. -- (void)setFocusPoint:(nullable FCPPlatformPoint *)point - completion:(void (^)(FlutterError *_Nullable))completion; -/// Returns the minimum zoom level supported by the camera. -- (void)getMinimumZoomLevel:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; -/// Returns the maximum zoom level supported by the camera. -- (void)getMaximumZoomLevel:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion; -/// Sets the zoom factor. -- (void)setZoomLevel:(double)zoom completion:(void (^)(FlutterError *_Nullable))completion; -/// Pauses streaming of preview frames. -- (void)pausePreviewWithCompletion:(void (^)(FlutterError *_Nullable))completion; -/// Resumes a previously paused preview stream. -- (void)resumePreviewWithCompletion:(void (^)(FlutterError *_Nullable))completion; -/// Changes the camera used while recording video. -/// -/// This should only be called while video recording is active. -- (void)updateDescriptionWhileRecordingCameraName:(NSString *)cameraName - completion:(void (^)(FlutterError *_Nullable))completion; -/// Sets the file format used for taking pictures. -- (void)setImageFileFormat:(FCPPlatformImageFileFormat)format - completion:(void (^)(FlutterError *_Nullable))completion; -@end - -extern void SetUpFCPCameraApi(id binaryMessenger, - NSObject *_Nullable api); - -extern void SetUpFCPCameraApiWithSuffix(id binaryMessenger, - NSObject *_Nullable api, - NSString *messageChannelSuffix); - -/// Handler for native callbacks that are not tied to a specific camera ID. -@interface FCPCameraGlobalEventApi : NSObject -- (instancetype)initWithBinaryMessenger:(id)binaryMessenger; -- (instancetype)initWithBinaryMessenger:(id)binaryMessenger - messageChannelSuffix:(nullable NSString *)messageChannelSuffix; -/// Called when the device's physical orientation changes. -- (void)deviceOrientationChangedOrientation:(FCPPlatformDeviceOrientation)orientation - completion:(void (^)(FlutterError *_Nullable))completion; -@end - -/// Handler for native callbacks that are tied to a specific camera ID. -/// -/// This is intended to be initialized with the camera ID as a suffix. -@interface FCPCameraEventApi : NSObject -- (instancetype)initWithBinaryMessenger:(id)binaryMessenger; -- (instancetype)initWithBinaryMessenger:(id)binaryMessenger - messageChannelSuffix:(nullable NSString *)messageChannelSuffix; -/// Called when the camera is inialitized for use. -- (void)initializedWithState:(FCPPlatformCameraState *)initialState - completion:(void (^)(FlutterError *_Nullable))completion; -/// Called when an error occurs in the camera. -/// -/// This should be used for errors that occur outside of the context of -/// handling a specific HostApi call, such as during streaming. -- (void)reportError:(NSString *)message completion:(void (^)(FlutterError *_Nullable))completion; -@end - -NS_ASSUME_NONNULL_END diff --git a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/messages.g.m b/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/messages.g.m deleted file mode 100644 index 64524e708c7d..000000000000 --- a/packages/camera/camera_avfoundation/ios/camera_avfoundation/Sources/camera_avfoundation_objc/messages.g.m +++ /dev/null @@ -1,1367 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -// Autogenerated from Pigeon (v26.1.0), do not edit directly. -// See also: https://pub.dev/packages/pigeon - -#import "./include/camera_avfoundation/messages.g.h" - -#if TARGET_OS_OSX -#import -#else -#import -#endif - -#if !__has_feature(objc_arc) -#error File requires ARC to be enabled. -#endif - -static NSArray *wrapResult(id result, FlutterError *error) { - if (error) { - return @[ - error.code ?: [NSNull null], error.message ?: [NSNull null], error.details ?: [NSNull null] - ]; - } - return @[ result ?: [NSNull null] ]; -} - -static FlutterError *createConnectionError(NSString *channelName) { - return [FlutterError - errorWithCode:@"channel-error" - message:[NSString stringWithFormat:@"%@/%@/%@", - @"Unable to establish connection on channel: '", - channelName, @"'."] - details:@""]; -} - -static id GetNullableObjectAtIndex(NSArray *array, NSInteger key) { - id result = array[key]; - return (result == [NSNull null]) ? nil : result; -} - -@implementation FCPPlatformCameraLensDirectionBox -- (instancetype)initWithValue:(FCPPlatformCameraLensDirection)value { - self = [super init]; - if (self) { - _value = value; - } - return self; -} -@end - -@implementation FCPPlatformCameraLensTypeBox -- (instancetype)initWithValue:(FCPPlatformCameraLensType)value { - self = [super init]; - if (self) { - _value = value; - } - return self; -} -@end - -@implementation FCPPlatformDeviceOrientationBox -- (instancetype)initWithValue:(FCPPlatformDeviceOrientation)value { - self = [super init]; - if (self) { - _value = value; - } - return self; -} -@end - -@implementation FCPPlatformExposureModeBox -- (instancetype)initWithValue:(FCPPlatformExposureMode)value { - self = [super init]; - if (self) { - _value = value; - } - return self; -} -@end - -@implementation FCPPlatformFlashModeBox -- (instancetype)initWithValue:(FCPPlatformFlashMode)value { - self = [super init]; - if (self) { - _value = value; - } - return self; -} -@end - -@implementation FCPPlatformFocusModeBox -- (instancetype)initWithValue:(FCPPlatformFocusMode)value { - self = [super init]; - if (self) { - _value = value; - } - return self; -} -@end - -/// Pigeon version of ImageFileFormat. -@implementation FCPPlatformImageFileFormatBox -- (instancetype)initWithValue:(FCPPlatformImageFileFormat)value { - self = [super init]; - if (self) { - _value = value; - } - return self; -} -@end - -@implementation FCPPlatformImageFormatGroupBox -- (instancetype)initWithValue:(FCPPlatformImageFormatGroup)value { - self = [super init]; - if (self) { - _value = value; - } - return self; -} -@end - -@implementation FCPPlatformResolutionPresetBox -- (instancetype)initWithValue:(FCPPlatformResolutionPreset)value { - self = [super init]; - if (self) { - _value = value; - } - return self; -} -@end - -@interface FCPPlatformCameraDescription () -+ (FCPPlatformCameraDescription *)fromList:(NSArray *)list; -+ (nullable FCPPlatformCameraDescription *)nullableFromList:(NSArray *)list; -- (NSArray *)toList; -@end - -@interface FCPPlatformCameraState () -+ (FCPPlatformCameraState *)fromList:(NSArray *)list; -+ (nullable FCPPlatformCameraState *)nullableFromList:(NSArray *)list; -- (NSArray *)toList; -@end - -@interface FCPPlatformMediaSettings () -+ (FCPPlatformMediaSettings *)fromList:(NSArray *)list; -+ (nullable FCPPlatformMediaSettings *)nullableFromList:(NSArray *)list; -- (NSArray *)toList; -@end - -@interface FCPPlatformPoint () -+ (FCPPlatformPoint *)fromList:(NSArray *)list; -+ (nullable FCPPlatformPoint *)nullableFromList:(NSArray *)list; -- (NSArray *)toList; -@end - -@interface FCPPlatformSize () -+ (FCPPlatformSize *)fromList:(NSArray *)list; -+ (nullable FCPPlatformSize *)nullableFromList:(NSArray *)list; -- (NSArray *)toList; -@end - -@implementation FCPPlatformCameraDescription -+ (instancetype)makeWithName:(NSString *)name - lensDirection:(FCPPlatformCameraLensDirection)lensDirection - lensType:(FCPPlatformCameraLensType)lensType { - FCPPlatformCameraDescription *pigeonResult = [[FCPPlatformCameraDescription alloc] init]; - pigeonResult.name = name; - pigeonResult.lensDirection = lensDirection; - pigeonResult.lensType = lensType; - return pigeonResult; -} -+ (FCPPlatformCameraDescription *)fromList:(NSArray *)list { - FCPPlatformCameraDescription *pigeonResult = [[FCPPlatformCameraDescription alloc] init]; - pigeonResult.name = GetNullableObjectAtIndex(list, 0); - FCPPlatformCameraLensDirectionBox *boxedFCPPlatformCameraLensDirection = - GetNullableObjectAtIndex(list, 1); - pigeonResult.lensDirection = boxedFCPPlatformCameraLensDirection.value; - FCPPlatformCameraLensTypeBox *boxedFCPPlatformCameraLensType = GetNullableObjectAtIndex(list, 2); - pigeonResult.lensType = boxedFCPPlatformCameraLensType.value; - return pigeonResult; -} -+ (nullable FCPPlatformCameraDescription *)nullableFromList:(NSArray *)list { - return (list) ? [FCPPlatformCameraDescription fromList:list] : nil; -} -- (NSArray *)toList { - return @[ - self.name ?: [NSNull null], - [[FCPPlatformCameraLensDirectionBox alloc] initWithValue:self.lensDirection], - [[FCPPlatformCameraLensTypeBox alloc] initWithValue:self.lensType], - ]; -} -@end - -@implementation FCPPlatformCameraState -+ (instancetype)makeWithPreviewSize:(FCPPlatformSize *)previewSize - exposureMode:(FCPPlatformExposureMode)exposureMode - focusMode:(FCPPlatformFocusMode)focusMode - exposurePointSupported:(BOOL)exposurePointSupported - focusPointSupported:(BOOL)focusPointSupported { - FCPPlatformCameraState *pigeonResult = [[FCPPlatformCameraState alloc] init]; - pigeonResult.previewSize = previewSize; - pigeonResult.exposureMode = exposureMode; - pigeonResult.focusMode = focusMode; - pigeonResult.exposurePointSupported = exposurePointSupported; - pigeonResult.focusPointSupported = focusPointSupported; - return pigeonResult; -} -+ (FCPPlatformCameraState *)fromList:(NSArray *)list { - FCPPlatformCameraState *pigeonResult = [[FCPPlatformCameraState alloc] init]; - pigeonResult.previewSize = GetNullableObjectAtIndex(list, 0); - FCPPlatformExposureModeBox *boxedFCPPlatformExposureMode = GetNullableObjectAtIndex(list, 1); - pigeonResult.exposureMode = boxedFCPPlatformExposureMode.value; - FCPPlatformFocusModeBox *boxedFCPPlatformFocusMode = GetNullableObjectAtIndex(list, 2); - pigeonResult.focusMode = boxedFCPPlatformFocusMode.value; - pigeonResult.exposurePointSupported = [GetNullableObjectAtIndex(list, 3) boolValue]; - pigeonResult.focusPointSupported = [GetNullableObjectAtIndex(list, 4) boolValue]; - return pigeonResult; -} -+ (nullable FCPPlatformCameraState *)nullableFromList:(NSArray *)list { - return (list) ? [FCPPlatformCameraState fromList:list] : nil; -} -- (NSArray *)toList { - return @[ - self.previewSize ?: [NSNull null], - [[FCPPlatformExposureModeBox alloc] initWithValue:self.exposureMode], - [[FCPPlatformFocusModeBox alloc] initWithValue:self.focusMode], - @(self.exposurePointSupported), - @(self.focusPointSupported), - ]; -} -@end - -@implementation FCPPlatformMediaSettings -+ (instancetype)makeWithResolutionPreset:(FCPPlatformResolutionPreset)resolutionPreset - framesPerSecond:(nullable NSNumber *)framesPerSecond - videoBitrate:(nullable NSNumber *)videoBitrate - audioBitrate:(nullable NSNumber *)audioBitrate - enableAudio:(BOOL)enableAudio { - FCPPlatformMediaSettings *pigeonResult = [[FCPPlatformMediaSettings alloc] init]; - pigeonResult.resolutionPreset = resolutionPreset; - pigeonResult.framesPerSecond = framesPerSecond; - pigeonResult.videoBitrate = videoBitrate; - pigeonResult.audioBitrate = audioBitrate; - pigeonResult.enableAudio = enableAudio; - return pigeonResult; -} -+ (FCPPlatformMediaSettings *)fromList:(NSArray *)list { - FCPPlatformMediaSettings *pigeonResult = [[FCPPlatformMediaSettings alloc] init]; - FCPPlatformResolutionPresetBox *boxedFCPPlatformResolutionPreset = - GetNullableObjectAtIndex(list, 0); - pigeonResult.resolutionPreset = boxedFCPPlatformResolutionPreset.value; - pigeonResult.framesPerSecond = GetNullableObjectAtIndex(list, 1); - pigeonResult.videoBitrate = GetNullableObjectAtIndex(list, 2); - pigeonResult.audioBitrate = GetNullableObjectAtIndex(list, 3); - pigeonResult.enableAudio = [GetNullableObjectAtIndex(list, 4) boolValue]; - return pigeonResult; -} -+ (nullable FCPPlatformMediaSettings *)nullableFromList:(NSArray *)list { - return (list) ? [FCPPlatformMediaSettings fromList:list] : nil; -} -- (NSArray *)toList { - return @[ - [[FCPPlatformResolutionPresetBox alloc] initWithValue:self.resolutionPreset], - self.framesPerSecond ?: [NSNull null], - self.videoBitrate ?: [NSNull null], - self.audioBitrate ?: [NSNull null], - @(self.enableAudio), - ]; -} -@end - -@implementation FCPPlatformPoint -+ (instancetype)makeWithX:(double)x y:(double)y { - FCPPlatformPoint *pigeonResult = [[FCPPlatformPoint alloc] init]; - pigeonResult.x = x; - pigeonResult.y = y; - return pigeonResult; -} -+ (FCPPlatformPoint *)fromList:(NSArray *)list { - FCPPlatformPoint *pigeonResult = [[FCPPlatformPoint alloc] init]; - pigeonResult.x = [GetNullableObjectAtIndex(list, 0) doubleValue]; - pigeonResult.y = [GetNullableObjectAtIndex(list, 1) doubleValue]; - return pigeonResult; -} -+ (nullable FCPPlatformPoint *)nullableFromList:(NSArray *)list { - return (list) ? [FCPPlatformPoint fromList:list] : nil; -} -- (NSArray *)toList { - return @[ - @(self.x), - @(self.y), - ]; -} -@end - -@implementation FCPPlatformSize -+ (instancetype)makeWithWidth:(double)width height:(double)height { - FCPPlatformSize *pigeonResult = [[FCPPlatformSize alloc] init]; - pigeonResult.width = width; - pigeonResult.height = height; - return pigeonResult; -} -+ (FCPPlatformSize *)fromList:(NSArray *)list { - FCPPlatformSize *pigeonResult = [[FCPPlatformSize alloc] init]; - pigeonResult.width = [GetNullableObjectAtIndex(list, 0) doubleValue]; - pigeonResult.height = [GetNullableObjectAtIndex(list, 1) doubleValue]; - return pigeonResult; -} -+ (nullable FCPPlatformSize *)nullableFromList:(NSArray *)list { - return (list) ? [FCPPlatformSize fromList:list] : nil; -} -- (NSArray *)toList { - return @[ - @(self.width), - @(self.height), - ]; -} -@end - -@interface FCPMessagesPigeonCodecReader : FlutterStandardReader -@end -@implementation FCPMessagesPigeonCodecReader -- (nullable id)readValueOfType:(UInt8)type { - switch (type) { - case 129: { - NSNumber *enumAsNumber = [self readValue]; - return enumAsNumber == nil ? nil - : [[FCPPlatformCameraLensDirectionBox alloc] - initWithValue:[enumAsNumber integerValue]]; - } - case 130: { - NSNumber *enumAsNumber = [self readValue]; - return enumAsNumber == nil - ? nil - : [[FCPPlatformCameraLensTypeBox alloc] initWithValue:[enumAsNumber integerValue]]; - } - case 131: { - NSNumber *enumAsNumber = [self readValue]; - return enumAsNumber == nil ? nil - : [[FCPPlatformDeviceOrientationBox alloc] - initWithValue:[enumAsNumber integerValue]]; - } - case 132: { - NSNumber *enumAsNumber = [self readValue]; - return enumAsNumber == nil - ? nil - : [[FCPPlatformExposureModeBox alloc] initWithValue:[enumAsNumber integerValue]]; - } - case 133: { - NSNumber *enumAsNumber = [self readValue]; - return enumAsNumber == nil - ? nil - : [[FCPPlatformFlashModeBox alloc] initWithValue:[enumAsNumber integerValue]]; - } - case 134: { - NSNumber *enumAsNumber = [self readValue]; - return enumAsNumber == nil - ? nil - : [[FCPPlatformFocusModeBox alloc] initWithValue:[enumAsNumber integerValue]]; - } - case 135: { - NSNumber *enumAsNumber = [self readValue]; - return enumAsNumber == nil ? nil - : [[FCPPlatformImageFileFormatBox alloc] - initWithValue:[enumAsNumber integerValue]]; - } - case 136: { - NSNumber *enumAsNumber = [self readValue]; - return enumAsNumber == nil ? nil - : [[FCPPlatformImageFormatGroupBox alloc] - initWithValue:[enumAsNumber integerValue]]; - } - case 137: { - NSNumber *enumAsNumber = [self readValue]; - return enumAsNumber == nil ? nil - : [[FCPPlatformResolutionPresetBox alloc] - initWithValue:[enumAsNumber integerValue]]; - } - case 138: - return [FCPPlatformCameraDescription fromList:[self readValue]]; - case 139: - return [FCPPlatformCameraState fromList:[self readValue]]; - case 140: - return [FCPPlatformMediaSettings fromList:[self readValue]]; - case 141: - return [FCPPlatformPoint fromList:[self readValue]]; - case 142: - return [FCPPlatformSize fromList:[self readValue]]; - default: - return [super readValueOfType:type]; - } -} -@end - -@interface FCPMessagesPigeonCodecWriter : FlutterStandardWriter -@end -@implementation FCPMessagesPigeonCodecWriter -- (void)writeValue:(id)value { - if ([value isKindOfClass:[FCPPlatformCameraLensDirectionBox class]]) { - FCPPlatformCameraLensDirectionBox *box = (FCPPlatformCameraLensDirectionBox *)value; - [self writeByte:129]; - [self writeValue:(value == nil ? [NSNull null] : [NSNumber numberWithInteger:box.value])]; - } else if ([value isKindOfClass:[FCPPlatformCameraLensTypeBox class]]) { - FCPPlatformCameraLensTypeBox *box = (FCPPlatformCameraLensTypeBox *)value; - [self writeByte:130]; - [self writeValue:(value == nil ? [NSNull null] : [NSNumber numberWithInteger:box.value])]; - } else if ([value isKindOfClass:[FCPPlatformDeviceOrientationBox class]]) { - FCPPlatformDeviceOrientationBox *box = (FCPPlatformDeviceOrientationBox *)value; - [self writeByte:131]; - [self writeValue:(value == nil ? [NSNull null] : [NSNumber numberWithInteger:box.value])]; - } else if ([value isKindOfClass:[FCPPlatformExposureModeBox class]]) { - FCPPlatformExposureModeBox *box = (FCPPlatformExposureModeBox *)value; - [self writeByte:132]; - [self writeValue:(value == nil ? [NSNull null] : [NSNumber numberWithInteger:box.value])]; - } else if ([value isKindOfClass:[FCPPlatformFlashModeBox class]]) { - FCPPlatformFlashModeBox *box = (FCPPlatformFlashModeBox *)value; - [self writeByte:133]; - [self writeValue:(value == nil ? [NSNull null] : [NSNumber numberWithInteger:box.value])]; - } else if ([value isKindOfClass:[FCPPlatformFocusModeBox class]]) { - FCPPlatformFocusModeBox *box = (FCPPlatformFocusModeBox *)value; - [self writeByte:134]; - [self writeValue:(value == nil ? [NSNull null] : [NSNumber numberWithInteger:box.value])]; - } else if ([value isKindOfClass:[FCPPlatformImageFileFormatBox class]]) { - FCPPlatformImageFileFormatBox *box = (FCPPlatformImageFileFormatBox *)value; - [self writeByte:135]; - [self writeValue:(value == nil ? [NSNull null] : [NSNumber numberWithInteger:box.value])]; - } else if ([value isKindOfClass:[FCPPlatformImageFormatGroupBox class]]) { - FCPPlatformImageFormatGroupBox *box = (FCPPlatformImageFormatGroupBox *)value; - [self writeByte:136]; - [self writeValue:(value == nil ? [NSNull null] : [NSNumber numberWithInteger:box.value])]; - } else if ([value isKindOfClass:[FCPPlatformResolutionPresetBox class]]) { - FCPPlatformResolutionPresetBox *box = (FCPPlatformResolutionPresetBox *)value; - [self writeByte:137]; - [self writeValue:(value == nil ? [NSNull null] : [NSNumber numberWithInteger:box.value])]; - } else if ([value isKindOfClass:[FCPPlatformCameraDescription class]]) { - [self writeByte:138]; - [self writeValue:[value toList]]; - } else if ([value isKindOfClass:[FCPPlatformCameraState class]]) { - [self writeByte:139]; - [self writeValue:[value toList]]; - } else if ([value isKindOfClass:[FCPPlatformMediaSettings class]]) { - [self writeByte:140]; - [self writeValue:[value toList]]; - } else if ([value isKindOfClass:[FCPPlatformPoint class]]) { - [self writeByte:141]; - [self writeValue:[value toList]]; - } else if ([value isKindOfClass:[FCPPlatformSize class]]) { - [self writeByte:142]; - [self writeValue:[value toList]]; - } else { - [super writeValue:value]; - } -} -@end - -@interface FCPMessagesPigeonCodecReaderWriter : FlutterStandardReaderWriter -@end -@implementation FCPMessagesPigeonCodecReaderWriter -- (FlutterStandardWriter *)writerWithData:(NSMutableData *)data { - return [[FCPMessagesPigeonCodecWriter alloc] initWithData:data]; -} -- (FlutterStandardReader *)readerWithData:(NSData *)data { - return [[FCPMessagesPigeonCodecReader alloc] initWithData:data]; -} -@end - -NSObject *FCPGetMessagesCodec(void) { - static FlutterStandardMessageCodec *sSharedObject = nil; - static dispatch_once_t sPred = 0; - dispatch_once(&sPred, ^{ - FCPMessagesPigeonCodecReaderWriter *readerWriter = - [[FCPMessagesPigeonCodecReaderWriter alloc] init]; - sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter]; - }); - return sSharedObject; -} -void SetUpFCPCameraApi(id binaryMessenger, NSObject *api) { - SetUpFCPCameraApiWithSuffix(binaryMessenger, api, @""); -} - -void SetUpFCPCameraApiWithSuffix(id binaryMessenger, - NSObject *api, NSString *messageChannelSuffix) { - messageChannelSuffix = messageChannelSuffix.length > 0 - ? [NSString stringWithFormat:@".%@", messageChannelSuffix] - : @""; - /// Returns the list of available cameras. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString stringWithFormat:@"%@%@", - @"dev.flutter.pigeon.camera_avfoundation." - @"CameraApi.getAvailableCameras", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert( - [api respondsToSelector:@selector(availableCamerasWithCompletion:)], - @"FCPCameraApi api (%@) doesn't respond to @selector(availableCamerasWithCompletion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api availableCamerasWithCompletion:^( - NSArray *_Nullable output, - FlutterError *_Nullable error) { - callback(wrapResult(output, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Create a new camera with the given settings, and returns its ID. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString stringWithFormat: - @"%@%@", - @"dev.flutter.pigeon.camera_avfoundation.CameraApi.create", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert([api respondsToSelector:@selector(createCameraWithName:settings:completion:)], - @"FCPCameraApi api (%@) doesn't respond to " - @"@selector(createCameraWithName:settings:completion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - NSArray *args = message; - NSString *arg_cameraName = GetNullableObjectAtIndex(args, 0); - FCPPlatformMediaSettings *arg_settings = GetNullableObjectAtIndex(args, 1); - [api createCameraWithName:arg_cameraName - settings:arg_settings - completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { - callback(wrapResult(output, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Initializes the camera with the given ID. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName: - [NSString - stringWithFormat:@"%@%@", - @"dev.flutter.pigeon.camera_avfoundation.CameraApi.initialize", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert([api respondsToSelector:@selector(initializeCamera:withImageFormat:completion:)], - @"FCPCameraApi api (%@) doesn't respond to " - @"@selector(initializeCamera:withImageFormat:completion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - NSArray *args = message; - NSInteger arg_cameraId = [GetNullableObjectAtIndex(args, 0) integerValue]; - FCPPlatformImageFormatGroupBox *boxedFCPPlatformImageFormatGroup = - GetNullableObjectAtIndex(args, 1); - FCPPlatformImageFormatGroup arg_imageFormat = boxedFCPPlatformImageFormatGroup.value; - [api initializeCamera:arg_cameraId - withImageFormat:arg_imageFormat - completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Begins streaming frames from the camera. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString stringWithFormat:@"%@%@", - @"dev.flutter.pigeon.camera_avfoundation." - @"CameraApi.startImageStream", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert( - [api respondsToSelector:@selector(startImageStreamWithCompletion:)], - @"FCPCameraApi api (%@) doesn't respond to @selector(startImageStreamWithCompletion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api startImageStreamWithCompletion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Stops streaming frames from the camera. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString - stringWithFormat: - @"%@%@", - @"dev.flutter.pigeon.camera_avfoundation.CameraApi.stopImageStream", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert( - [api respondsToSelector:@selector(stopImageStreamWithCompletion:)], - @"FCPCameraApi api (%@) doesn't respond to @selector(stopImageStreamWithCompletion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api stopImageStreamWithCompletion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Called by the Dart side of the plugin when it has received the last image - /// frame sent. - /// - /// This is used to throttle sending frames across the channel. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString stringWithFormat:@"%@%@", - @"dev.flutter.pigeon.camera_avfoundation." - @"CameraApi.receivedImageStreamData", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert([api respondsToSelector:@selector(receivedImageStreamDataWithCompletion:)], - @"FCPCameraApi api (%@) doesn't respond to " - @"@selector(receivedImageStreamDataWithCompletion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api receivedImageStreamDataWithCompletion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Indicates that the given camera is no longer being used on the Dart side, - /// and any associated resources can be cleaned up. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString stringWithFormat: - @"%@%@", - @"dev.flutter.pigeon.camera_avfoundation.CameraApi.dispose", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert([api respondsToSelector:@selector(disposeCamera:completion:)], - @"FCPCameraApi api (%@) doesn't respond to @selector(disposeCamera:completion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - NSArray *args = message; - NSInteger arg_cameraId = [GetNullableObjectAtIndex(args, 0) integerValue]; - [api disposeCamera:arg_cameraId - completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Locks the camera capture to the current device orientation. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString stringWithFormat:@"%@%@", - @"dev.flutter.pigeon.camera_avfoundation." - @"CameraApi.lockCaptureOrientation", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert( - [api respondsToSelector:@selector(lockCaptureOrientation:completion:)], - @"FCPCameraApi api (%@) doesn't respond to @selector(lockCaptureOrientation:completion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - NSArray *args = message; - FCPPlatformDeviceOrientationBox *boxedFCPPlatformDeviceOrientation = - GetNullableObjectAtIndex(args, 0); - FCPPlatformDeviceOrientation arg_orientation = boxedFCPPlatformDeviceOrientation.value; - [api lockCaptureOrientation:arg_orientation - completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Unlocks camera capture orientation, allowing it to automatically adapt to - /// device orientation. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString stringWithFormat:@"%@%@", - @"dev.flutter.pigeon.camera_avfoundation." - @"CameraApi.unlockCaptureOrientation", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert([api respondsToSelector:@selector(unlockCaptureOrientationWithCompletion:)], - @"FCPCameraApi api (%@) doesn't respond to " - @"@selector(unlockCaptureOrientationWithCompletion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api unlockCaptureOrientationWithCompletion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Takes a picture with the current settings, and returns the path to the - /// resulting file. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName: - [NSString - stringWithFormat:@"%@%@", - @"dev.flutter.pigeon.camera_avfoundation.CameraApi.takePicture", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert([api respondsToSelector:@selector(takePictureWithCompletion:)], - @"FCPCameraApi api (%@) doesn't respond to @selector(takePictureWithCompletion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api - takePictureWithCompletion:^(NSString *_Nullable output, FlutterError *_Nullable error) { - callback(wrapResult(output, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Does any preprocessing necessary before beginning to record video. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString stringWithFormat:@"%@%@", - @"dev.flutter.pigeon.camera_avfoundation." - @"CameraApi.prepareForVideoRecording", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert([api respondsToSelector:@selector(prepareForVideoRecordingWithCompletion:)], - @"FCPCameraApi api (%@) doesn't respond to " - @"@selector(prepareForVideoRecordingWithCompletion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api prepareForVideoRecordingWithCompletion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Begins recording video, optionally enabling streaming to Dart at the same - /// time. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString stringWithFormat:@"%@%@", - @"dev.flutter.pigeon.camera_avfoundation." - @"CameraApi.startVideoRecording", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert([api respondsToSelector:@selector(startVideoRecordingWithStreaming:completion:)], - @"FCPCameraApi api (%@) doesn't respond to " - @"@selector(startVideoRecordingWithStreaming:completion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - NSArray *args = message; - BOOL arg_enableStream = [GetNullableObjectAtIndex(args, 0) boolValue]; - [api startVideoRecordingWithStreaming:arg_enableStream - completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Stops recording video, and results the path to the resulting file. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString stringWithFormat:@"%@%@", - @"dev.flutter.pigeon.camera_avfoundation." - @"CameraApi.stopVideoRecording", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert( - [api respondsToSelector:@selector(stopVideoRecordingWithCompletion:)], - @"FCPCameraApi api (%@) doesn't respond to @selector(stopVideoRecordingWithCompletion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api stopVideoRecordingWithCompletion:^(NSString *_Nullable output, - FlutterError *_Nullable error) { - callback(wrapResult(output, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Pauses video recording. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString stringWithFormat:@"%@%@", - @"dev.flutter.pigeon.camera_avfoundation." - @"CameraApi.pauseVideoRecording", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert( - [api respondsToSelector:@selector(pauseVideoRecordingWithCompletion:)], - @"FCPCameraApi api (%@) doesn't respond to @selector(pauseVideoRecordingWithCompletion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api pauseVideoRecordingWithCompletion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Resumes a previously paused video recording. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString stringWithFormat:@"%@%@", - @"dev.flutter.pigeon.camera_avfoundation." - @"CameraApi.resumeVideoRecording", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert([api respondsToSelector:@selector(resumeVideoRecordingWithCompletion:)], - @"FCPCameraApi api (%@) doesn't respond to " - @"@selector(resumeVideoRecordingWithCompletion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api resumeVideoRecordingWithCompletion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Switches the camera to the given flash mode. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString - stringWithFormat: - @"%@%@", - @"dev.flutter.pigeon.camera_avfoundation.CameraApi.setFlashMode", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert([api respondsToSelector:@selector(setFlashMode:completion:)], - @"FCPCameraApi api (%@) doesn't respond to @selector(setFlashMode:completion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - NSArray *args = message; - FCPPlatformFlashModeBox *boxedFCPPlatformFlashMode = GetNullableObjectAtIndex(args, 0); - FCPPlatformFlashMode arg_mode = boxedFCPPlatformFlashMode.value; - [api setFlashMode:arg_mode - completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Switches the camera to the given exposure mode. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString - stringWithFormat: - @"%@%@", - @"dev.flutter.pigeon.camera_avfoundation.CameraApi.setExposureMode", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert([api respondsToSelector:@selector(setExposureMode:completion:)], - @"FCPCameraApi api (%@) doesn't respond to @selector(setExposureMode:completion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - NSArray *args = message; - FCPPlatformExposureModeBox *boxedFCPPlatformExposureMode = - GetNullableObjectAtIndex(args, 0); - FCPPlatformExposureMode arg_mode = boxedFCPPlatformExposureMode.value; - [api setExposureMode:arg_mode - completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Anchors auto-exposure to the given point in (0,1) coordinate space. - /// - /// A null value resets to the default exposure point. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString stringWithFormat:@"%@%@", - @"dev.flutter.pigeon.camera_avfoundation." - @"CameraApi.setExposurePoint", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert([api respondsToSelector:@selector(setExposurePoint:completion:)], - @"FCPCameraApi api (%@) doesn't respond to @selector(setExposurePoint:completion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - NSArray *args = message; - FCPPlatformPoint *arg_point = GetNullableObjectAtIndex(args, 0); - [api setExposurePoint:arg_point - completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Returns the minimum exposure offset supported by the camera. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString stringWithFormat:@"%@%@", - @"dev.flutter.pigeon.camera_avfoundation." - @"CameraApi.getMinExposureOffset", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert([api respondsToSelector:@selector(getMinimumExposureOffset:)], - @"FCPCameraApi api (%@) doesn't respond to @selector(getMinimumExposureOffset:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api getMinimumExposureOffset:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { - callback(wrapResult(output, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Returns the maximum exposure offset supported by the camera. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString stringWithFormat:@"%@%@", - @"dev.flutter.pigeon.camera_avfoundation." - @"CameraApi.getMaxExposureOffset", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert([api respondsToSelector:@selector(getMaximumExposureOffset:)], - @"FCPCameraApi api (%@) doesn't respond to @selector(getMaximumExposureOffset:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api getMaximumExposureOffset:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { - callback(wrapResult(output, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Sets the exposure offset manually to the given value. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString stringWithFormat:@"%@%@", - @"dev.flutter.pigeon.camera_avfoundation." - @"CameraApi.setExposureOffset", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert( - [api respondsToSelector:@selector(setExposureOffset:completion:)], - @"FCPCameraApi api (%@) doesn't respond to @selector(setExposureOffset:completion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - NSArray *args = message; - double arg_offset = [GetNullableObjectAtIndex(args, 0) doubleValue]; - [api setExposureOffset:arg_offset - completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Switches the camera to the given focus mode. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString - stringWithFormat: - @"%@%@", - @"dev.flutter.pigeon.camera_avfoundation.CameraApi.setFocusMode", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert([api respondsToSelector:@selector(setFocusMode:completion:)], - @"FCPCameraApi api (%@) doesn't respond to @selector(setFocusMode:completion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - NSArray *args = message; - FCPPlatformFocusModeBox *boxedFCPPlatformFocusMode = GetNullableObjectAtIndex(args, 0); - FCPPlatformFocusMode arg_mode = boxedFCPPlatformFocusMode.value; - [api setFocusMode:arg_mode - completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Anchors auto-focus to the given point in (0,1) coordinate space. - /// - /// A null value resets to the default focus point. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString - stringWithFormat: - @"%@%@", - @"dev.flutter.pigeon.camera_avfoundation.CameraApi.setFocusPoint", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert([api respondsToSelector:@selector(setFocusPoint:completion:)], - @"FCPCameraApi api (%@) doesn't respond to @selector(setFocusPoint:completion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - NSArray *args = message; - FCPPlatformPoint *arg_point = GetNullableObjectAtIndex(args, 0); - [api setFocusPoint:arg_point - completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Returns the minimum zoom level supported by the camera. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString - stringWithFormat: - @"%@%@", - @"dev.flutter.pigeon.camera_avfoundation.CameraApi.getMinZoomLevel", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert([api respondsToSelector:@selector(getMinimumZoomLevel:)], - @"FCPCameraApi api (%@) doesn't respond to @selector(getMinimumZoomLevel:)", api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api getMinimumZoomLevel:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { - callback(wrapResult(output, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Returns the maximum zoom level supported by the camera. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString - stringWithFormat: - @"%@%@", - @"dev.flutter.pigeon.camera_avfoundation.CameraApi.getMaxZoomLevel", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert([api respondsToSelector:@selector(getMaximumZoomLevel:)], - @"FCPCameraApi api (%@) doesn't respond to @selector(getMaximumZoomLevel:)", api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api getMaximumZoomLevel:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { - callback(wrapResult(output, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Sets the zoom factor. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString - stringWithFormat: - @"%@%@", - @"dev.flutter.pigeon.camera_avfoundation.CameraApi.setZoomLevel", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert([api respondsToSelector:@selector(setZoomLevel:completion:)], - @"FCPCameraApi api (%@) doesn't respond to @selector(setZoomLevel:completion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - NSArray *args = message; - double arg_zoom = [GetNullableObjectAtIndex(args, 0) doubleValue]; - [api setZoomLevel:arg_zoom - completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Pauses streaming of preview frames. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString - stringWithFormat: - @"%@%@", - @"dev.flutter.pigeon.camera_avfoundation.CameraApi.pausePreview", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert([api respondsToSelector:@selector(pausePreviewWithCompletion:)], - @"FCPCameraApi api (%@) doesn't respond to @selector(pausePreviewWithCompletion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api pausePreviewWithCompletion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Resumes a previously paused preview stream. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString - stringWithFormat: - @"%@%@", - @"dev.flutter.pigeon.camera_avfoundation.CameraApi.resumePreview", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert([api respondsToSelector:@selector(resumePreviewWithCompletion:)], - @"FCPCameraApi api (%@) doesn't respond to @selector(resumePreviewWithCompletion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - [api resumePreviewWithCompletion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Changes the camera used while recording video. - /// - /// This should only be called while video recording is active. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString stringWithFormat:@"%@%@", - @"dev.flutter.pigeon.camera_avfoundation." - @"CameraApi.updateDescriptionWhileRecording", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert([api respondsToSelector:@selector(updateDescriptionWhileRecordingCameraName: - completion:)], - @"FCPCameraApi api (%@) doesn't respond to " - @"@selector(updateDescriptionWhileRecordingCameraName:completion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - NSArray *args = message; - NSString *arg_cameraName = GetNullableObjectAtIndex(args, 0); - [api updateDescriptionWhileRecordingCameraName:arg_cameraName - completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } - /// Sets the file format used for taking pictures. - { - FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] - initWithName:[NSString stringWithFormat:@"%@%@", - @"dev.flutter.pigeon.camera_avfoundation." - @"CameraApi.setImageFileFormat", - messageChannelSuffix] - binaryMessenger:binaryMessenger - codec:FCPGetMessagesCodec()]; - if (api) { - NSCAssert( - [api respondsToSelector:@selector(setImageFileFormat:completion:)], - @"FCPCameraApi api (%@) doesn't respond to @selector(setImageFileFormat:completion:)", - api); - [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { - NSArray *args = message; - FCPPlatformImageFileFormatBox *boxedFCPPlatformImageFileFormat = - GetNullableObjectAtIndex(args, 0); - FCPPlatformImageFileFormat arg_format = boxedFCPPlatformImageFileFormat.value; - [api setImageFileFormat:arg_format - completion:^(FlutterError *_Nullable error) { - callback(wrapResult(nil, error)); - }]; - }]; - } else { - [channel setMessageHandler:nil]; - } - } -} -@interface FCPCameraGlobalEventApi () -@property(nonatomic, strong) NSObject *binaryMessenger; -@property(nonatomic, strong) NSString *messageChannelSuffix; -@end - -@implementation FCPCameraGlobalEventApi - -- (instancetype)initWithBinaryMessenger:(NSObject *)binaryMessenger { - return [self initWithBinaryMessenger:binaryMessenger messageChannelSuffix:@""]; -} -- (instancetype)initWithBinaryMessenger:(NSObject *)binaryMessenger - messageChannelSuffix:(nullable NSString *)messageChannelSuffix { - self = [self init]; - if (self) { - _binaryMessenger = binaryMessenger; - _messageChannelSuffix = [messageChannelSuffix length] == 0 - ? @"" - : [NSString stringWithFormat:@".%@", messageChannelSuffix]; - } - return self; -} -- (void)deviceOrientationChangedOrientation:(FCPPlatformDeviceOrientation)arg_orientation - completion:(void (^)(FlutterError *_Nullable))completion { - NSString *channelName = [NSString - stringWithFormat: - @"%@%@", - @"dev.flutter.pigeon.camera_avfoundation.CameraGlobalEventApi.deviceOrientationChanged", - _messageChannelSuffix]; - FlutterBasicMessageChannel *channel = - [FlutterBasicMessageChannel messageChannelWithName:channelName - binaryMessenger:self.binaryMessenger - codec:FCPGetMessagesCodec()]; - [channel sendMessage:@[ [[FCPPlatformDeviceOrientationBox alloc] initWithValue:arg_orientation] ] - reply:^(NSArray *reply) { - if (reply != nil) { - if (reply.count > 1) { - completion([FlutterError errorWithCode:reply[0] - message:reply[1] - details:reply[2]]); - } else { - completion(nil); - } - } else { - completion(createConnectionError(channelName)); - } - }]; -} -@end - -@interface FCPCameraEventApi () -@property(nonatomic, strong) NSObject *binaryMessenger; -@property(nonatomic, strong) NSString *messageChannelSuffix; -@end - -@implementation FCPCameraEventApi - -- (instancetype)initWithBinaryMessenger:(NSObject *)binaryMessenger { - return [self initWithBinaryMessenger:binaryMessenger messageChannelSuffix:@""]; -} -- (instancetype)initWithBinaryMessenger:(NSObject *)binaryMessenger - messageChannelSuffix:(nullable NSString *)messageChannelSuffix { - self = [self init]; - if (self) { - _binaryMessenger = binaryMessenger; - _messageChannelSuffix = [messageChannelSuffix length] == 0 - ? @"" - : [NSString stringWithFormat:@".%@", messageChannelSuffix]; - } - return self; -} -- (void)initializedWithState:(FCPPlatformCameraState *)arg_initialState - completion:(void (^)(FlutterError *_Nullable))completion { - NSString *channelName = [NSString - stringWithFormat:@"%@%@", - @"dev.flutter.pigeon.camera_avfoundation.CameraEventApi.initialized", - _messageChannelSuffix]; - FlutterBasicMessageChannel *channel = - [FlutterBasicMessageChannel messageChannelWithName:channelName - binaryMessenger:self.binaryMessenger - codec:FCPGetMessagesCodec()]; - [channel sendMessage:@[ arg_initialState ?: [NSNull null] ] - reply:^(NSArray *reply) { - if (reply != nil) { - if (reply.count > 1) { - completion([FlutterError errorWithCode:reply[0] - message:reply[1] - details:reply[2]]); - } else { - completion(nil); - } - } else { - completion(createConnectionError(channelName)); - } - }]; -} -- (void)reportError:(NSString *)arg_message - completion:(void (^)(FlutterError *_Nullable))completion { - NSString *channelName = [NSString - stringWithFormat:@"%@%@", @"dev.flutter.pigeon.camera_avfoundation.CameraEventApi.error", - _messageChannelSuffix]; - FlutterBasicMessageChannel *channel = - [FlutterBasicMessageChannel messageChannelWithName:channelName - binaryMessenger:self.binaryMessenger - codec:FCPGetMessagesCodec()]; - [channel sendMessage:@[ arg_message ?: [NSNull null] ] - reply:^(NSArray *reply) { - if (reply != nil) { - if (reply.count > 1) { - completion([FlutterError errorWithCode:reply[0] - message:reply[1] - details:reply[2]]); - } else { - completion(nil); - } - } else { - completion(createConnectionError(channelName)); - } - }]; -} -@end diff --git a/packages/camera/camera_avfoundation/lib/src/avfoundation_camera.dart b/packages/camera/camera_avfoundation/lib/src/avfoundation_camera.dart index 188062f99706..3907ed89219b 100644 --- a/packages/camera/camera_avfoundation/lib/src/avfoundation_camera.dart +++ b/packages/camera/camera_avfoundation/lib/src/avfoundation_camera.dart @@ -118,7 +118,7 @@ class AVFoundationCamera extends CameraPlatform { () => HostCameraMessageHandler(cameraId, cameraEventStreamController), ); - final Completer completer = Completer(); + final completer = Completer(); unawaited( onCameraInitialized(cameraId).first.then((CameraInitializedEvent value) { @@ -274,21 +274,16 @@ class AVFoundationCamera extends CameraPlatform { } void _startStreamListener() { - const EventChannel cameraEventChannel = EventChannel( - 'plugins.flutter.io/camera_avfoundation/imageStream', - ); - _platformImageStreamSubscription = cameraEventChannel - .receiveBroadcastStream() - .listen((dynamic imageData) { - try { - _hostApi.receivedImageStreamData(); - } on PlatformException catch (e) { - throw CameraException(e.code, e.message); - } - _frameStreamController!.add( - cameraImageFromPlatformData(imageData as Map), - ); - }); + _platformImageStreamSubscription = imageDataStream().listen(( + PlatformCameraImageData imageData, + ) { + try { + _hostApi.receivedImageStreamData(); + } on PlatformException catch (e) { + throw CameraException(e.code, e.message); + } + _frameStreamController!.add(cameraImageFromPlatformData(imageData)); + }); } FutureOr _onFrameStreamCancel() async { @@ -380,6 +375,51 @@ class AVFoundationCamera extends CameraPlatform { } } + @override + Future setVideoStabilizationMode( + int cameraId, + VideoStabilizationMode mode, + ) async { + try { + final Map + availableModes = await _getSupportedVideoStabilizationModeMap(cameraId); + + final PlatformVideoStabilizationMode? platformMode = availableModes[mode]; + if (platformMode == null) { + throw ArgumentError('Unavailable video stabilization mode.', 'mode'); + } + await _hostApi.setVideoStabilizationMode(platformMode); + } on PlatformException catch (e) { + throw CameraException(e.code, e.message); + } + } + + @override + Future> getSupportedVideoStabilizationModes( + int cameraId, + ) async { + return (await _getSupportedVideoStabilizationModeMap(cameraId)).keys; + } + + Future> + _getSupportedVideoStabilizationModeMap(int cameraId) async { + final ret = {}; + + for (final VideoStabilizationMode mode in VideoStabilizationMode.values) { + final PlatformVideoStabilizationMode? platformMode = + _pigeonVideoStabilizationMode(mode); + if (platformMode != null) { + final bool isSupported = await _hostApi + .isVideoStabilizationModeSupported(platformMode); + if (isSupported) { + ret[mode] = platformMode; + } + } + } + + return ret; + } + @override Future pausePreview(int cameraId) async { await _hostApi.pausePreview(); @@ -494,6 +534,29 @@ class AVFoundationCamera extends CameraPlatform { return PlatformResolutionPreset.max; } + /// Returns a [VideoStabilizationMode]'s Pigeon representation. + PlatformVideoStabilizationMode? _pigeonVideoStabilizationMode( + VideoStabilizationMode videoStabilizationMode, + ) { + switch (videoStabilizationMode) { + case VideoStabilizationMode.off: + return PlatformVideoStabilizationMode.off; + case VideoStabilizationMode.level1: + return PlatformVideoStabilizationMode.standard; + case VideoStabilizationMode.level2: + return PlatformVideoStabilizationMode.cinematic; + case VideoStabilizationMode.level3: + return PlatformVideoStabilizationMode.cinematicExtended; + } + // The enum comes from a different package, which could get a new value at + // any time, so provide a fallback that ensures this won't break when used + // with a version that contains new values. This is deliberately outside + // the switch rather than a `default` so that the linter will flag the + // switch as needing an update. + // ignore: dead_code + return null; + } + /// Returns an [ImageFormatGroup]'s Pigeon representation. PlatformImageFormatGroup _pigeonImageFormat(ImageFormatGroup format) { switch (format) { diff --git a/packages/camera/camera_avfoundation/lib/src/messages.g.dart b/packages/camera/camera_avfoundation/lib/src/messages.g.dart index fd25e3be8bad..46c94d58f8a1 100644 --- a/packages/camera/camera_avfoundation/lib/src/messages.g.dart +++ b/packages/camera/camera_avfoundation/lib/src/messages.g.dart @@ -1,9 +1,9 @@ // Copyright 2013 The Flutter Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// Autogenerated from Pigeon (v26.1.0), do not edit directly. +// Autogenerated from Pigeon (v26.1.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, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import, no_leading_underscores_for_local_identifiers +// 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, omit_obvious_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; @@ -95,6 +95,13 @@ enum PlatformImageFormatGroup { bgra8888, yuv420 } enum PlatformResolutionPreset { low, medium, high, veryHigh, ultraHigh, max } +enum PlatformVideoStabilizationMode { + off, + standard, + cinematic, + cinematicExtended, +} + class PlatformCameraDescription { PlatformCameraDescription({ required this.name, @@ -212,6 +219,130 @@ class PlatformCameraState { int get hashCode => Object.hashAll(_toList()); } +class PlatformCameraImageData { + PlatformCameraImageData({ + required this.formatCode, + required this.width, + required this.height, + required this.planes, + required this.lensAperture, + required this.sensorExposureTimeNanoseconds, + required this.sensorSensitivity, + }); + + /// The FourCharCode of the image format. + int formatCode; + + int width; + + int height; + + List planes; + + double lensAperture; + + int sensorExposureTimeNanoseconds; + + double sensorSensitivity; + + List _toList() { + return [ + formatCode, + width, + height, + planes, + lensAperture, + sensorExposureTimeNanoseconds, + sensorSensitivity, + ]; + } + + Object encode() { + return _toList(); + } + + static PlatformCameraImageData decode(Object result) { + result as List; + return PlatformCameraImageData( + formatCode: result[0]! as int, + width: result[1]! as int, + height: result[2]! as int, + planes: (result[3] as List?)!.cast(), + lensAperture: result[4]! as double, + sensorExposureTimeNanoseconds: result[5]! as int, + sensorSensitivity: result[6]! as double, + ); + } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + bool operator ==(Object other) { + if (other is! PlatformCameraImageData || other.runtimeType != runtimeType) { + return false; + } + if (identical(this, other)) { + return true; + } + return _deepEquals(encode(), other.encode()); + } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + int get hashCode => Object.hashAll(_toList()); +} + +class PlatformCameraImagePlane { + PlatformCameraImagePlane({ + required this.bytes, + required this.bytesPerRow, + required this.width, + required this.height, + }); + + Uint8List bytes; + + int bytesPerRow; + + int width; + + int height; + + List _toList() { + return [bytes, bytesPerRow, width, height]; + } + + Object encode() { + return _toList(); + } + + static PlatformCameraImagePlane decode(Object result) { + result as List; + return PlatformCameraImagePlane( + bytes: result[0]! as Uint8List, + bytesPerRow: result[1]! as int, + width: result[2]! as int, + height: result[3]! as int, + ); + } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + bool operator ==(Object other) { + if (other is! PlatformCameraImagePlane || + other.runtimeType != runtimeType) { + return false; + } + if (identical(this, other)) { + return true; + } + return _deepEquals(encode(), other.encode()); + } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + int get hashCode => Object.hashAll(_toList()); +} + class PlatformMediaSettings { PlatformMediaSettings({ required this.resolutionPreset, @@ -384,20 +515,29 @@ class _PigeonCodec extends StandardMessageCodec { } else if (value is PlatformResolutionPreset) { buffer.putUint8(137); writeValue(buffer, value.index); - } else if (value is PlatformCameraDescription) { + } else if (value is PlatformVideoStabilizationMode) { buffer.putUint8(138); + writeValue(buffer, value.index); + } else if (value is PlatformCameraDescription) { + buffer.putUint8(139); writeValue(buffer, value.encode()); } else if (value is PlatformCameraState) { - buffer.putUint8(139); + buffer.putUint8(140); + writeValue(buffer, value.encode()); + } else if (value is PlatformCameraImageData) { + buffer.putUint8(141); + writeValue(buffer, value.encode()); + } else if (value is PlatformCameraImagePlane) { + buffer.putUint8(142); writeValue(buffer, value.encode()); } else if (value is PlatformMediaSettings) { - buffer.putUint8(140); + buffer.putUint8(143); writeValue(buffer, value.encode()); } else if (value is PlatformPoint) { - buffer.putUint8(141); + buffer.putUint8(144); writeValue(buffer, value.encode()); } else if (value is PlatformSize) { - buffer.putUint8(142); + buffer.putUint8(145); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); @@ -408,41 +548,50 @@ class _PigeonCodec extends StandardMessageCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 129: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : PlatformCameraLensDirection.values[value]; case 130: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : PlatformCameraLensType.values[value]; case 131: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : PlatformDeviceOrientation.values[value]; case 132: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : PlatformExposureMode.values[value]; case 133: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : PlatformFlashMode.values[value]; case 134: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : PlatformFocusMode.values[value]; case 135: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : PlatformImageFileFormat.values[value]; case 136: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : PlatformImageFormatGroup.values[value]; case 137: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : PlatformResolutionPreset.values[value]; case 138: - return PlatformCameraDescription.decode(readValue(buffer)!); + final value = readValue(buffer) as int?; + return value == null + ? null + : PlatformVideoStabilizationMode.values[value]; case 139: - return PlatformCameraState.decode(readValue(buffer)!); + return PlatformCameraDescription.decode(readValue(buffer)!); case 140: - return PlatformMediaSettings.decode(readValue(buffer)!); + return PlatformCameraState.decode(readValue(buffer)!); case 141: - return PlatformPoint.decode(readValue(buffer)!); + return PlatformCameraImageData.decode(readValue(buffer)!); case 142: + return PlatformCameraImagePlane.decode(readValue(buffer)!); + case 143: + return PlatformMediaSettings.decode(readValue(buffer)!); + case 144: + return PlatformPoint.decode(readValue(buffer)!); + case 145: return PlatformSize.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); @@ -450,6 +599,10 @@ class _PigeonCodec extends StandardMessageCodec { } } +const StandardMethodCodec pigeonMethodCodec = StandardMethodCodec( + _PigeonCodec(), +); + class CameraApi { /// Constructor for [CameraApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default @@ -469,17 +622,15 @@ class CameraApi { /// Returns the list of available cameras. Future> getAvailableCameras() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.getAvailableCameras$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -501,19 +652,17 @@ class CameraApi { /// Create a new camera with the given settings, and returns its ID. Future create(String cameraName, PlatformMediaSettings settings) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.create$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [cameraName, settings], ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -537,19 +686,17 @@ class CameraApi { int cameraId, PlatformImageFormatGroup imageFormat, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.initialize$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [cameraId, imageFormat], ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -565,17 +712,15 @@ class CameraApi { /// Begins streaming frames from the camera. Future startImageStream() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.startImageStream$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -591,17 +736,15 @@ class CameraApi { /// Stops streaming frames from the camera. Future stopImageStream() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.stopImageStream$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -620,17 +763,15 @@ class CameraApi { /// /// This is used to throttle sending frames across the channel. Future receivedImageStreamData() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.receivedImageStreamData$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -647,19 +788,17 @@ class CameraApi { /// Indicates that the given camera is no longer being used on the Dart side, /// and any associated resources can be cleaned up. Future dispose(int cameraId) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.dispose$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [cameraId], ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -677,19 +816,17 @@ class CameraApi { Future lockCaptureOrientation( PlatformDeviceOrientation orientation, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.lockCaptureOrientation$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [orientation], ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -706,17 +843,15 @@ class CameraApi { /// Unlocks camera capture orientation, allowing it to automatically adapt to /// device orientation. Future unlockCaptureOrientation() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.unlockCaptureOrientation$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -733,17 +868,15 @@ class CameraApi { /// Takes a picture with the current settings, and returns the path to the /// resulting file. Future takePicture() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.takePicture$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -764,17 +897,15 @@ class CameraApi { /// Does any preprocessing necessary before beginning to record video. Future prepareForVideoRecording() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.prepareForVideoRecording$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -791,19 +922,17 @@ class CameraApi { /// Begins recording video, optionally enabling streaming to Dart at the same /// time. Future startVideoRecording(bool enableStream) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.startVideoRecording$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [enableStream], ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -819,17 +948,15 @@ class CameraApi { /// Stops recording video, and results the path to the resulting file. Future stopVideoRecording() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.stopVideoRecording$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -850,17 +977,15 @@ class CameraApi { /// Pauses video recording. Future pauseVideoRecording() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.pauseVideoRecording$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -876,17 +1001,15 @@ class CameraApi { /// Resumes a previously paused video recording. Future resumeVideoRecording() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.resumeVideoRecording$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -902,19 +1025,17 @@ class CameraApi { /// Switches the camera to the given flash mode. Future setFlashMode(PlatformFlashMode mode) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.setFlashMode$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [mode], ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -930,19 +1051,17 @@ class CameraApi { /// Switches the camera to the given exposure mode. Future setExposureMode(PlatformExposureMode mode) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.setExposureMode$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [mode], ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -960,19 +1079,17 @@ class CameraApi { /// /// A null value resets to the default exposure point. Future setExposurePoint(PlatformPoint? point) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.setExposurePoint$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [point], ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -988,17 +1105,15 @@ class CameraApi { /// Returns the minimum exposure offset supported by the camera. Future getMinExposureOffset() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.getMinExposureOffset$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1019,17 +1134,15 @@ class CameraApi { /// Returns the maximum exposure offset supported by the camera. Future getMaxExposureOffset() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.getMaxExposureOffset$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1050,19 +1163,17 @@ class CameraApi { /// Sets the exposure offset manually to the given value. Future setExposureOffset(double offset) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.setExposureOffset$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [offset], ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1078,19 +1189,17 @@ class CameraApi { /// Switches the camera to the given focus mode. Future setFocusMode(PlatformFocusMode mode) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.setFocusMode$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [mode], ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1108,19 +1217,17 @@ class CameraApi { /// /// A null value resets to the default focus point. Future setFocusPoint(PlatformPoint? point) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.setFocusPoint$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [point], ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1136,17 +1243,15 @@ class CameraApi { /// Returns the minimum zoom level supported by the camera. Future getMinZoomLevel() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.getMinZoomLevel$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1167,17 +1272,15 @@ class CameraApi { /// Returns the maximum zoom level supported by the camera. Future getMaxZoomLevel() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.getMaxZoomLevel$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1198,19 +1301,45 @@ class CameraApi { /// Sets the zoom factor. Future setZoomLevel(double zoom) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.setZoomLevel$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [zoom], ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final 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; + } + } + + /// Sets the video stabilization mode. + Future setVideoStabilizationMode( + PlatformVideoStabilizationMode mode, + ) async { + final pigeonVar_channelName = + 'dev.flutter.pigeon.camera_avfoundation.CameraApi.setVideoStabilizationMode$pigeonVar_messageChannelSuffix'; + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [mode], + ); + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1224,19 +1353,50 @@ class CameraApi { } } + /// Gets if the given video stabilization mode is supported. + Future isVideoStabilizationModeSupported( + PlatformVideoStabilizationMode mode, + ) async { + final pigeonVar_channelName = + 'dev.flutter.pigeon.camera_avfoundation.CameraApi.isVideoStabilizationModeSupported$pigeonVar_messageChannelSuffix'; + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [mode], + ); + final 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?)!; + } + } + /// Pauses streaming of preview frames. Future pausePreview() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.pausePreview$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1252,17 +1412,15 @@ class CameraApi { /// Resumes a previously paused preview stream. Future resumePreview() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.resumePreview$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1280,19 +1438,17 @@ class CameraApi { /// /// This should only be called while video recording is active. Future updateDescriptionWhileRecording(String cameraName) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.updateDescriptionWhileRecording$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [cameraName], ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1308,19 +1464,17 @@ class CameraApi { /// Sets the file format used for taking pictures. Future setImageFileFormat(PlatformImageFileFormat format) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.camera_avfoundation.CameraApi.setImageFileFormat$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [format], ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { @@ -1335,6 +1489,19 @@ class CameraApi { } } +Stream imageDataStream({String instanceName = ''}) { + if (instanceName.isNotEmpty) { + instanceName = '.$instanceName'; + } + final EventChannel imageDataStreamChannel = EventChannel( + 'dev.flutter.pigeon.camera_avfoundation.CameraImageStreamEventApi.imageDataStream$instanceName', + pigeonMethodCodec, + ); + return imageDataStreamChannel.receiveBroadcastStream().map((dynamic event) { + return event as PlatformCameraImageData; + }); +} + /// Handler for native callbacks that are not tied to a specific camera ID. abstract class CameraGlobalEventApi { static const MessageCodec pigeonChannelCodec = _PigeonCodec(); @@ -1351,8 +1518,7 @@ abstract class CameraGlobalEventApi { ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_avfoundation.CameraGlobalEventApi.deviceOrientationChanged$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -1412,8 +1578,7 @@ abstract class CameraEventApi { ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_avfoundation.CameraEventApi.initialized$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -1447,8 +1612,7 @@ abstract class CameraEventApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.camera_avfoundation.CameraEventApi.error$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, diff --git a/packages/camera/camera_avfoundation/lib/src/type_conversion.dart b/packages/camera/camera_avfoundation/lib/src/type_conversion.dart index c79e9eaa6c93..7753f054b007 100644 --- a/packages/camera/camera_avfoundation/lib/src/type_conversion.dart +++ b/packages/camera/camera_avfoundation/lib/src/type_conversion.dart @@ -2,35 +2,37 @@ // 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_platform_interface/camera_platform_interface.dart'; +import 'messages.g.dart'; + /// Converts method channel call [data] for `receivedImageStreamData` to a /// [CameraImageData]. -CameraImageData cameraImageFromPlatformData(Map data) { +CameraImageData cameraImageFromPlatformData(PlatformCameraImageData data) { return CameraImageData( - format: _cameraImageFormatFromPlatformData(data['format']), - height: data['height'] as int, - width: data['width'] as int, - lensAperture: data['lensAperture'] as double?, - sensorExposureTime: data['sensorExposureTime'] as int?, - sensorSensitivity: data['sensorSensitivity'] as double?, + format: _cameraImageFormatFromPlatformImageFormat(data.formatCode), + width: data.width, + height: data.height, + lensAperture: data.lensAperture, + sensorExposureTime: data.sensorExposureTimeNanoseconds, + sensorSensitivity: data.sensorSensitivity, planes: List.unmodifiable( - (data['planes'] as List).map( - (dynamic planeData) => _cameraImagePlaneFromPlatformData( - planeData as Map, - ), + data.planes.map( + (PlatformCameraImagePlane planeData) => + _cameraImagePlaneFromPlatformData(planeData), ), ), ); } -CameraImageFormat _cameraImageFormatFromPlatformData(dynamic data) { - return CameraImageFormat(_imageFormatGroupFromPlatformData(data), raw: data); +CameraImageFormat _cameraImageFormatFromPlatformImageFormat(int data) { + return CameraImageFormat( + _imageFormatGroupFromPlatformImageFormat(data), + raw: data, + ); } -ImageFormatGroup _imageFormatGroupFromPlatformData(dynamic data) { +ImageFormatGroup _imageFormatGroupFromPlatformImageFormat(int data) { switch (data) { case 875704438: // kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange return ImageFormatGroup.yuv420; @@ -42,12 +44,13 @@ ImageFormatGroup _imageFormatGroupFromPlatformData(dynamic data) { return ImageFormatGroup.unknown; } -CameraImagePlane _cameraImagePlaneFromPlatformData(Map data) { +CameraImagePlane _cameraImagePlaneFromPlatformData( + PlatformCameraImagePlane data, +) { return CameraImagePlane( - bytes: data['bytes'] as Uint8List, - bytesPerPixel: data['bytesPerPixel'] as int?, - bytesPerRow: data['bytesPerRow'] as int, - height: data['height'] as int?, - width: data['width'] as int?, + bytes: data.bytes, + bytesPerRow: data.bytesPerRow, + width: data.width, + height: data.height, ); } diff --git a/packages/camera/camera_avfoundation/pigeons/messages.dart b/packages/camera/camera_avfoundation/pigeons/messages.dart index f4bdd8d998da..b4976758cf47 100644 --- a/packages/camera/camera_avfoundation/pigeons/messages.dart +++ b/packages/camera/camera_avfoundation/pigeons/messages.dart @@ -7,14 +7,8 @@ import 'package:pigeon/pigeon.dart'; @ConfigurePigeon( PigeonOptions( dartOut: 'lib/src/messages.g.dart', - objcHeaderOut: - 'ios/camera_avfoundation/Sources/camera_avfoundation_objc/include/camera_avfoundation/messages.g.h', - objcSourceOut: - 'ios/camera_avfoundation/Sources/camera_avfoundation_objc/messages.g.m', - objcOptions: ObjcOptions( - prefix: 'FCP', - headerIncludePath: './include/camera_avfoundation/messages.g.h', - ), + swiftOut: + 'ios/camera_avfoundation/Sources/camera_avfoundation/Messages.swift', copyrightHeader: 'pigeons/copyright.txt', ), ) @@ -71,6 +65,13 @@ enum PlatformImageFormatGroup { bgra8888, yuv420 } // Pigeon version of ResolutionPreset. enum PlatformResolutionPreset { low, medium, high, veryHigh, ultraHigh, max } +enum PlatformVideoStabilizationMode { + off, + standard, + cinematic, + cinematicExtended, +} + // Pigeon version of CameraDescription. class PlatformCameraDescription { PlatformCameraDescription({ @@ -115,6 +116,44 @@ class PlatformCameraState { final bool focusPointSupported; } +// Pigeon version of the data needed for a CameraImageData. +class PlatformCameraImageData { + PlatformCameraImageData({ + required this.formatCode, + required this.width, + required this.height, + required this.planes, + required this.lensAperture, + required this.sensorExposureTimeNanoseconds, + required this.sensorSensitivity, + }); + + /// The FourCharCode of the image format. + final int formatCode; + + final int width; + final int height; + final List planes; + final double lensAperture; + final int sensorExposureTimeNanoseconds; + final double sensorSensitivity; +} + +// Pigeon version of the data needed for a CameraImagePlane. +class PlatformCameraImagePlane { + const PlatformCameraImagePlane({ + required this.bytes, + required this.bytesPerRow, + required this.width, + required this.height, + }); + + final Uint8List bytes; + final int bytesPerRow; + final int width; + final int height; +} + // Pigeon version of to MediaSettings. class PlatformMediaSettings { PlatformMediaSettings({ @@ -151,9 +190,6 @@ class PlatformSize { @HostApi() abstract class CameraApi { /// Returns the list of available cameras. - // TODO(stuartmorgan): Make the generic type non-nullable once supported. - // https://github.com/flutter/flutter/issues/97848 - // The consuming code treats it as non-nullable. @async @ObjCSelector('availableCamerasWithCompletion') List getAvailableCameras(); @@ -285,6 +321,16 @@ abstract class CameraApi { @ObjCSelector('setZoomLevel:') void setZoomLevel(double zoom); + /// Sets the video stabilization mode. + @async + @ObjCSelector('setVideoStabilizationMode:') + void setVideoStabilizationMode(PlatformVideoStabilizationMode mode); + + /// Gets if the given video stabilization mode is supported. + @async + @ObjCSelector('isVideoStabilizationModeSupported:') + bool isVideoStabilizationModeSupported(PlatformVideoStabilizationMode mode); + /// Pauses streaming of preview frames. @async void pausePreview(); @@ -305,6 +351,11 @@ abstract class CameraApi { void setImageFileFormat(PlatformImageFileFormat format); } +@EventChannelApi() +abstract class CameraImageStreamEventApi { + PlatformCameraImageData imageDataStream(); +} + /// Handler for native callbacks that are not tied to a specific camera ID. @FlutterApi() abstract class CameraGlobalEventApi { diff --git a/packages/camera/camera_avfoundation/pubspec.yaml b/packages/camera/camera_avfoundation/pubspec.yaml index dd391e086cb7..8a10d0d21f72 100644 --- a/packages/camera/camera_avfoundation/pubspec.yaml +++ b/packages/camera/camera_avfoundation/pubspec.yaml @@ -2,7 +2,7 @@ name: camera_avfoundation description: iOS implementation of the camera plugin. repository: https://github.com/flutter/packages/tree/main/packages/camera/camera_avfoundation issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+camera%22 -version: 0.9.22+6 +version: 0.10.1 environment: sdk: ^3.9.0 @@ -17,7 +17,7 @@ flutter: dartPluginClass: AVFoundationCamera dependencies: - camera_platform_interface: ^2.10.0 + camera_platform_interface: ^2.12.0 flutter: sdk: flutter stream_transform: ^2.0.0 @@ -29,7 +29,7 @@ dev_dependencies: sdk: flutter leak_tracker_flutter_testing: any mockito: ^5.4.4 - pigeon: ^26.1.0 + pigeon: ^26.1.5 topics: - camera diff --git a/packages/camera/camera_avfoundation/test/avfoundation_camera_test.dart b/packages/camera/camera_avfoundation/test/avfoundation_camera_test.dart index ec31faf9c276..53d7965c6bac 100644 --- a/packages/camera/camera_avfoundation/test/avfoundation_camera_test.dart +++ b/packages/camera/camera_avfoundation/test/avfoundation_camera_test.dart @@ -30,10 +30,10 @@ void main() { group('Creation, Initialization & Disposal Tests', () { test('Should send creation data and receive back a camera id', () async { // Arrange - final MockCameraApi mockApi = MockCameraApi(); + final mockApi = MockCameraApi(); when(mockApi.create(any, any)).thenAnswer((_) async => 1); - final AVFoundationCamera camera = AVFoundationCamera(api: mockApi); - const String cameraName = 'Test'; + final camera = AVFoundationCamera(api: mockApi); + const cameraName = 'Test'; // Act final int cameraId = await camera.createCamera( @@ -50,8 +50,7 @@ void main() { mockApi.create(captureAny, captureAny), ); expect(verification.captured[0], cameraName); - final PlatformMediaSettings? settings = - verification.captured[1] as PlatformMediaSettings?; + final settings = verification.captured[1] as PlatformMediaSettings?; expect(settings, isNotNull); expect(settings?.resolutionPreset, PlatformResolutionPreset.high); expect(cameraId, 1); @@ -61,13 +60,13 @@ void main() { 'Should send creation data and receive back a camera id using createCameraWithSettings', () async { // Arrange - final MockCameraApi mockApi = MockCameraApi(); + final mockApi = MockCameraApi(); when(mockApi.create(any, any)).thenAnswer((_) async => 1); - final AVFoundationCamera camera = AVFoundationCamera(api: mockApi); - const String cameraName = 'Test'; - const int fps = 15; - const int videoBitrate = 200000; - const int audioBitrate = 32000; + final camera = AVFoundationCamera(api: mockApi); + const cameraName = 'Test'; + const fps = 15; + const videoBitrate = 200000; + const audioBitrate = 32000; // Act final int cameraId = await camera.createCameraWithSettings( @@ -90,8 +89,7 @@ void main() { mockApi.create(captureAny, captureAny), ); expect(verification.captured[0], cameraName); - final PlatformMediaSettings? settings = - verification.captured[1] as PlatformMediaSettings?; + final settings = verification.captured[1] as PlatformMediaSettings?; expect(settings, isNotNull); expect(settings?.resolutionPreset, PlatformResolutionPreset.low); expect(settings?.framesPerSecond, fps); @@ -106,17 +104,16 @@ void main() { 'Should throw CameraException when create throws a PlatformException', () { // Arrange - const String exceptionCode = 'TESTING_ERROR_CODE'; - const String exceptionMessage = - 'Mock error message used during testing.'; - final MockCameraApi mockApi = MockCameraApi(); + const exceptionCode = 'TESTING_ERROR_CODE'; + const exceptionMessage = 'Mock error message used during testing.'; + final mockApi = MockCameraApi(); when(mockApi.create(any, any)).thenAnswer((_) async { throw PlatformException( code: exceptionCode, message: exceptionMessage, ); }); - final AVFoundationCamera camera = AVFoundationCamera(api: mockApi); + final camera = AVFoundationCamera(api: mockApi); // Act expect( @@ -145,17 +142,16 @@ void main() { 'Should throw CameraException when initialize throws a PlatformException', () { // Arrange - const String exceptionCode = 'TESTING_ERROR_CODE'; - const String exceptionMessage = - 'Mock error message used during testing.'; - final MockCameraApi mockApi = MockCameraApi(); + const exceptionCode = 'TESTING_ERROR_CODE'; + const exceptionMessage = 'Mock error message used during testing.'; + final mockApi = MockCameraApi(); when(mockApi.initialize(any, any)).thenAnswer((_) async { throw PlatformException( code: exceptionCode, message: exceptionMessage, ); }); - final AVFoundationCamera camera = AVFoundationCamera(api: mockApi); + final camera = AVFoundationCamera(api: mockApi); // Act expect( @@ -179,8 +175,8 @@ void main() { test('Should send initialization data', () async { // Arrange - final MockCameraApi mockApi = MockCameraApi(); - final AVFoundationCamera camera = AVFoundationCamera(api: mockApi); + final mockApi = MockCameraApi(); + final camera = AVFoundationCamera(api: mockApi); final int cameraId = await camera.createCamera( const CameraDescription( name: 'Test', @@ -216,8 +212,8 @@ void main() { test('Should send a disposal call on dispose', () async { // Arrange - final MockCameraApi mockApi = MockCameraApi(); - final AVFoundationCamera camera = AVFoundationCamera(api: mockApi); + final mockApi = MockCameraApi(); + final camera = AVFoundationCamera(api: mockApi); final int cameraId = await camera.createCamera( const CameraDescription( name: 'Test', @@ -255,7 +251,7 @@ void main() { late AVFoundationCamera camera; late int cameraId; setUp(() async { - final MockCameraApi mockApi = MockCameraApi(); + final mockApi = MockCameraApi(); when(mockApi.create(any, any)).thenAnswer((_) async => 1); camera = AVFoundationCamera(api: mockApi); cameraId = await camera.createCamera( @@ -285,12 +281,11 @@ void main() { // Act final Stream eventStream = camera .onCameraInitialized(cameraId); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); - final PlatformSize previewSize = PlatformSize(width: 3840, height: 2160); + final previewSize = PlatformSize(width: 3840, height: 2160); // Emit test events - final CameraInitializedEvent event = CameraInitializedEvent( + final event = CameraInitializedEvent( cameraId, previewSize.width, previewSize.height, @@ -321,12 +316,11 @@ void main() { final Stream errorStream = camera.onCameraError( cameraId, ); - final StreamQueue streamQueue = - StreamQueue(errorStream); + final streamQueue = StreamQueue(errorStream); // Emit test events - const String errorMessage = 'Error Description'; - final CameraErrorEvent event = CameraErrorEvent(cameraId, errorMessage); + const errorMessage = 'Error Description'; + final event = CameraErrorEvent(cameraId, errorMessage); camera.hostCameraHandlers[cameraId]!.error(errorMessage); camera.hostCameraHandlers[cameraId]!.error(errorMessage); camera.hostCameraHandlers[cameraId]!.error(errorMessage); @@ -344,14 +338,13 @@ void main() { // Act final Stream eventStream = camera .onDeviceOrientationChanged(); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue( + eventStream, + ); // Emit test events - const DeviceOrientationChangedEvent event = DeviceOrientationChangedEvent( - DeviceOrientation.portraitUp, - ); - for (int i = 0; i < 3; i++) { + const event = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); + for (var i = 0; i < 3; i++) { camera.hostHandler.deviceOrientationChanged( PlatformDeviceOrientation.portraitUp, ); @@ -402,25 +395,24 @@ void main() { test( 'Should fetch CameraDescription instances for available cameras', () async { - final List returnData = - [ - PlatformCameraDescription( - name: 'Test 1', - lensDirection: PlatformCameraLensDirection.front, - lensType: PlatformCameraLensType.ultraWide, - ), - PlatformCameraDescription( - name: 'Test 2', - lensDirection: PlatformCameraLensDirection.back, - lensType: PlatformCameraLensType.telephoto, - ), - ]; + final returnData = [ + PlatformCameraDescription( + name: 'Test 1', + lensDirection: PlatformCameraLensDirection.front, + lensType: PlatformCameraLensType.ultraWide, + ), + PlatformCameraDescription( + name: 'Test 2', + lensDirection: PlatformCameraLensDirection.back, + lensType: PlatformCameraLensType.telephoto, + ), + ]; when(mockApi.getAvailableCameras()).thenAnswer((_) async => returnData); final List cameras = await camera.availableCameras(); expect(cameras.length, returnData.length); - for (int i = 0; i < returnData.length; i++) { + for (var i = 0; i < returnData.length; i++) { expect(cameras[i].name, returnData[i].name); expect( cameras[i].lensDirection, @@ -439,8 +431,8 @@ void main() { test( 'Should throw CameraException when availableCameras throws a PlatformException', () { - const String code = 'TESTING_ERROR_CODE'; - const String message = 'Mock error message used during testing.'; + const code = 'TESTING_ERROR_CODE'; + const message = 'Mock error message used during testing.'; when(mockApi.getAvailableCameras()).thenAnswer( (_) async => throw PlatformException(code: code, message: message), ); @@ -461,7 +453,7 @@ void main() { ); test('Should take a picture and return an XFile instance', () async { - const String stubPath = '/test/path.jpg'; + const stubPath = '/test/path.jpg'; when(mockApi.takePicture()).thenAnswer((_) async => stubPath); final XFile file = await camera.takePicture(cameraId); @@ -496,7 +488,7 @@ void main() { ); test('Should stop a video recording and return the file', () async { - const String stubPath = '/test/path.mp4'; + const stubPath = '/test/path.mp4'; when(mockApi.stopVideoRecording()).thenAnswer((_) async => stubPath); final XFile file = await camera.stopVideoRecording(cameraId); @@ -517,7 +509,7 @@ void main() { }); test('Should set the description while recording', () async { - const CameraDescription camera2Description = CameraDescription( + const camera2Description = CameraDescription( name: 'Test2', lensDirection: CameraLensDirection.front, sensorOrientation: 0, @@ -565,14 +557,13 @@ void main() { }); test('Should set the exposure point to a value', () async { - const Point point = Point(0.4, 0.6); + const point = Point(0.4, 0.6); await camera.setExposurePoint(cameraId, point); final VerificationResult verification = verify( mockApi.setExposurePoint(captureAny), ); - final PlatformPoint? passedPoint = - verification.captured[0] as PlatformPoint?; + final passedPoint = verification.captured[0] as PlatformPoint?; expect(passedPoint?.x, point.x); expect(passedPoint?.y, point.y); }); @@ -583,13 +574,12 @@ void main() { final VerificationResult verification = verify( mockApi.setExposurePoint(captureAny), ); - final PlatformPoint? passedPoint = - verification.captured[0] as PlatformPoint?; + final passedPoint = verification.captured[0] as PlatformPoint?; expect(passedPoint, null); }); test('Should get the min exposure offset', () async { - const double stubMinOffset = 2.0; + const stubMinOffset = 2.0; when( mockApi.getMinExposureOffset(), ).thenAnswer((_) async => stubMinOffset); @@ -602,7 +592,7 @@ void main() { }); test('Should get the max exposure offset', () async { - const double stubMaxOffset = 2.0; + const stubMaxOffset = 2.0; when( mockApi.getMaxExposureOffset(), ).thenAnswer((_) async => stubMaxOffset); @@ -621,7 +611,7 @@ void main() { }); test('Should set the exposure offset', () async { - const double stubOffset = 0.5; + const stubOffset = 0.5; final double actualOffset = await camera.setExposureOffset(cameraId, 0.5); verify(mockApi.setExposureOffset(stubOffset)); @@ -642,14 +632,13 @@ void main() { }); test('Should set the focus point to a value', () async { - const Point point = Point(0.4, 0.6); + const point = Point(0.4, 0.6); await camera.setFocusPoint(cameraId, point); final VerificationResult verification = verify( mockApi.setFocusPoint(captureAny), ); - final PlatformPoint? passedPoint = - verification.captured[0] as PlatformPoint?; + final passedPoint = verification.captured[0] as PlatformPoint?; expect(passedPoint?.x, point.x); expect(passedPoint?.y, point.y); }); @@ -660,8 +649,7 @@ void main() { final VerificationResult verification = verify( mockApi.setFocusPoint(captureAny), ); - final PlatformPoint? passedPoint = - verification.captured[0] as PlatformPoint?; + final passedPoint = verification.captured[0] as PlatformPoint?; expect(passedPoint, null); }); @@ -673,7 +661,7 @@ void main() { }); test('Should get the max zoom level', () async { - const double stubZoomLevel = 10.0; + const stubZoomLevel = 10.0; when(mockApi.getMaxZoomLevel()).thenAnswer((_) async => stubZoomLevel); final double maxZoomLevel = await camera.getMaxZoomLevel(cameraId); @@ -682,7 +670,7 @@ void main() { }); test('Should get the min zoom level', () async { - const double stubZoomLevel = 10.0; + const stubZoomLevel = 10.0; when(mockApi.getMinZoomLevel()).thenAnswer((_) async => stubZoomLevel); final double minZoomLevel = await camera.getMinZoomLevel(cameraId); @@ -691,7 +679,7 @@ void main() { }); test('Should set the zoom level', () async { - const double zoom = 2.0; + const zoom = 2.0; await camera.setZoomLevel(cameraId, zoom); @@ -701,8 +689,226 @@ void main() { test( 'Should throw CameraException when illegal zoom level is supplied', () async { - const String code = 'ZOOM_ERROR'; - const String message = 'Illegal zoom error'; + const code = 'ZOOM_ERROR'; + const message = 'Illegal zoom error'; + when(mockApi.setZoomLevel(any)).thenAnswer( + (_) async => throw PlatformException(code: code, message: message), + ); + + expect( + () => camera.setZoomLevel(cameraId, -1.0), + throwsA( + isA() + .having((CameraException e) => e.code, 'code', code) + .having( + (CameraException e) => e.description, + 'description', + message, + ), + ), + ); + }, + ); + + test('Should set video stabilization mode to off', () async { + when( + mockApi.isVideoStabilizationModeSupported( + PlatformVideoStabilizationMode.off, + ), + ).thenAnswer((_) async => true); + + await camera.setVideoStabilizationMode( + cameraId, + VideoStabilizationMode.off, + ); + + verify( + mockApi.setVideoStabilizationMode(PlatformVideoStabilizationMode.off), + ); + }); + + test('Should set video stabilization mode to level1', () async { + when( + mockApi.isVideoStabilizationModeSupported( + PlatformVideoStabilizationMode.standard, + ), + ).thenAnswer((_) async => true); + + await camera.setVideoStabilizationMode( + cameraId, + VideoStabilizationMode.level1, + ); + + verify( + mockApi.setVideoStabilizationMode( + PlatformVideoStabilizationMode.standard, + ), + ); + }); + + test('Should set video stabilization mode to cinematic', () async { + when( + mockApi.isVideoStabilizationModeSupported( + PlatformVideoStabilizationMode.cinematic, + ), + ).thenAnswer((_) async => true); + + await camera.setVideoStabilizationMode( + cameraId, + VideoStabilizationMode.level2, + ); + + verify( + mockApi.setVideoStabilizationMode( + PlatformVideoStabilizationMode.cinematic, + ), + ); + }); + + test('Should set video stabilization mode to cinematicExtended', () async { + when( + mockApi.isVideoStabilizationModeSupported( + PlatformVideoStabilizationMode.cinematicExtended, + ), + ).thenAnswer((_) async => true); + + await camera.setVideoStabilizationMode( + cameraId, + VideoStabilizationMode.level3, + ); + + verify( + mockApi.setVideoStabilizationMode( + PlatformVideoStabilizationMode.cinematicExtended, + ), + ); + }); + + test('Should get no video stabilization mode', () async { + when( + mockApi.isVideoStabilizationModeSupported(any), + ).thenAnswer((_) async => false); + + final Iterable modes = await camera + .getSupportedVideoStabilizationModes(cameraId); + + expect(modes, isEmpty); + }); + + test('Should get off and standard video stabilization modes', () async { + when( + mockApi.isVideoStabilizationModeSupported( + PlatformVideoStabilizationMode.off, + ), + ).thenAnswer((_) async => true); + when( + mockApi.isVideoStabilizationModeSupported( + PlatformVideoStabilizationMode.standard, + ), + ).thenAnswer((_) async => true); + when( + mockApi.isVideoStabilizationModeSupported( + PlatformVideoStabilizationMode.cinematic, + ), + ).thenAnswer((_) async => false); + when( + mockApi.isVideoStabilizationModeSupported( + PlatformVideoStabilizationMode.cinematicExtended, + ), + ).thenAnswer((_) async => false); + + final List modes = + (await camera.getSupportedVideoStabilizationModes(cameraId)).toList(); + + expect(modes, [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + ]); + }); + + test('Should get all video stabilization modes', () async { + when( + mockApi.isVideoStabilizationModeSupported(any), + ).thenAnswer((_) async => true); + + final List modes = + (await camera.getSupportedVideoStabilizationModes(cameraId)).toList(); + + expect(modes, [ + VideoStabilizationMode.off, + VideoStabilizationMode.level1, + VideoStabilizationMode.level2, + VideoStabilizationMode.level3, + ]); + }); + + test( + 'Should throw ArgumentError when unavailable video stabilization mode is set', + () async { + when( + mockApi.isVideoStabilizationModeSupported(any), + ).thenAnswer((_) async => false); + + expect( + () => camera.setVideoStabilizationMode( + cameraId, + VideoStabilizationMode.off, + ), + throwsA( + isA().having( + (ArgumentError e) => e.name, + 'name', + 'mode', + ), + ), + ); + expect( + () => camera.setVideoStabilizationMode( + cameraId, + VideoStabilizationMode.level1, + ), + throwsA( + isA().having( + (ArgumentError e) => e.name, + 'name', + 'mode', + ), + ), + ); + expect( + () => camera.setVideoStabilizationMode( + cameraId, + VideoStabilizationMode.level2, + ), + throwsA( + isA().having( + (ArgumentError e) => e.name, + 'name', + 'mode', + ), + ), + ); + expect( + () => camera.setVideoStabilizationMode( + cameraId, + VideoStabilizationMode.level3, + ), + throwsA( + isA().having( + (ArgumentError e) => e.name, + 'name', + 'mode', + ), + ), + ); + }, + ); + + test( + 'Should throw CameraException when illegal zoom level is supplied', + () async { + const code = 'ZOOM_ERROR'; + const message = 'Illegal zoom error'; when(mockApi.setZoomLevel(any)).thenAnswer( (_) async => throw PlatformException(code: code, message: message), ); diff --git a/packages/camera/camera_avfoundation/test/avfoundation_camera_test.mocks.dart b/packages/camera/camera_avfoundation/test/avfoundation_camera_test.mocks.dart index 0d09546d2aed..225eac9931c6 100644 --- a/packages/camera/camera_avfoundation/test/avfoundation_camera_test.mocks.dart +++ b/packages/camera/camera_avfoundation/test/avfoundation_camera_test.mocks.dart @@ -1,4 +1,4 @@ -// Mocks generated by Mockito 5.4.4 from annotations +// Mocks generated by Mockito 5.4.6 from annotations // in camera_avfoundation/test/avfoundation_camera_test.dart. // Do not manually edit this file. @@ -17,6 +17,7 @@ import 'package:mockito/src/dummies.dart' as _i3; // 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 @@ -302,6 +303,28 @@ class MockCameraApi extends _i1.Mock implements _i2.CameraApi { ) as _i4.Future); + @override + _i4.Future setVideoStabilizationMode( + _i2.PlatformVideoStabilizationMode? mode, + ) => + (super.noSuchMethod( + Invocation.method(#setVideoStabilizationMode, [mode]), + returnValue: _i4.Future.value(), + returnValueForMissingStub: _i4.Future.value(), + ) + as _i4.Future); + + @override + _i4.Future isVideoStabilizationModeSupported( + _i2.PlatformVideoStabilizationMode? mode, + ) => + (super.noSuchMethod( + Invocation.method(#isVideoStabilizationModeSupported, [mode]), + returnValue: _i4.Future.value(false), + returnValueForMissingStub: _i4.Future.value(false), + ) + as _i4.Future); + @override _i4.Future pausePreview() => (super.noSuchMethod( diff --git a/packages/camera/camera_avfoundation/test/type_conversion_test.dart b/packages/camera/camera_avfoundation/test/type_conversion_test.dart index ce0d6d5d493d..56bea24a084b 100644 --- a/packages/camera/camera_avfoundation/test/type_conversion_test.dart +++ b/packages/camera/camera_avfoundation/test/type_conversion_test.dart @@ -4,6 +4,7 @@ import 'dart:typed_data'; +import 'package:camera_avfoundation/src/messages.g.dart'; import 'package:camera_avfoundation/src/type_conversion.dart'; import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -11,23 +12,22 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('CameraImageData can be created', () { final CameraImageData cameraImage = cameraImageFromPlatformData( - { - 'format': 1, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4, - }, + PlatformCameraImageData( + formatCode: 1, + width: 4, + height: 1, + lensAperture: 1.8, + sensorExposureTimeNanoseconds: 9991324, + sensorSensitivity: 92.0, + planes: [ + PlatformCameraImagePlane( + bytes: Uint8List.fromList([1, 2, 3, 4]), + bytesPerRow: 4, + width: 4, + height: 1, + ), ], - }, + ), ); expect(cameraImage.height, 1); expect(cameraImage.width, 4); @@ -37,23 +37,22 @@ void main() { test('CameraImageData has ImageFormatGroup.yuv420', () { final CameraImageData cameraImage = cameraImageFromPlatformData( - { - 'format': 875704438, - 'height': 1, - 'width': 4, - 'lensAperture': 1.8, - 'sensorExposureTime': 9991324, - 'sensorSensitivity': 92.0, - 'planes': [ - { - 'bytes': Uint8List.fromList([1, 2, 3, 4]), - 'bytesPerPixel': 1, - 'bytesPerRow': 4, - 'height': 1, - 'width': 4, - }, + PlatformCameraImageData( + formatCode: 875704438, + width: 4, + height: 1, + lensAperture: 1.8, + sensorExposureTimeNanoseconds: 9991324, + sensorSensitivity: 92.0, + planes: [ + PlatformCameraImagePlane( + bytes: Uint8List.fromList([1, 2, 3, 4]), + bytesPerRow: 4, + width: 4, + height: 1, + ), ], - }, + ), ); expect(cameraImage.format.group, ImageFormatGroup.yuv420); }); diff --git a/packages/camera/camera_platform_interface/CHANGELOG.md b/packages/camera/camera_platform_interface/CHANGELOG.md index 4293013ddeb1..fb538d49fd98 100644 --- a/packages/camera/camera_platform_interface/CHANGELOG.md +++ b/packages/camera/camera_platform_interface/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. ## 2.12.0 diff --git a/packages/camera/camera_platform_interface/lib/src/method_channel/method_channel_camera.dart b/packages/camera/camera_platform_interface/lib/src/method_channel/method_channel_camera.dart index d48b06023f13..3652de5861d5 100644 --- a/packages/camera/camera_platform_interface/lib/src/method_channel/method_channel_camera.dart +++ b/packages/camera/camera_platform_interface/lib/src/method_channel/method_channel_camera.dart @@ -20,9 +20,7 @@ const MethodChannel _channel = MethodChannel('plugins.flutter.io/camera'); class MethodChannelCamera extends CameraPlatform { /// Construct a new method channel camera instance. MethodChannelCamera() { - const MethodChannel channel = MethodChannel( - 'flutter.io/cameraPlugin/device', - ); + const channel = MethodChannel('flutter.io/cameraPlugin/device'); channel.setMethodCallHandler( (MethodCall call) => handleDeviceMethodCall(call), ); @@ -127,16 +125,14 @@ class MethodChannelCamera extends CameraPlatform { ImageFormatGroup imageFormatGroup = ImageFormatGroup.unknown, }) { _channels.putIfAbsent(cameraId, () { - final MethodChannel channel = MethodChannel( - 'flutter.io/cameraPlugin/camera$cameraId', - ); + final channel = MethodChannel('flutter.io/cameraPlugin/camera$cameraId'); channel.setMethodCallHandler( (MethodCall call) => handleCameraMethodCall(call, cameraId), ); return channel; }); - final Completer completer = Completer(); + final completer = Completer(); onCameraInitialized(cameraId).first.then((CameraInitializedEvent value) { completer.complete(); @@ -338,7 +334,7 @@ class MethodChannelCamera extends CameraPlatform { } void _startStreamListener() { - const EventChannel cameraEventChannel = EventChannel( + const cameraEventChannel = EventChannel( 'plugins.flutter.io/camera/imageStream', ); _platformImageStreamSubscription = cameraEventChannel diff --git a/packages/camera/camera_platform_interface/pubspec.yaml b/packages/camera/camera_platform_interface/pubspec.yaml index 9d8e8c97665b..3c2a1cbea685 100644 --- a/packages/camera/camera_platform_interface/pubspec.yaml +++ b/packages/camera/camera_platform_interface/pubspec.yaml @@ -7,8 +7,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.12.0 environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" dependencies: cross_file: ^0.3.1 diff --git a/packages/camera/camera_platform_interface/test/camera_platform_interface_test.dart b/packages/camera/camera_platform_interface/test/camera_platform_interface_test.dart index e252ba9e6139..9a9731062fdd 100644 --- a/packages/camera/camera_platform_interface/test/camera_platform_interface_test.dart +++ b/packages/camera/camera_platform_interface/test/camera_platform_interface_test.dart @@ -36,7 +36,7 @@ void main() { 'Default implementation of availableCameras() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -50,7 +50,7 @@ void main() { 'Default implementation of onCameraInitialized() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -64,7 +64,7 @@ void main() { 'Default implementation of onResolutionChanged() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -78,7 +78,7 @@ void main() { 'Default implementation of onCameraClosing() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -92,7 +92,7 @@ void main() { 'Default implementation of onCameraError() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect(() => cameraPlatform.onCameraError(1), throwsUnimplementedError); @@ -103,7 +103,7 @@ void main() { 'Default implementation of onDeviceOrientationChanged() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -117,7 +117,7 @@ void main() { 'Default implementation of lockCaptureOrientation() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -134,7 +134,7 @@ void main() { 'Default implementation of unlockCaptureOrientation() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -148,7 +148,7 @@ void main() { 'Default implementation of dispose() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect(() => cameraPlatform.dispose(1), throwsUnimplementedError); @@ -159,7 +159,7 @@ void main() { 'Default implementation of createCamera() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -180,13 +180,13 @@ void main() { 'Default implementation of createCameraWithSettings() should call createCamera() passing parameters', () { // Arrange - const CameraDescription cameraDescription = CameraDescription( + const cameraDescription = CameraDescription( name: 'back', lensDirection: CameraLensDirection.back, sensorOrientation: 0, ); - const MediaSettings mediaSettings = MediaSettings( + const mediaSettings = MediaSettings( resolutionPreset: ResolutionPreset.low, fps: 15, videoBitrate: 200000, @@ -194,32 +194,31 @@ void main() { enableAudio: true, ); - bool createCameraCalled = false; - - final OverriddenCameraPlatform cameraPlatform = - OverriddenCameraPlatform(( - CameraDescription cameraDescriptionArg, - ResolutionPreset? resolutionPresetArg, - bool enableAudioArg, - ) { - expect( - cameraDescriptionArg, - cameraDescription, - reason: 'should pass camera description', - ); - expect( - resolutionPresetArg, - mediaSettings.resolutionPreset, - reason: 'should pass resolution preset', - ); - expect( - enableAudioArg, - mediaSettings.enableAudio, - reason: 'should pass enableAudio', - ); - - createCameraCalled = true; - }); + var createCameraCalled = false; + + final cameraPlatform = OverriddenCameraPlatform(( + CameraDescription cameraDescriptionArg, + ResolutionPreset? resolutionPresetArg, + bool enableAudioArg, + ) { + expect( + cameraDescriptionArg, + cameraDescription, + reason: 'should pass camera description', + ); + expect( + resolutionPresetArg, + mediaSettings.resolutionPreset, + reason: 'should pass resolution preset', + ); + expect( + enableAudioArg, + mediaSettings.enableAudio, + reason: 'should pass enableAudio', + ); + + createCameraCalled = true; + }); // Act & Assert cameraPlatform.createCameraWithSettings( @@ -240,7 +239,7 @@ void main() { 'Default implementation of initializeCamera() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -254,7 +253,7 @@ void main() { 'Default implementation of pauseVideoRecording() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -268,7 +267,7 @@ void main() { 'Default implementation of prepareForVideoRecording() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -282,7 +281,7 @@ void main() { 'Default implementation of resumeVideoRecording() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -296,7 +295,7 @@ void main() { 'Default implementation of setFlashMode() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -310,7 +309,7 @@ void main() { 'Default implementation of setExposureMode() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -324,7 +323,7 @@ void main() { 'Default implementation of setExposurePoint() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -338,7 +337,7 @@ void main() { 'Default implementation of getMinExposureOffset() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -352,7 +351,7 @@ void main() { 'Default implementation of getMaxExposureOffset() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -366,7 +365,7 @@ void main() { 'Default implementation of getExposureOffsetStepSize() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -380,7 +379,7 @@ void main() { 'Default implementation of setExposureOffset() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -394,7 +393,7 @@ void main() { 'Default implementation of setFocusMode() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -408,7 +407,7 @@ void main() { 'Default implementation of setFocusPoint() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -422,7 +421,7 @@ void main() { 'Default implementation of startVideoRecording() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -436,7 +435,7 @@ void main() { 'Default implementation of stopVideoRecording() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -450,7 +449,7 @@ void main() { 'Default implementation of takePicture() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect(() => cameraPlatform.takePicture(1), throwsUnimplementedError); @@ -461,7 +460,7 @@ void main() { 'Default implementation of getMaxZoomLevel() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -475,7 +474,7 @@ void main() { 'Default implementation of getMinZoomLevel() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -489,7 +488,7 @@ void main() { 'Default implementation of setZoomLevel() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect( @@ -503,7 +502,7 @@ void main() { 'Default implementation of pausePreview() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect(() => cameraPlatform.pausePreview(1), throwsUnimplementedError); @@ -514,7 +513,7 @@ void main() { 'Default implementation of resumePreview() should throw unimplemented error', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect(() => cameraPlatform.resumePreview(1), throwsUnimplementedError); @@ -525,7 +524,7 @@ void main() { 'Default implementation of supportsImageStreaming() should return false', () { // Arrange - final ExtendsCameraPlatform cameraPlatform = ExtendsCameraPlatform(); + final cameraPlatform = ExtendsCameraPlatform(); // Act & Assert expect(cameraPlatform.supportsImageStreaming(), false); diff --git a/packages/camera/camera_platform_interface/test/events/camera_event_test.dart b/packages/camera/camera_platform_interface/test/events/camera_event_test.dart index a5e45d95f00a..58ace30ce4bb 100644 --- a/packages/camera/camera_platform_interface/test/events/camera_event_test.dart +++ b/packages/camera/camera_platform_interface/test/events/camera_event_test.dart @@ -10,7 +10,7 @@ void main() { group('CameraInitializedEvent tests', () { test('Constructor should initialize all properties', () { - const CameraInitializedEvent event = CameraInitializedEvent( + const event = CameraInitializedEvent( 1, 1024, 640, @@ -30,16 +30,15 @@ void main() { }); test('fromJson should initialize all properties', () { - final CameraInitializedEvent event = - CameraInitializedEvent.fromJson(const { - 'cameraId': 1, - 'previewWidth': 1024.0, - 'previewHeight': 640.0, - 'exposureMode': 'auto', - 'exposurePointSupported': true, - 'focusMode': 'auto', - 'focusPointSupported': true, - }); + final event = CameraInitializedEvent.fromJson(const { + 'cameraId': 1, + 'previewWidth': 1024.0, + 'previewHeight': 640.0, + 'exposureMode': 'auto', + 'exposurePointSupported': true, + 'focusMode': 'auto', + 'focusPointSupported': true, + }); expect(event.cameraId, 1); expect(event.previewWidth, 1024); @@ -51,7 +50,7 @@ void main() { }); test('toJson should return a map with all fields', () { - const CameraInitializedEvent event = CameraInitializedEvent( + const event = CameraInitializedEvent( 1, 1024, 640, @@ -74,7 +73,7 @@ void main() { }); test('equals should return true if objects are the same', () { - const CameraInitializedEvent firstEvent = CameraInitializedEvent( + const firstEvent = CameraInitializedEvent( 1, 1024, 640, @@ -83,7 +82,7 @@ void main() { FocusMode.auto, true, ); - const CameraInitializedEvent secondEvent = CameraInitializedEvent( + const secondEvent = CameraInitializedEvent( 1, 1024, 640, @@ -97,7 +96,7 @@ void main() { }); test('equals should return false if cameraId is different', () { - const CameraInitializedEvent firstEvent = CameraInitializedEvent( + const firstEvent = CameraInitializedEvent( 1, 1024, 640, @@ -106,7 +105,7 @@ void main() { FocusMode.auto, true, ); - const CameraInitializedEvent secondEvent = CameraInitializedEvent( + const secondEvent = CameraInitializedEvent( 2, 1024, 640, @@ -120,7 +119,7 @@ void main() { }); test('equals should return false if previewWidth is different', () { - const CameraInitializedEvent firstEvent = CameraInitializedEvent( + const firstEvent = CameraInitializedEvent( 1, 1024, 640, @@ -129,7 +128,7 @@ void main() { FocusMode.auto, true, ); - const CameraInitializedEvent secondEvent = CameraInitializedEvent( + const secondEvent = CameraInitializedEvent( 1, 2048, 640, @@ -143,7 +142,7 @@ void main() { }); test('equals should return false if previewHeight is different', () { - const CameraInitializedEvent firstEvent = CameraInitializedEvent( + const firstEvent = CameraInitializedEvent( 1, 1024, 640, @@ -152,7 +151,7 @@ void main() { FocusMode.auto, true, ); - const CameraInitializedEvent secondEvent = CameraInitializedEvent( + const secondEvent = CameraInitializedEvent( 1, 1024, 980, @@ -166,7 +165,7 @@ void main() { }); test('equals should return false if exposureMode is different', () { - const CameraInitializedEvent firstEvent = CameraInitializedEvent( + const firstEvent = CameraInitializedEvent( 1, 1024, 640, @@ -175,7 +174,7 @@ void main() { FocusMode.auto, true, ); - const CameraInitializedEvent secondEvent = CameraInitializedEvent( + const secondEvent = CameraInitializedEvent( 1, 1024, 640, @@ -191,7 +190,7 @@ void main() { test( 'equals should return false if exposurePointSupported is different', () { - const CameraInitializedEvent firstEvent = CameraInitializedEvent( + const firstEvent = CameraInitializedEvent( 1, 1024, 640, @@ -200,7 +199,7 @@ void main() { FocusMode.auto, true, ); - const CameraInitializedEvent secondEvent = CameraInitializedEvent( + const secondEvent = CameraInitializedEvent( 1, 1024, 640, @@ -215,7 +214,7 @@ void main() { ); test('equals should return false if focusMode is different', () { - const CameraInitializedEvent firstEvent = CameraInitializedEvent( + const firstEvent = CameraInitializedEvent( 1, 1024, 640, @@ -224,7 +223,7 @@ void main() { FocusMode.auto, true, ); - const CameraInitializedEvent secondEvent = CameraInitializedEvent( + const secondEvent = CameraInitializedEvent( 1, 1024, 640, @@ -238,7 +237,7 @@ void main() { }); test('equals should return false if focusPointSupported is different', () { - const CameraInitializedEvent firstEvent = CameraInitializedEvent( + const firstEvent = CameraInitializedEvent( 1, 1024, 640, @@ -247,7 +246,7 @@ void main() { FocusMode.auto, true, ); - const CameraInitializedEvent secondEvent = CameraInitializedEvent( + const secondEvent = CameraInitializedEvent( 1, 1024, 640, @@ -261,7 +260,7 @@ void main() { }); test('hashCode should match hashCode of all properties', () { - const CameraInitializedEvent event = CameraInitializedEvent( + const event = CameraInitializedEvent( 1, 1024, 640, @@ -286,11 +285,7 @@ void main() { group('CameraResolutionChangesEvent tests', () { test('Constructor should initialize all properties', () { - const CameraResolutionChangedEvent event = CameraResolutionChangedEvent( - 1, - 1024, - 640, - ); + const event = CameraResolutionChangedEvent(1, 1024, 640); expect(event.cameraId, 1); expect(event.captureWidth, 1024); @@ -298,12 +293,13 @@ void main() { }); test('fromJson should initialize all properties', () { - final CameraResolutionChangedEvent event = - CameraResolutionChangedEvent.fromJson(const { - 'cameraId': 1, - 'captureWidth': 1024.0, - 'captureHeight': 640.0, - }); + final event = CameraResolutionChangedEvent.fromJson( + const { + 'cameraId': 1, + 'captureWidth': 1024.0, + 'captureHeight': 640.0, + }, + ); expect(event.cameraId, 1); expect(event.captureWidth, 1024); @@ -311,11 +307,7 @@ void main() { }); test('toJson should return a map with all fields', () { - const CameraResolutionChangedEvent event = CameraResolutionChangedEvent( - 1, - 1024, - 640, - ); + const event = CameraResolutionChangedEvent(1, 1024, 640); final Map jsonMap = event.toJson(); @@ -326,47 +318,35 @@ void main() { }); test('equals should return true if objects are the same', () { - const CameraResolutionChangedEvent firstEvent = - CameraResolutionChangedEvent(1, 1024, 640); - const CameraResolutionChangedEvent secondEvent = - CameraResolutionChangedEvent(1, 1024, 640); + const firstEvent = CameraResolutionChangedEvent(1, 1024, 640); + const secondEvent = CameraResolutionChangedEvent(1, 1024, 640); expect(firstEvent == secondEvent, true); }); test('equals should return false if cameraId is different', () { - const CameraResolutionChangedEvent firstEvent = - CameraResolutionChangedEvent(1, 1024, 640); - const CameraResolutionChangedEvent secondEvent = - CameraResolutionChangedEvent(2, 1024, 640); + const firstEvent = CameraResolutionChangedEvent(1, 1024, 640); + const secondEvent = CameraResolutionChangedEvent(2, 1024, 640); expect(firstEvent == secondEvent, false); }); test('equals should return false if captureWidth is different', () { - const CameraResolutionChangedEvent firstEvent = - CameraResolutionChangedEvent(1, 1024, 640); - const CameraResolutionChangedEvent secondEvent = - CameraResolutionChangedEvent(1, 2048, 640); + const firstEvent = CameraResolutionChangedEvent(1, 1024, 640); + const secondEvent = CameraResolutionChangedEvent(1, 2048, 640); expect(firstEvent == secondEvent, false); }); test('equals should return false if captureHeight is different', () { - const CameraResolutionChangedEvent firstEvent = - CameraResolutionChangedEvent(1, 1024, 640); - const CameraResolutionChangedEvent secondEvent = - CameraResolutionChangedEvent(1, 1024, 980); + const firstEvent = CameraResolutionChangedEvent(1, 1024, 640); + const secondEvent = CameraResolutionChangedEvent(1, 1024, 980); expect(firstEvent == secondEvent, false); }); test('hashCode should match hashCode of all properties', () { - const CameraResolutionChangedEvent event = CameraResolutionChangedEvent( - 1, - 1024, - 640, - ); + const event = CameraResolutionChangedEvent(1, 1024, 640); final int expectedHashCode = Object.hash( event.cameraId.hashCode, event.captureWidth, @@ -379,21 +359,21 @@ void main() { group('CameraClosingEvent tests', () { test('Constructor should initialize all properties', () { - const CameraClosingEvent event = CameraClosingEvent(1); + const event = CameraClosingEvent(1); expect(event.cameraId, 1); }); test('fromJson should initialize all properties', () { - final CameraClosingEvent event = CameraClosingEvent.fromJson( - const {'cameraId': 1}, - ); + final event = CameraClosingEvent.fromJson(const { + 'cameraId': 1, + }); expect(event.cameraId, 1); }); test('toJson should return a map with all fields', () { - const CameraClosingEvent event = CameraClosingEvent(1); + const event = CameraClosingEvent(1); final Map jsonMap = event.toJson(); @@ -402,22 +382,22 @@ void main() { }); test('equals should return true if objects are the same', () { - const CameraClosingEvent firstEvent = CameraClosingEvent(1); - const CameraClosingEvent secondEvent = CameraClosingEvent(1); + const firstEvent = CameraClosingEvent(1); + const secondEvent = CameraClosingEvent(1); expect(firstEvent == secondEvent, true); }); test('equals should return false if cameraId is different', () { - const CameraClosingEvent firstEvent = CameraClosingEvent(1); - const CameraClosingEvent secondEvent = CameraClosingEvent(2); + const firstEvent = CameraClosingEvent(1); + const secondEvent = CameraClosingEvent(2); expect(firstEvent == secondEvent, false); }); test('hashCode should match hashCode of all properties', () { - const CameraClosingEvent event = CameraClosingEvent(1); - final int expectedHashCode = event.cameraId.hashCode; + const event = CameraClosingEvent(1); + final expectedHashCode = event.cameraId.hashCode; expect(event.hashCode, expectedHashCode); }); @@ -425,23 +405,24 @@ void main() { group('CameraErrorEvent tests', () { test('Constructor should initialize all properties', () { - const CameraErrorEvent event = CameraErrorEvent(1, 'Error'); + const event = CameraErrorEvent(1, 'Error'); expect(event.cameraId, 1); expect(event.description, 'Error'); }); test('fromJson should initialize all properties', () { - final CameraErrorEvent event = CameraErrorEvent.fromJson( - const {'cameraId': 1, 'description': 'Error'}, - ); + final event = CameraErrorEvent.fromJson(const { + 'cameraId': 1, + 'description': 'Error', + }); expect(event.cameraId, 1); expect(event.description, 'Error'); }); test('toJson should return a map with all fields', () { - const CameraErrorEvent event = CameraErrorEvent(1, 'Error'); + const event = CameraErrorEvent(1, 'Error'); final Map jsonMap = event.toJson(); @@ -451,28 +432,28 @@ void main() { }); test('equals should return true if objects are the same', () { - const CameraErrorEvent firstEvent = CameraErrorEvent(1, 'Error'); - const CameraErrorEvent secondEvent = CameraErrorEvent(1, 'Error'); + const firstEvent = CameraErrorEvent(1, 'Error'); + const secondEvent = CameraErrorEvent(1, 'Error'); expect(firstEvent == secondEvent, true); }); test('equals should return false if cameraId is different', () { - const CameraErrorEvent firstEvent = CameraErrorEvent(1, 'Error'); - const CameraErrorEvent secondEvent = CameraErrorEvent(2, 'Error'); + const firstEvent = CameraErrorEvent(1, 'Error'); + const secondEvent = CameraErrorEvent(2, 'Error'); expect(firstEvent == secondEvent, false); }); test('equals should return false if description is different', () { - const CameraErrorEvent firstEvent = CameraErrorEvent(1, 'Error'); - const CameraErrorEvent secondEvent = CameraErrorEvent(1, 'Ooops'); + const firstEvent = CameraErrorEvent(1, 'Error'); + const secondEvent = CameraErrorEvent(1, 'Ooops'); expect(firstEvent == secondEvent, false); }); test('hashCode should match hashCode of all properties', () { - const CameraErrorEvent event = CameraErrorEvent(1, 'Error'); + const event = CameraErrorEvent(1, 'Error'); final int expectedHashCode = Object.hash( event.cameraId.hashCode, event.description, diff --git a/packages/camera/camera_platform_interface/test/events/device_event_test.dart b/packages/camera/camera_platform_interface/test/events/device_event_test.dart index ffd77a42ffba..794a301f7523 100644 --- a/packages/camera/camera_platform_interface/test/events/device_event_test.dart +++ b/packages/camera/camera_platform_interface/test/events/device_event_test.dart @@ -11,26 +11,21 @@ void main() { group('DeviceOrientationChangedEvent tests', () { test('Constructor should initialize all properties', () { - const DeviceOrientationChangedEvent event = DeviceOrientationChangedEvent( - DeviceOrientation.portraitUp, - ); + const event = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); expect(event.orientation, DeviceOrientation.portraitUp); }); test('fromJson should initialize all properties', () { - final DeviceOrientationChangedEvent event = - DeviceOrientationChangedEvent.fromJson(const { - 'orientation': 'portraitUp', - }); + final event = DeviceOrientationChangedEvent.fromJson( + const {'orientation': 'portraitUp'}, + ); expect(event.orientation, DeviceOrientation.portraitUp); }); test('toJson should return a map with all fields', () { - const DeviceOrientationChangedEvent event = DeviceOrientationChangedEvent( - DeviceOrientation.portraitUp, - ); + const event = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); final Map jsonMap = event.toJson(); @@ -39,28 +34,30 @@ void main() { }); test('equals should return true if objects are the same', () { - const DeviceOrientationChangedEvent firstEvent = - DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); - const DeviceOrientationChangedEvent secondEvent = - DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); + const firstEvent = DeviceOrientationChangedEvent( + DeviceOrientation.portraitUp, + ); + const secondEvent = DeviceOrientationChangedEvent( + DeviceOrientation.portraitUp, + ); expect(firstEvent == secondEvent, true); }); test('equals should return false if orientation is different', () { - const DeviceOrientationChangedEvent firstEvent = - DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); - const DeviceOrientationChangedEvent secondEvent = - DeviceOrientationChangedEvent(DeviceOrientation.landscapeLeft); + const firstEvent = DeviceOrientationChangedEvent( + DeviceOrientation.portraitUp, + ); + const secondEvent = DeviceOrientationChangedEvent( + DeviceOrientation.landscapeLeft, + ); expect(firstEvent == secondEvent, false); }); test('hashCode should match hashCode of all properties', () { - const DeviceOrientationChangedEvent event = DeviceOrientationChangedEvent( - DeviceOrientation.portraitUp, - ); - final int expectedHashCode = event.orientation.hashCode; + const event = DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); + final expectedHashCode = event.orientation.hashCode; expect(event.hashCode, expectedHashCode); }); diff --git a/packages/camera/camera_platform_interface/test/method_channel/method_channel_camera_test.dart b/packages/camera/camera_platform_interface/test/method_channel/method_channel_camera_test.dart index 78cf02f80697..15d1c34ef555 100644 --- a/packages/camera/camera_platform_interface/test/method_channel/method_channel_camera_test.dart +++ b/packages/camera/camera_platform_interface/test/method_channel/method_channel_camera_test.dart @@ -22,7 +22,7 @@ void main() { group('Creation, Initialization & Disposal Tests', () { test('Should send creation data and receive back a camera id', () async { // Arrange - final MethodChannelMock cameraMockChannel = MethodChannelMock( + final cameraMockChannel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: { 'create': { @@ -31,7 +31,7 @@ void main() { }, }, ); - final MethodChannelCamera camera = MethodChannelCamera(); + final camera = MethodChannelCamera(); // Act final int cameraId = await camera.createCameraWithSettings( @@ -78,7 +78,7 @@ void main() { ), }, ); - final MethodChannelCamera camera = MethodChannelCamera(); + final camera = MethodChannelCamera(); // Act expect( @@ -126,7 +126,7 @@ void main() { ), }, ); - final MethodChannelCamera camera = MethodChannelCamera(); + final camera = MethodChannelCamera(); // Act expect( @@ -174,7 +174,7 @@ void main() { ), }, ); - final MethodChannelCamera camera = MethodChannelCamera(); + final camera = MethodChannelCamera(); // Act expect( @@ -198,7 +198,7 @@ void main() { test('Should send initialization data', () async { // Arrange - final MethodChannelMock cameraMockChannel = MethodChannelMock( + final cameraMockChannel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: { 'create': { @@ -208,7 +208,7 @@ void main() { 'initialize': null, }, ); - final MethodChannelCamera camera = MethodChannelCamera(); + final camera = MethodChannelCamera(); final int cameraId = await camera.createCameraWithSettings( const CameraDescription( name: 'Test', @@ -255,7 +255,7 @@ void main() { test('Should send a disposal call on dispose', () async { // Arrange - final MethodChannelMock cameraMockChannel = MethodChannelMock( + final cameraMockChannel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: { 'create': {'cameraId': 1}, @@ -264,7 +264,7 @@ void main() { }, ); - final MethodChannelCamera camera = MethodChannelCamera(); + final camera = MethodChannelCamera(); final int cameraId = await camera.createCameraWithSettings( const CameraDescription( name: 'Test', @@ -351,11 +351,10 @@ void main() { // Act final Stream eventStream = camera .onCameraInitialized(cameraId); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); // Emit test events - final CameraInitializedEvent event = CameraInitializedEvent( + final event = CameraInitializedEvent( cameraId, 3840, 2160, @@ -380,14 +379,13 @@ void main() { // Act final Stream resolutionStream = camera .onCameraResolutionChanged(cameraId); - final StreamQueue streamQueue = - StreamQueue(resolutionStream); + final streamQueue = StreamQueue( + resolutionStream, + ); // Emit test events - final CameraResolutionChangedEvent fhdEvent = - CameraResolutionChangedEvent(cameraId, 1920, 1080); - final CameraResolutionChangedEvent uhdEvent = - CameraResolutionChangedEvent(cameraId, 3840, 2160); + final fhdEvent = CameraResolutionChangedEvent(cameraId, 1920, 1080); + final uhdEvent = CameraResolutionChangedEvent(cameraId, 3840, 2160); await camera.handleCameraMethodCall( MethodCall('resolution_changed', fhdEvent.toJson()), cameraId, @@ -420,11 +418,10 @@ void main() { final Stream eventStream = camera.onCameraClosing( cameraId, ); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); // Emit test events - final CameraClosingEvent event = CameraClosingEvent(cameraId); + final event = CameraClosingEvent(cameraId); await camera.handleCameraMethodCall( MethodCall('camera_closing', event.toJson()), cameraId, @@ -452,14 +449,10 @@ void main() { final Stream errorStream = camera.onCameraError( cameraId, ); - final StreamQueue streamQueue = - StreamQueue(errorStream); + final streamQueue = StreamQueue(errorStream); // Emit test events - final CameraErrorEvent event = CameraErrorEvent( - cameraId, - 'Error Description', - ); + final event = CameraErrorEvent(cameraId, 'Error Description'); await camera.handleCameraMethodCall( MethodCall('error', event.toJson()), cameraId, @@ -486,12 +479,14 @@ void main() { // Act final Stream eventStream = camera .onDeviceOrientationChanged(); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue( + eventStream, + ); // Emit test events - const DeviceOrientationChangedEvent event = - DeviceOrientationChangedEvent(DeviceOrientation.portraitUp); + const event = DeviceOrientationChangedEvent( + DeviceOrientation.portraitUp, + ); await camera.handleDeviceMethodCall( MethodCall('orientation_changed', event.toJson()), ); @@ -558,7 +553,7 @@ void main() { 'Should fetch CameraDescription instances for available cameras', () async { // Arrange - final List returnData = [ + final returnData = [ { 'name': 'Test 1', 'lensFacing': 'front', @@ -570,7 +565,7 @@ void main() { 'sensorOrientation': 2, }, ]; - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'availableCameras': returnData}, ); @@ -584,11 +579,11 @@ void main() { isMethodCall('availableCameras', arguments: null), ]); expect(cameras.length, returnData.length); - for (int i = 0; i < returnData.length; i++) { + for (var i = 0; i < returnData.length; i++) { final Map typedData = (returnData[i] as Map) .cast(); - final CameraDescription cameraDescription = CameraDescription( + final cameraDescription = CameraDescription( name: typedData['name']! as String, lensDirection: parseCameraLensDirection( typedData['lensFacing']! as String, @@ -636,7 +631,7 @@ void main() { test('Should take a picture and return an XFile instance', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'takePicture': '/test/path.jpg'}, ); @@ -656,7 +651,7 @@ void main() { test('Should prepare for video recording', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'prepareForVideoRecording': null}, ); @@ -672,7 +667,7 @@ void main() { test('Should start recording a video', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'startVideoRecording': null}, ); @@ -695,13 +690,13 @@ void main() { test('Should set description while recording', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'setDescriptionWhileRecording': null}, ); // Act - const CameraDescription cameraDescription = CameraDescription( + const cameraDescription = CameraDescription( name: 'Test', lensDirection: CameraLensDirection.back, sensorOrientation: 0, @@ -719,7 +714,7 @@ void main() { test('Should stop a video recording and return the file', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'stopVideoRecording': '/test/path.mp4'}, ); @@ -739,7 +734,7 @@ void main() { test('Should pause a video recording', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'pauseVideoRecording': null}, ); @@ -758,7 +753,7 @@ void main() { test('Should resume a video recording', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'resumeVideoRecording': null}, ); @@ -777,7 +772,7 @@ void main() { test('Should set the flash mode', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'setFlashMode': null}, ); @@ -814,7 +809,7 @@ void main() { test('Should set the exposure mode', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'setExposureMode': null}, ); @@ -841,7 +836,7 @@ void main() { test('Should set the exposure point', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'setExposurePoint': null}, ); @@ -875,7 +870,7 @@ void main() { test('Should get the min exposure offset', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'getMinExposureOffset': 2.0}, ); @@ -897,7 +892,7 @@ void main() { test('Should get the max exposure offset', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'getMaxExposureOffset': 2.0}, ); @@ -919,7 +914,7 @@ void main() { test('Should get the exposure offset step size', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'getExposureOffsetStepSize': 0.25}, ); @@ -941,7 +936,7 @@ void main() { test('Should set the exposure offset', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'setExposureOffset': 0.6}, ); @@ -964,7 +959,7 @@ void main() { test('Should set the focus mode', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'setFocusMode': null}, ); @@ -991,7 +986,7 @@ void main() { test('Should set the exposure point', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'setFocusPoint': null}, ); @@ -1035,7 +1030,7 @@ void main() { test( 'Should throw MissingPluginException when handling unknown method', () { - final MethodChannelCamera camera = MethodChannelCamera(); + final camera = MethodChannelCamera(); expect( () => camera.handleCameraMethodCall( @@ -1049,7 +1044,7 @@ void main() { test('Should get the max zoom level', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'getMaxZoomLevel': 10.0}, ); @@ -1069,7 +1064,7 @@ void main() { test('Should get the min zoom level', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'getMinZoomLevel': 1.0}, ); @@ -1089,7 +1084,7 @@ void main() { test('Should set the zoom level', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'setZoomLevel': null}, ); @@ -1138,7 +1133,7 @@ void main() { test('Should lock the capture orientation', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'lockCaptureOrientation': null}, ); @@ -1163,7 +1158,7 @@ void main() { test('Should unlock the capture orientation', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'unlockCaptureOrientation': null}, ); @@ -1182,7 +1177,7 @@ void main() { test('Should pause the camera preview', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'pausePreview': null}, ); @@ -1201,7 +1196,7 @@ void main() { test('Should resume the camera preview', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'resumePreview': null}, ); @@ -1220,7 +1215,7 @@ void main() { test('Should start streaming', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: { 'startImageStream': null, @@ -1243,7 +1238,7 @@ void main() { test('Should stop streaming', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: { 'startImageStream': null, @@ -1266,7 +1261,7 @@ void main() { test('Should set the ImageFileFormat to heif', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'setImageFileFormat': 'heif'}, ); @@ -1288,7 +1283,7 @@ void main() { test('Should set the ImageFileFormat to jpeg', () async { // Arrange - final MethodChannelMock channel = MethodChannelMock( + final channel = MethodChannelMock( channelName: 'plugins.flutter.io/camera', methods: {'setImageFileFormat': 'jpeg'}, ); diff --git a/packages/camera/camera_platform_interface/test/types/camera_description_test.dart b/packages/camera/camera_platform_interface/test/types/camera_description_test.dart index 8b5aa448ab81..6bf9ee3f2bcd 100644 --- a/packages/camera/camera_platform_interface/test/types/camera_description_test.dart +++ b/packages/camera/camera_platform_interface/test/types/camera_description_test.dart @@ -26,7 +26,7 @@ void main() { group('CameraDescription tests', () { test('Constructor should initialize all properties', () { - const CameraDescription description = CameraDescription( + const description = CameraDescription( name: 'Test', lensDirection: CameraLensDirection.front, sensorOrientation: 90, @@ -40,13 +40,13 @@ void main() { }); test('equals should return true if objects are the same', () { - const CameraDescription firstDescription = CameraDescription( + const firstDescription = CameraDescription( name: 'Test', lensDirection: CameraLensDirection.front, sensorOrientation: 90, lensType: CameraLensType.ultraWide, ); - const CameraDescription secondDescription = CameraDescription( + const secondDescription = CameraDescription( name: 'Test', lensDirection: CameraLensDirection.front, sensorOrientation: 90, @@ -57,13 +57,13 @@ void main() { }); test('equals should return false if name is different', () { - const CameraDescription firstDescription = CameraDescription( + const firstDescription = CameraDescription( name: 'Test', lensDirection: CameraLensDirection.front, sensorOrientation: 90, lensType: CameraLensType.ultraWide, ); - const CameraDescription secondDescription = CameraDescription( + const secondDescription = CameraDescription( name: 'Testing', lensDirection: CameraLensDirection.front, sensorOrientation: 90, @@ -74,13 +74,13 @@ void main() { }); test('equals should return false if lens direction is different', () { - const CameraDescription firstDescription = CameraDescription( + const firstDescription = CameraDescription( name: 'Test', lensDirection: CameraLensDirection.front, sensorOrientation: 90, lensType: CameraLensType.ultraWide, ); - const CameraDescription secondDescription = CameraDescription( + const secondDescription = CameraDescription( name: 'Test', lensDirection: CameraLensDirection.back, sensorOrientation: 90, @@ -91,13 +91,13 @@ void main() { }); test('equals should return true if sensor orientation is different', () { - const CameraDescription firstDescription = CameraDescription( + const firstDescription = CameraDescription( name: 'Test', lensDirection: CameraLensDirection.front, sensorOrientation: 0, lensType: CameraLensType.ultraWide, ); - const CameraDescription secondDescription = CameraDescription( + const secondDescription = CameraDescription( name: 'Test', lensDirection: CameraLensDirection.front, sensorOrientation: 90, @@ -110,7 +110,7 @@ void main() { test( 'hashCode should match hashCode of all equality-tested properties', () { - const CameraDescription description = CameraDescription( + const description = CameraDescription( name: 'Test', lensDirection: CameraLensDirection.front, sensorOrientation: 0, @@ -127,7 +127,7 @@ void main() { ); test('toString should return correct string representation', () { - const CameraDescription description = CameraDescription( + const description = CameraDescription( name: 'Test', lensDirection: CameraLensDirection.front, sensorOrientation: 90, diff --git a/packages/camera/camera_platform_interface/test/types/camera_exception_test.dart b/packages/camera/camera_platform_interface/test/types/camera_exception_test.dart index 295fc5d76021..5eea0a8697f1 100644 --- a/packages/camera/camera_platform_interface/test/types/camera_exception_test.dart +++ b/packages/camera/camera_platform_interface/test/types/camera_exception_test.dart @@ -7,21 +7,21 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('constructor should initialize properties', () { - const String code = 'TEST_ERROR'; - const String description = 'This is a test error'; - final CameraException exception = CameraException(code, description); + const code = 'TEST_ERROR'; + const description = 'This is a test error'; + final exception = CameraException(code, description); expect(exception.code, code); expect(exception.description, description); }); test('toString: Should return a description of the exception', () { - const String code = 'TEST_ERROR'; - const String description = 'This is a test error'; - const String expected = 'CameraException($code, $description)'; - final CameraException exception = CameraException(code, description); + const code = 'TEST_ERROR'; + const description = 'This is a test error'; + const expected = 'CameraException($code, $description)'; + final exception = CameraException(code, description); - final String actual = exception.toString(); + final actual = exception.toString(); expect(actual, expected); }); diff --git a/packages/camera/camera_platform_interface/test/types/camera_image_data_test.dart b/packages/camera/camera_platform_interface/test/types/camera_image_data_test.dart index ea60b9b0f1a5..b5b1f6610f50 100644 --- a/packages/camera/camera_platform_interface/test/types/camera_image_data_test.dart +++ b/packages/camera/camera_platform_interface/test/types/camera_image_data_test.dart @@ -9,7 +9,7 @@ import 'package:flutter_test/flutter_test.dart'; void main() { test('CameraImageData can be created', () { debugDefaultTargetPlatformOverride = TargetPlatform.android; - final CameraImageData cameraImage = CameraImageData( + final cameraImage = CameraImageData( format: const CameraImageFormat(ImageFormatGroup.jpeg, raw: 42), height: 100, width: 200, diff --git a/packages/camera/camera_platform_interface/test/types/media_settings_test.dart b/packages/camera/camera_platform_interface/test/types/media_settings_test.dart index 4da938acc840..65f619b1673d 100644 --- a/packages/camera/camera_platform_interface/test/types/media_settings_test.dart +++ b/packages/camera/camera_platform_interface/test/types/media_settings_test.dart @@ -11,7 +11,7 @@ void main() { test( 'MediaSettings non-parametrized constructor should have correct initial values', () { - const MediaSettings settingsWithNoParameters = MediaSettings(); + const settingsWithNoParameters = MediaSettings(); expect( settingsWithNoParameters.resolutionPreset, @@ -50,7 +50,7 @@ void main() { ); test('MediaSettings fps should hold parameters', () { - const MediaSettings settings = MediaSettings( + const settings = MediaSettings( resolutionPreset: ResolutionPreset.low, fps: 20, videoBitrate: 128000, @@ -91,7 +91,7 @@ void main() { }); test('MediaSettings hash should be Object.hash of passed parameters', () { - const MediaSettings settings = MediaSettings( + const settings = MediaSettings( resolutionPreset: ResolutionPreset.low, fps: 20, videoBitrate: 128000, @@ -109,10 +109,10 @@ void main() { group('MediaSettings == operator', () { const ResolutionPreset preset1 = ResolutionPreset.low; - const int fps1 = 20; - const int videoBitrate1 = 128000; - const int audioBitrate1 = 32000; - const bool enableAudio1 = true; + const fps1 = 20; + const videoBitrate1 = 128000; + const audioBitrate1 = 32000; + const enableAudio1 = true; const ResolutionPreset preset2 = ResolutionPreset.high; const int fps2 = fps1 + 10; @@ -120,7 +120,7 @@ void main() { const int audioBitrate2 = audioBitrate1 * 2; const bool enableAudio2 = !enableAudio1; - const MediaSettings settings1 = MediaSettings( + const settings1 = MediaSettings( resolutionPreset: ResolutionPreset.low, fps: 20, videoBitrate: 128000, @@ -129,7 +129,7 @@ void main() { ); test('should compare resolutionPreset', () { - const MediaSettings settings2 = MediaSettings( + const settings2 = MediaSettings( resolutionPreset: preset2, fps: fps1, videoBitrate: videoBitrate1, @@ -141,7 +141,7 @@ void main() { }); test('should compare fps', () { - const MediaSettings settings2 = MediaSettings( + const settings2 = MediaSettings( resolutionPreset: preset1, fps: fps2, videoBitrate: videoBitrate1, @@ -153,7 +153,7 @@ void main() { }); test('should compare videoBitrate', () { - const MediaSettings settings2 = MediaSettings( + const settings2 = MediaSettings( resolutionPreset: preset1, fps: fps1, videoBitrate: videoBitrate2, @@ -165,7 +165,7 @@ void main() { }); test('should compare audioBitrate', () { - const MediaSettings settings2 = MediaSettings( + const settings2 = MediaSettings( resolutionPreset: preset1, fps: fps1, videoBitrate: videoBitrate1, @@ -177,7 +177,7 @@ void main() { }); test('should compare enableAudio', () { - const MediaSettings settings2 = MediaSettings( + const settings2 = MediaSettings( resolutionPreset: preset1, fps: fps1, videoBitrate: videoBitrate1, @@ -190,7 +190,7 @@ void main() { }); test('should return true when all parameters are equal', () { - const MediaSettings sameSettings = MediaSettings( + const sameSettings = MediaSettings( resolutionPreset: preset1, fps: fps1, videoBitrate: videoBitrate1, @@ -202,7 +202,7 @@ void main() { }); test('Identical objects should be equal', () { - const MediaSettings settingsIdentical = settings1; + const settingsIdentical = settings1; expect( settings1 == settingsIdentical, diff --git a/packages/camera/camera_web/CHANGELOG.md b/packages/camera/camera_web/CHANGELOG.md index 6fb3e44569c1..46d7958a8eb1 100644 --- a/packages/camera/camera_web/CHANGELOG.md +++ b/packages/camera/camera_web/CHANGELOG.md @@ -1,3 +1,17 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. + +## 0.3.5+3 + +* Fixes camera initialization failure on Safari by fixing a null check operator error using + a nullable getter and null safe practices. + +## 0.3.5+2 + +* Fixes camera initialization failure on Firefox Android by using `{video: true}` instead + of `{video: {}}` when no video constraints are specified. + ## 0.3.5+1 * Uses `CanvasRenderingContext2D.drawImage` instead of the deprecated `drawImageScaled`. diff --git a/packages/camera/camera_web/example/integration_test/camera_bitrate_test.dart b/packages/camera/camera_web/example/integration_test/camera_bitrate_test.dart index c6547ca28bf0..371f23d341b1 100644 --- a/packages/camera/camera_web/example/integration_test/camera_bitrate_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_bitrate_test.dart @@ -20,21 +20,21 @@ import 'helpers/helpers.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); - const Size videoSize = Size(320, 240); + const videoSize = Size(320, 240); /// Draw some seconds of random video frames on canvas in realtime. Future simulateCamera(HTMLCanvasElement canvasElement) async { - const int fps = 15; - const int seconds = 3; + const fps = 15; + const seconds = 3; const int frameDuration = 1000 ~/ fps; - final Random random = Random(0); + final random = Random(0); - for (int n = 0; n < fps * seconds; n++) { + for (var n = 0; n < fps * seconds; n++) { await Future.delayed(const Duration(milliseconds: frameDuration)); final int w = videoSize.width ~/ 20; final int h = videoSize.height ~/ 20; - for (int y = 0; y < videoSize.height; y += h) { - for (int x = 0; x < videoSize.width; x += w) { + for (var y = 0; y < videoSize.height; y += h) { + for (var x = 0; x < videoSize.width; x += w) { final int r = random.nextInt(255); final int g = random.nextInt(255); final int b = random.nextInt(255); @@ -49,36 +49,35 @@ void main() { WidgetTester tester, ) async { //const String supportedVideoType = 'video/webm'; - const String supportedVideoType = 'video/webm;codecs="vp9,opus"'; + const supportedVideoType = 'video/webm;codecs="vp9,opus"'; bool isVideoTypeSupported(String type) => type == supportedVideoType; Future recordVideo(int videoBitrate) async { - final MockWindow mockWindow = MockWindow(); - final MockNavigator mockNavigator = MockNavigator(); - final MockMediaDevices mockMediaDevices = MockMediaDevices(); - - final Window window = createJSInteropWrapper(mockWindow) as Window; - final Navigator navigator = - createJSInteropWrapper(mockNavigator) as Navigator; - final MediaDevices mediaDevices = + final mockWindow = MockWindow(); + final mockNavigator = MockNavigator(); + final mockMediaDevices = MockMediaDevices(); + + final window = createJSInteropWrapper(mockWindow) as Window; + final navigator = createJSInteropWrapper(mockNavigator) as Navigator; + final mediaDevices = createJSInteropWrapper(mockMediaDevices) as MediaDevices; mockWindow.navigator = navigator; mockNavigator.mediaDevices = mediaDevices; - final HTMLCanvasElement canvasElement = HTMLCanvasElement() + final canvasElement = HTMLCanvasElement() ..width = videoSize.width.toInt() ..height = videoSize.height.toInt() ..context2D.clearRect(0, 0, videoSize.width, videoSize.height); - final HTMLVideoElement videoElement = HTMLVideoElement(); + final videoElement = HTMLVideoElement(); - final MockCameraService cameraService = MockCameraService(); + final cameraService = MockCameraService(); CameraPlatform.instance = CameraPlugin(cameraService: cameraService) ..window = window; - final CameraOptions options = CameraOptions( + final options = CameraOptions( audio: const AudioConstraints(), video: VideoConstraints( width: VideoSizeConstraint(ideal: videoSize.width.toInt()), @@ -86,13 +85,13 @@ void main() { ), ); - final int cameraId = videoBitrate; + final cameraId = videoBitrate; when( cameraService.getMediaStreamForOptions(options, cameraId: cameraId), ).thenAnswer((_) async => canvasElement.captureStream()); - final Camera camera = Camera( + final camera = Camera( textureId: cameraId, cameraService: cameraService, options: options, @@ -125,7 +124,7 @@ void main() { return length; } - const int kilobits = 1024; + const kilobits = 1024; const int megabits = kilobits * kilobits; final int lengthSmall = await recordVideo(500 * kilobits); diff --git a/packages/camera/camera_web/example/integration_test/camera_options_test.dart b/packages/camera/camera_web/example/integration_test/camera_options_test.dart index c6e5740f0cbd..75d72107dd2b 100644 --- a/packages/camera/camera_web/example/integration_test/camera_options_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_options_test.dart @@ -14,7 +14,7 @@ void main() { group('CameraOptions', () { testWidgets('serializes correctly', (WidgetTester tester) async { - final CameraOptions cameraOptions = CameraOptions( + final cameraOptions = CameraOptions( audio: const AudioConstraints(enabled: true), video: VideoConstraints( facingMode: FacingModeConstraint.exact(CameraType.user), @@ -90,7 +90,7 @@ void main() { group('VideoConstraints', () { testWidgets('serializes correctly', (WidgetTester tester) async { - final VideoConstraints videoConstraints = VideoConstraints( + final videoConstraints = VideoConstraints( facingMode: FacingModeConstraint.exact(CameraType.user), width: const VideoSizeConstraint(ideal: 100, maximum: 100), height: const VideoSizeConstraint(ideal: 50, maximum: 50), @@ -108,6 +108,13 @@ void main() { ); }); + testWidgets('serializes to true when no constraints are provided', ( + WidgetTester tester, + ) async { + const videoConstraints = VideoConstraints(); + expect(videoConstraints.toMediaStreamConstraints().dartify(), isTrue); + }); + testWidgets('supports value equality', (WidgetTester tester) async { expect( VideoConstraints( diff --git a/packages/camera/camera_web/example/integration_test/camera_service_test.dart b/packages/camera/camera_web/example/integration_test/camera_service_test.dart index 485fcac55084..2805ae069350 100644 --- a/packages/camera/camera_web/example/integration_test/camera_service_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_service_test.dart @@ -23,7 +23,7 @@ void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('CameraService', () { - const int cameraId = 1; + const cameraId = 1; late MockWindow mockWindow; late MockNavigator mockNavigator; @@ -70,13 +70,13 @@ void main() { mockMediaDevices .getUserMedia = ([web.MediaStreamConstraints? constraints]) { capturedConstraints = constraints; - final web.MediaStream stream = + final stream = createJSInteropWrapper(FakeMediaStream([])) as web.MediaStream; return Future.value(stream).toJS; }.toJS; - final CameraOptions options = CameraOptions( + final options = CameraOptions( video: VideoConstraints( facingMode: FacingModeConstraint.exact(CameraType.user), width: const VideoSizeConstraint(ideal: 200), @@ -708,6 +708,29 @@ void main() { expect(facingMode, isNull); }); + + testWidgets('returns null ' + 'when the facing mode setting is empty and ' + 'the facingMode capability is null', (WidgetTester tester) async { + mockVideoTrack.getSettings = () { + return createJSInteropWrapper(FakeMediaTrackSettings()) + as web.MediaTrackSettings; + }.toJS; + mockVideoTrack.getCapabilities = () { + return createJSInteropWrapper(FakeMediaTrackCapabilities()) + as web.MediaTrackCapabilities; + }.toJS; + + when( + jsUtil.hasProperty(videoTrack, 'getCapabilities'.toJS), + ).thenReturn(true); + + final String? facingMode = cameraService.getFacingModeForVideoTrack( + videoTrack, + ); + + expect(facingMode, isNull); + }); }); }); diff --git a/packages/camera/camera_web/example/integration_test/camera_test.dart b/packages/camera/camera_web/example/integration_test/camera_test.dart index 69e0e55c8d35..29af6ceddbd9 100644 --- a/packages/camera/camera_web/example/integration_test/camera_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_test.dart @@ -23,7 +23,7 @@ void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('Camera', () { - const int textureId = 1; + const textureId = 1; late MockWindow mockWindow; late MockNavigator mockNavigator; @@ -66,14 +66,14 @@ void main() { group('initialize', () { testWidgets('calls CameraService.getMediaStreamForOptions ' 'with provided options', (WidgetTester tester) async { - final CameraOptions options = CameraOptions( + final options = CameraOptions( video: VideoConstraints( facingMode: FacingModeConstraint.exact(CameraType.user), width: const VideoSizeConstraint(ideal: 200), ), ); - final Camera camera = Camera( + final camera = Camera( textureId: textureId, options: options, cameraService: cameraService, @@ -88,14 +88,12 @@ void main() { testWidgets('creates a video element ' 'with correct properties', (WidgetTester tester) async { - const AudioConstraints audioConstraints = AudioConstraints( - enabled: true, - ); - final VideoConstraints videoConstraints = VideoConstraints( + const audioConstraints = AudioConstraints(enabled: true); + final videoConstraints = VideoConstraints( facingMode: FacingModeConstraint(CameraType.user), ); - final Camera camera = Camera( + final camera = Camera( textureId: textureId, options: CameraOptions( audio: audioConstraints, @@ -127,11 +125,11 @@ void main() { testWidgets('flips the video element horizontally ' 'for a back camera', (WidgetTester tester) async { - final VideoConstraints videoConstraints = VideoConstraints( + final videoConstraints = VideoConstraints( facingMode: FacingModeConstraint(CameraType.environment), ); - final Camera camera = Camera( + final camera = Camera( textureId: textureId, options: CameraOptions(video: videoConstraints), cameraService: cameraService, @@ -144,7 +142,7 @@ void main() { testWidgets('creates a wrapping div element ' 'with correct properties', (WidgetTester tester) async { - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, ); @@ -153,7 +151,7 @@ void main() { expect(camera.divElement, isNotNull); expect(camera.divElement.style.objectFit, equals('cover')); - final JSArray? array = + final array = (globalContext['Array']! as JSObject).callMethod( 'from'.toJS, camera.divElement.children, @@ -163,7 +161,7 @@ void main() { }); testWidgets('initializes the camera stream', (WidgetTester tester) async { - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, ); @@ -177,9 +175,7 @@ void main() { 'when CameraService.getMediaStreamForOptions throws', ( WidgetTester tester, ) async { - final Exception exception = Exception( - 'A media stream exception occured.', - ); + final exception = Exception('A media stream exception occured.'); when( cameraService.getMediaStreamForOptions( @@ -188,7 +184,7 @@ void main() { ), ).thenThrow(exception); - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, ); @@ -201,9 +197,9 @@ void main() { testWidgets('starts playing the video element', ( WidgetTester tester, ) async { - bool startedPlaying = false; + var startedPlaying = false; - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, ); @@ -225,11 +221,11 @@ void main() { testWidgets('initializes the camera stream ' 'from CameraService.getMediaStreamForOptions ' 'if it does not exist', (WidgetTester tester) async { - const CameraOptions options = CameraOptions( + const options = CameraOptions( video: VideoConstraints(width: VideoSizeConstraint(ideal: 100)), ); - final Camera camera = Camera( + final camera = Camera( textureId: textureId, options: options, cameraService: cameraService, @@ -255,7 +251,7 @@ void main() { group('pause', () { testWidgets('pauses the camera stream', (WidgetTester tester) async { - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, ); @@ -273,7 +269,7 @@ void main() { group('stop', () { testWidgets('resets the camera stream', (WidgetTester tester) async { - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, ); @@ -290,7 +286,7 @@ void main() { group('takePicture', () { testWidgets('returns a captured picture', (WidgetTester tester) async { - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, ); @@ -329,7 +325,7 @@ void main() { }); testWidgets('if the flash mode is auto', (WidgetTester tester) async { - final Camera camera = + final camera = Camera(textureId: textureId, cameraService: cameraService) ..window = window ..stream = videoStream @@ -338,8 +334,7 @@ void main() { await camera.play(); - final List capturedConstraints = - []; + final capturedConstraints = []; mockVideoTrack.applyConstraints = ([MediaTrackConstraints? constraints]) { if (constraints != null) { @@ -356,7 +351,7 @@ void main() { }); testWidgets('if the flash mode is always', (WidgetTester tester) async { - final Camera camera = + final camera = Camera(textureId: textureId, cameraService: cameraService) ..window = window ..stream = videoStream @@ -365,8 +360,7 @@ void main() { await camera.play(); - final List capturedConstraints = - []; + final capturedConstraints = []; mockVideoTrack.applyConstraints = ([MediaTrackConstraints? constraints]) { if (constraints != null) { @@ -389,14 +383,14 @@ void main() { 'based on the first video track settings', ( WidgetTester tester, ) async { - const Size videoSize = Size(1280, 720); + const videoSize = Size(1280, 720); final HTMLVideoElement videoElement = getVideoElementWithBlankStream( videoSize, ); mediaStream = videoElement.captureStream(); - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, ); @@ -409,10 +403,10 @@ void main() { testWidgets('returns Size.zero ' 'if the camera is missing video tracks', (WidgetTester tester) async { // Create a video stream with no video tracks. - final HTMLVideoElement videoElement = HTMLVideoElement(); + final videoElement = HTMLVideoElement(); mediaStream = videoElement.captureStream(); - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, ); @@ -456,7 +450,7 @@ void main() { return MediaTrackCapabilities(torch: [true.toJS].toJS); }.toJS; - final Camera camera = + final camera = Camera(textureId: textureId, cameraService: cameraService) ..window = window ..stream = videoStream; @@ -478,13 +472,12 @@ void main() { return MediaTrackCapabilities(torch: [true.toJS].toJS); }.toJS; - final Camera camera = + final camera = Camera(textureId: textureId, cameraService: cameraService) ..window = window ..stream = videoStream; - final List capturedConstraints = - []; + final capturedConstraints = []; mockVideoTrack.applyConstraints = ([MediaTrackConstraints? constraints]) { if (constraints != null) { @@ -509,13 +502,12 @@ void main() { return MediaTrackCapabilities(torch: [true.toJS].toJS); }.toJS; - final Camera camera = + final camera = Camera(textureId: textureId, cameraService: cameraService) ..window = window ..stream = videoStream; - final List capturedConstraints = - []; + final capturedConstraints = []; mockVideoTrack.applyConstraints = ([MediaTrackConstraints? constraints]) { if (constraints != null) { @@ -542,7 +534,7 @@ void main() { return MediaTrackCapabilities(torch: [true.toJS].toJS); }.toJS; - final Camera camera = + final camera = Camera(textureId: textureId, cameraService: cameraService) ..window = window ..stream = videoStream; @@ -576,7 +568,7 @@ void main() { return MediaTrackCapabilities(torch: [false.toJS].toJS); }.toJS; - final Camera camera = + final camera = Camera(textureId: textureId, cameraService: cameraService) ..window = window ..stream = videoStream; @@ -611,7 +603,7 @@ void main() { return MediaTrackCapabilities(torch: [true.toJS].toJS); }.toJS; - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, )..window = window; @@ -642,12 +634,12 @@ void main() { 'from CameraService.getZoomLevelCapabilityForCamera', ( WidgetTester tester, ) async { - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, ); - final ZoomLevelCapability zoomLevelCapability = ZoomLevelCapability( + final zoomLevelCapability = ZoomLevelCapability( minimum: 50.0, maximum: 100.0, videoTrack: @@ -674,12 +666,12 @@ void main() { 'from CameraService.getZoomLevelCapabilityForCamera', ( WidgetTester tester, ) async { - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, ); - final ZoomLevelCapability zoomLevelCapability = ZoomLevelCapability( + final zoomLevelCapability = ZoomLevelCapability( minimum: 50.0, maximum: 100.0, videoTrack: @@ -706,23 +698,22 @@ void main() { 'from CameraService.getZoomLevelCapabilityForCamera', ( WidgetTester tester, ) async { - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, ); - final MockMediaStreamTrack mockVideoTrack = MockMediaStreamTrack(); - final MediaStreamTrack videoTrack = + final mockVideoTrack = MockMediaStreamTrack(); + final videoTrack = createJSInteropWrapper(mockVideoTrack) as MediaStreamTrack; - final ZoomLevelCapability zoomLevelCapability = ZoomLevelCapability( + final zoomLevelCapability = ZoomLevelCapability( minimum: 50.0, maximum: 100.0, videoTrack: videoTrack, ); - final List capturedConstraints = - []; + final capturedConstraints = []; mockVideoTrack.applyConstraints = ([MediaTrackConstraints? constraints]) { if (constraints != null) { @@ -735,7 +726,7 @@ void main() { cameraService.getZoomLevelCapabilityForCamera(camera), ).thenReturn(zoomLevelCapability); - const double zoom = 75.0; + const zoom = 75.0; camera.setZoomLevel(zoom); @@ -748,12 +739,12 @@ void main() { 'when the provided zoom level is below minimum', ( WidgetTester tester, ) async { - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, ); - final ZoomLevelCapability zoomLevelCapability = ZoomLevelCapability( + final zoomLevelCapability = ZoomLevelCapability( minimum: 50.0, maximum: 100.0, videoTrack: @@ -787,12 +778,12 @@ void main() { 'when the provided zoom level is below minimum', ( WidgetTester tester, ) async { - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, ); - final ZoomLevelCapability zoomLevelCapability = ZoomLevelCapability( + final zoomLevelCapability = ZoomLevelCapability( minimum: 50.0, maximum: 100.0, videoTrack: @@ -830,16 +821,16 @@ void main() { 'based on the first video track settings', ( WidgetTester tester, ) async { - final MockVideoElement mockVideoElement = MockVideoElement(); - final HTMLVideoElement videoElement = + final mockVideoElement = MockVideoElement(); + final videoElement = createJSInteropWrapper(mockVideoElement) as HTMLVideoElement; - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, )..videoElement = videoElement; - final MockMediaStreamTrack firstVideoTrack = MockMediaStreamTrack(); + final firstVideoTrack = MockMediaStreamTrack(); mockVideoElement.srcObject = createJSInteropWrapper( @@ -866,16 +857,16 @@ void main() { 'if the first video track is missing the facing mode', ( WidgetTester tester, ) async { - final MockVideoElement mockVideoElement = MockVideoElement(); - final HTMLVideoElement videoElement = + final mockVideoElement = MockVideoElement(); + final videoElement = createJSInteropWrapper(mockVideoElement) as HTMLVideoElement; - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, )..videoElement = videoElement; - final MockMediaStreamTrack firstVideoTrack = MockMediaStreamTrack(); + final firstVideoTrack = MockMediaStreamTrack(); videoElement.srcObject = createJSInteropWrapper( @@ -897,10 +888,10 @@ void main() { testWidgets('returns null ' 'if the camera is missing video tracks', (WidgetTester tester) async { // Create a video stream with no video tracks. - final HTMLVideoElement videoElement = HTMLVideoElement(); + final videoElement = HTMLVideoElement(); mediaStream = videoElement.captureStream(); - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, ); @@ -913,7 +904,7 @@ void main() { group('getViewType', () { testWidgets('returns a correct view type', (WidgetTester tester) async { - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, ); @@ -928,7 +919,7 @@ void main() { }); group('video recording', () { - const String supportedVideoType = 'video/webm'; + const supportedVideoType = 'video/webm'; late MockMediaRecorder mockMediaRecorder; late MediaRecorder mediaRecorder; @@ -944,10 +935,8 @@ void main() { group('startVideoRecording', () { testWidgets('creates a media recorder ' 'with appropriate options', (WidgetTester tester) async { - final Camera camera = Camera( - textureId: 1, - cameraService: cameraService, - )..isVideoTypeSupported = isVideoTypeSupported; + final camera = Camera(textureId: 1, cameraService: cameraService) + ..isVideoTypeSupported = isVideoTypeSupported; await camera.initialize(); await camera.play(); @@ -964,15 +953,14 @@ void main() { testWidgets('listens to the media recorder data events', ( WidgetTester tester, ) async { - final Camera camera = - Camera(textureId: 1, cameraService: cameraService) - ..mediaRecorder = mediaRecorder - ..isVideoTypeSupported = isVideoTypeSupported; + final camera = Camera(textureId: 1, cameraService: cameraService) + ..mediaRecorder = mediaRecorder + ..isVideoTypeSupported = isVideoTypeSupported; await camera.initialize(); await camera.play(); - final List capturedEvents = []; + final capturedEvents = []; mockMediaRecorder.addEventListener = (String type, EventListener? callback, [JSAny? options]) { capturedEvents.add(type); @@ -989,15 +977,14 @@ void main() { testWidgets('listens to the media recorder stop events', ( WidgetTester tester, ) async { - final Camera camera = - Camera(textureId: 1, cameraService: cameraService) - ..mediaRecorder = mediaRecorder - ..isVideoTypeSupported = isVideoTypeSupported; + final camera = Camera(textureId: 1, cameraService: cameraService) + ..mediaRecorder = mediaRecorder + ..isVideoTypeSupported = isVideoTypeSupported; await camera.initialize(); await camera.play(); - final List capturedEvents = []; + final capturedEvents = []; mockMediaRecorder.addEventListener = (String type, EventListener? callback, [JSAny? options]) { capturedEvents.add(type); @@ -1009,15 +996,14 @@ void main() { }); testWidgets('starts a video recording', (WidgetTester tester) async { - final Camera camera = - Camera(textureId: 1, cameraService: cameraService) - ..mediaRecorder = mediaRecorder - ..isVideoTypeSupported = isVideoTypeSupported; + final camera = Camera(textureId: 1, cameraService: cameraService) + ..mediaRecorder = mediaRecorder + ..isVideoTypeSupported = isVideoTypeSupported; await camera.initialize(); await camera.play(); - final List capturedStarts = []; + final capturedStarts = []; mockMediaRecorder.start = ([int? timeslice]) { capturedStarts.add(timeslice); }.toJS; @@ -1030,10 +1016,8 @@ void main() { group('throws a CameraWebException', () { testWidgets('with notSupported error ' 'when no video types are supported', (WidgetTester tester) async { - final Camera camera = Camera( - textureId: 1, - cameraService: cameraService, - )..isVideoTypeSupported = (String type) => false; + final camera = Camera(textureId: 1, cameraService: cameraService) + ..isVideoTypeSupported = (String type) => false; await camera.initialize(); await camera.play(); @@ -1060,12 +1044,10 @@ void main() { group('pauseVideoRecording', () { testWidgets('pauses a video recording', (WidgetTester tester) async { - final Camera camera = Camera( - textureId: 1, - cameraService: cameraService, - )..mediaRecorder = mediaRecorder; + final camera = Camera(textureId: 1, cameraService: cameraService) + ..mediaRecorder = mediaRecorder; - int pauses = 0; + var pauses = 0; mockMediaRecorder.pause = () { pauses++; }.toJS; @@ -1080,10 +1062,7 @@ void main() { 'if the video recording was not started', ( WidgetTester tester, ) async { - final Camera camera = Camera( - textureId: 1, - cameraService: cameraService, - ); + final camera = Camera(textureId: 1, cameraService: cameraService); expect( camera.pauseVideoRecording, @@ -1106,12 +1085,10 @@ void main() { group('resumeVideoRecording', () { testWidgets('resumes a video recording', (WidgetTester tester) async { - final Camera camera = Camera( - textureId: 1, - cameraService: cameraService, - )..mediaRecorder = mediaRecorder; + final camera = Camera(textureId: 1, cameraService: cameraService) + ..mediaRecorder = mediaRecorder; - int resumes = 0; + var resumes = 0; mockMediaRecorder.resume = () { resumes++; }.toJS; @@ -1126,10 +1103,7 @@ void main() { 'if the video recording was not started', ( WidgetTester tester, ) async { - final Camera camera = Camera( - textureId: 1, - cameraService: cameraService, - ); + final camera = Camera(textureId: 1, cameraService: cameraService); expect( camera.resumeVideoRecording, @@ -1154,10 +1128,9 @@ void main() { testWidgets('stops a video recording and ' 'returns the captured file ' 'based on all video data parts', (WidgetTester tester) async { - final Camera camera = - Camera(textureId: 1, cameraService: cameraService) - ..mediaRecorder = mediaRecorder - ..isVideoTypeSupported = isVideoTypeSupported; + final camera = Camera(textureId: 1, cameraService: cameraService) + ..mediaRecorder = mediaRecorder + ..isVideoTypeSupported = isVideoTypeSupported; await camera.initialize(); await camera.play(); @@ -1184,17 +1157,17 @@ void main() { await camera.startVideoRecording(); - int stops = 0; + var stops = 0; mockMediaRecorder.stop = () { stops++; }.toJS; final Future videoFileFuture = camera.stopVideoRecording(); - final Blob capturedVideoPartOne = Blob([].toJS); - final Blob capturedVideoPartTwo = Blob([].toJS); + final capturedVideoPartOne = Blob([].toJS); + final capturedVideoPartTwo = Blob([].toJS); - final List capturedVideoParts = [ + final capturedVideoParts = [ capturedVideoPartOne, capturedVideoPartTwo, ]; @@ -1230,10 +1203,7 @@ void main() { 'if the video recording was not started', ( WidgetTester tester, ) async { - final Camera camera = Camera( - textureId: 1, - cameraService: cameraService, - ); + final camera = Camera(textureId: 1, cameraService: cameraService); expect( camera.stopVideoRecording, @@ -1269,17 +1239,16 @@ void main() { testWidgets('stops listening to the media recorder data events', ( WidgetTester tester, ) async { - final Camera camera = - Camera(textureId: 1, cameraService: cameraService) - ..mediaRecorder = mediaRecorder - ..isVideoTypeSupported = isVideoTypeSupported; + final camera = Camera(textureId: 1, cameraService: cameraService) + ..mediaRecorder = mediaRecorder + ..isVideoTypeSupported = isVideoTypeSupported; await camera.initialize(); await camera.play(); await camera.startVideoRecording(); - final List capturedEvents = []; + final capturedEvents = []; mockMediaRecorder.removeEventListener = (String type, EventListener? callback, [JSAny? options]) { capturedEvents.add(type); @@ -1298,17 +1267,16 @@ void main() { testWidgets('stops listening to the media recorder stop events', ( WidgetTester tester, ) async { - final Camera camera = - Camera(textureId: 1, cameraService: cameraService) - ..mediaRecorder = mediaRecorder - ..isVideoTypeSupported = isVideoTypeSupported; + final camera = Camera(textureId: 1, cameraService: cameraService) + ..mediaRecorder = mediaRecorder + ..isVideoTypeSupported = isVideoTypeSupported; await camera.initialize(); await camera.play(); await camera.startVideoRecording(); - final List capturedEvents = []; + final capturedEvents = []; mockMediaRecorder.removeEventListener = (String type, EventListener? callback, [JSAny? options]) { capturedEvents.add(type); @@ -1324,16 +1292,13 @@ void main() { testWidgets('stops listening to the media recorder errors', ( WidgetTester tester, ) async { - final StreamController onErrorStreamController = - StreamController(); - final MockEventStreamProvider provider = - MockEventStreamProvider(); + final onErrorStreamController = StreamController(); + final provider = MockEventStreamProvider(); - final Camera camera = - Camera(textureId: 1, cameraService: cameraService) - ..mediaRecorder = mediaRecorder - ..isVideoTypeSupported = isVideoTypeSupported - ..mediaRecorderOnErrorProvider = provider; + final camera = Camera(textureId: 1, cameraService: cameraService) + ..mediaRecorder = mediaRecorder + ..isVideoTypeSupported = isVideoTypeSupported + ..mediaRecorderOnErrorProvider = provider; when( provider.forTarget(mediaRecorder), @@ -1357,7 +1322,7 @@ void main() { testWidgets("resets the video element's source", ( WidgetTester tester, ) async { - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, ); @@ -1369,7 +1334,7 @@ void main() { }); testWidgets('closes the onEnded stream', (WidgetTester tester) async { - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, ); @@ -1383,7 +1348,7 @@ void main() { testWidgets('closes the onVideoRecordedEvent stream', ( WidgetTester tester, ) async { - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, ); @@ -1397,7 +1362,7 @@ void main() { testWidgets('closes the onVideoRecordingError stream', ( WidgetTester tester, ) async { - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, ); @@ -1413,16 +1378,15 @@ void main() { group('onVideoRecordedEvent', () { testWidgets('emits a VideoRecordedEvent ' 'when a video recording is created', (WidgetTester tester) async { - const String supportedVideoType = 'video/webm'; + const supportedVideoType = 'video/webm'; - final MockMediaRecorder mockMediaRecorder = MockMediaRecorder(); - final MediaRecorder mediaRecorder = + final mockMediaRecorder = MockMediaRecorder(); + final mediaRecorder = createJSInteropWrapper(mockMediaRecorder) as MediaRecorder; - final Camera camera = - Camera(textureId: 1, cameraService: cameraService) - ..mediaRecorder = mediaRecorder - ..isVideoTypeSupported = (String type) => type == 'video/webm'; + final camera = Camera(textureId: 1, cameraService: cameraService) + ..mediaRecorder = mediaRecorder + ..isVideoTypeSupported = (String type) => type == 'video/webm'; await camera.initialize(); await camera.play(); @@ -1439,8 +1403,9 @@ void main() { } }.toJS; - final StreamQueue streamQueue = - StreamQueue(camera.onVideoRecordedEvent); + final streamQueue = StreamQueue( + camera.onVideoRecordedEvent, + ); await camera.startVideoRecording(); @@ -1490,13 +1455,12 @@ void main() { group('onEnded', () { testWidgets('emits the default video track ' 'when it emits an ended event', (WidgetTester tester) async { - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, ); - final StreamQueue streamQueue = - StreamQueue(camera.onEnded); + final streamQueue = StreamQueue(camera.onEnded); await camera.initialize(); @@ -1514,13 +1478,12 @@ void main() { testWidgets('emits the default video track ' 'when the camera is stopped', (WidgetTester tester) async { - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: cameraService, ); - final StreamQueue streamQueue = - StreamQueue(camera.onEnded); + final streamQueue = StreamQueue(camera.onEnded); await camera.initialize(); @@ -1541,15 +1504,13 @@ void main() { testWidgets('emits an ErrorEvent ' 'when the media recorder fails ' 'when recording a video', (WidgetTester tester) async { - final MockMediaRecorder mockMediaRecorder = MockMediaRecorder(); - final MediaRecorder mediaRecorder = + final mockMediaRecorder = MockMediaRecorder(); + final mediaRecorder = createJSInteropWrapper(mockMediaRecorder) as MediaRecorder; - final StreamController errorController = - StreamController(); - final MockEventStreamProvider provider = - MockEventStreamProvider(); + final errorController = StreamController(); + final provider = MockEventStreamProvider(); - final Camera camera = + final camera = Camera(textureId: textureId, cameraService: cameraService) ..mediaRecorder = mediaRecorder ..mediaRecorderOnErrorProvider = provider; @@ -1558,7 +1519,7 @@ void main() { provider.forTarget(mediaRecorder), ).thenAnswer((_) => errorController.stream); - final StreamQueue streamQueue = StreamQueue( + final streamQueue = StreamQueue( camera.onVideoRecordingError, ); @@ -1567,7 +1528,7 @@ void main() { await camera.startVideoRecording(); - final ErrorEvent errorEvent = ErrorEvent('type'); + final errorEvent = ErrorEvent('type'); errorController.add(errorEvent); expect(await streamQueue.next, equals(errorEvent)); diff --git a/packages/camera/camera_web/example/integration_test/camera_web_exception_test.dart b/packages/camera/camera_web/example/integration_test/camera_web_exception_test.dart index 7ae645f164ef..8bc9469510b1 100644 --- a/packages/camera/camera_web/example/integration_test/camera_web_exception_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_web_exception_test.dart @@ -12,15 +12,11 @@ void main() { group('CameraWebException', () { testWidgets('sets all properties', (WidgetTester tester) async { - const int cameraId = 1; + const cameraId = 1; const CameraErrorCode code = CameraErrorCode.notFound; - const String description = 'The camera is not found.'; + const description = 'The camera is not found.'; - final CameraWebException exception = CameraWebException( - cameraId, - code, - description, - ); + final exception = CameraWebException(cameraId, code, description); expect(exception.cameraId, equals(cameraId)); expect(exception.code, equals(code)); @@ -30,15 +26,11 @@ void main() { testWidgets('toString includes all properties', ( WidgetTester tester, ) async { - const int cameraId = 2; + const cameraId = 2; const CameraErrorCode code = CameraErrorCode.notReadable; - const String description = 'The camera is not readable.'; + const description = 'The camera is not readable.'; - final CameraWebException exception = CameraWebException( - cameraId, - code, - description, - ); + final exception = CameraWebException(cameraId, code, description); expect( exception.toString(), diff --git a/packages/camera/camera_web/example/integration_test/camera_web_test.dart b/packages/camera/camera_web/example/integration_test/camera_web_test.dart index 78e2f24dc5a9..5542bac34ec0 100644 --- a/packages/camera/camera_web/example/integration_test/camera_web_test.dart +++ b/packages/camera/camera_web/example/integration_test/camera_web_test.dart @@ -27,7 +27,7 @@ void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('CameraPlugin', () { - const int cameraId = 1; + const cameraId = 1; late MockWindow mockWindow; late MockNavigator mockNavigator; @@ -127,11 +127,11 @@ void main() { testWidgets('releases the camera stream ' 'used to request video permissions', (WidgetTester tester) async { - final MockMediaStreamTrack mockVideoTrack = MockMediaStreamTrack(); - final MediaStreamTrack videoTrack = + final mockVideoTrack = MockMediaStreamTrack(); + final videoTrack = createJSInteropWrapper(mockVideoTrack) as MediaStreamTrack; - bool videoTrackStopped = false; + var videoTrackStopped = false; mockVideoTrack.stop = () { videoTrackStopped = true; }.toJS; @@ -155,7 +155,7 @@ void main() { testWidgets('gets a video stream ' 'for a video input device', (WidgetTester tester) async { - final MediaDeviceInfo videoDevice = + final videoDevice = createJSInteropWrapper( FakeMediaDeviceInfo( '1', @@ -186,7 +186,7 @@ void main() { testWidgets('does not get a video stream ' 'for the video input device ' 'with an empty device id', (WidgetTester tester) async { - final MediaDeviceInfo videoDevice = + final videoDevice = createJSInteropWrapper( FakeMediaDeviceInfo( '', @@ -217,7 +217,7 @@ void main() { testWidgets('gets the facing mode ' 'from the first available video track ' 'of the video input device', (WidgetTester tester) async { - final MediaDeviceInfo videoDevice = + final videoDevice = createJSInteropWrapper( FakeMediaDeviceInfo( '1', @@ -227,7 +227,7 @@ void main() { ) as MediaDeviceInfo; - final MediaStream videoStream = + final videoStream = createJSInteropWrapper( FakeMediaStream([ createJSInteropWrapper(MockMediaStreamTrack()) @@ -265,7 +265,7 @@ void main() { testWidgets('returns appropriate camera descriptions ' 'for multiple video devices ' 'based on video streams', (WidgetTester tester) async { - final MediaDeviceInfo firstVideoDevice = + final firstVideoDevice = createJSInteropWrapper( FakeMediaDeviceInfo( '1', @@ -275,7 +275,7 @@ void main() { ) as MediaDeviceInfo; - final MediaDeviceInfo secondVideoDevice = + final secondVideoDevice = createJSInteropWrapper( FakeMediaDeviceInfo( '4', @@ -286,7 +286,7 @@ void main() { as MediaDeviceInfo; // Create a video stream for the first video device. - final MediaStream firstVideoStream = + final firstVideoStream = createJSInteropWrapper( FakeMediaStream([ createJSInteropWrapper(MockMediaStreamTrack()) @@ -298,7 +298,7 @@ void main() { as MediaStream; // Create a video stream for the second video device. - final MediaStream secondVideoStream = + final secondVideoStream = createJSInteropWrapper( FakeMediaStream([ createJSInteropWrapper(MockMediaStreamTrack()) @@ -401,7 +401,7 @@ void main() { testWidgets('sets camera metadata ' 'for the camera description', (WidgetTester tester) async { - final MediaDeviceInfo videoDevice = + final videoDevice = createJSInteropWrapper( FakeMediaDeviceInfo( '1', @@ -411,7 +411,7 @@ void main() { ) as MediaDeviceInfo; - final MediaStream videoStream = + final videoStream = createJSInteropWrapper( FakeMediaStream([ createJSInteropWrapper(MockMediaStreamTrack()) @@ -462,7 +462,7 @@ void main() { testWidgets('releases the video stream ' 'of a video input device', (WidgetTester tester) async { - final MediaDeviceInfo videoDevice = + final videoDevice = createJSInteropWrapper( FakeMediaDeviceInfo( '1', @@ -472,17 +472,17 @@ void main() { ) as MediaDeviceInfo; - final List tracks = []; - final List stops = List.generate(2, (_) => false); - for (int i = 0; i < stops.length; i++) { - final MockMediaStreamTrack track = MockMediaStreamTrack(); + final tracks = []; + final stops = List.generate(2, (_) => false); + for (var i = 0; i < stops.length; i++) { + final track = MockMediaStreamTrack(); track.stop = () { stops[i] = true; }.toJS; tracks.add(createJSInteropWrapper(track) as MediaStreamTrack); } - final MediaStream videoStream = + final videoStream = createJSInteropWrapper(FakeMediaStream(tracks)) as MediaStream; mockMediaDevices.enumerateDevices = () { @@ -509,7 +509,7 @@ void main() { testWidgets('when MediaDevices.enumerateDevices throws DomException', ( WidgetTester tester, ) async { - final DOMException exception = DOMException('UnknownError'); + final exception = DOMException('UnknownError'); mockMediaDevices.enumerateDevices = () { throw exception; @@ -533,7 +533,7 @@ void main() { testWidgets('when CameraService.getMediaStreamForOptions ' 'throws CameraWebException', (WidgetTester tester) async { - final CameraWebException exception = CameraWebException( + final exception = CameraWebException( cameraId, CameraErrorCode.security, 'description', @@ -557,7 +557,7 @@ void main() { testWidgets('when CameraService.getMediaStreamForOptions ' 'throws PlatformException', (WidgetTester tester) async { - final PlatformException exception = PlatformException( + final exception = PlatformException( code: CameraErrorCode.notSupported.toString(), message: 'message', ); @@ -582,16 +582,16 @@ void main() { group('createCamera', () { group('creates a camera', () { - const Size ultraHighResolutionSize = Size(3840, 2160); - const Size maxResolutionSize = Size(3840, 2160); + const ultraHighResolutionSize = Size(3840, 2160); + const maxResolutionSize = Size(3840, 2160); - const CameraDescription cameraDescription = CameraDescription( + const cameraDescription = CameraDescription( name: 'name', lensDirection: CameraLensDirection.front, sensorOrientation: 0, ); - const CameraMetadata cameraMetadata = CameraMetadata( + const cameraMetadata = CameraMetadata( deviceId: 'deviceId', facingMode: 'user', ); @@ -824,10 +824,8 @@ void main() { when(camera.videoElement).thenReturn(videoElement); - final MockEventStreamProvider errorProvider = - MockEventStreamProvider(); - final MockEventStreamProvider abortProvider = - MockEventStreamProvider(); + final errorProvider = MockEventStreamProvider(); + final abortProvider = MockEventStreamProvider(); (CameraPlatform.instance as CameraPlugin).videoElementOnErrorProvider = errorProvider; @@ -903,7 +901,7 @@ void main() { testWidgets('when camera throws CameraWebException', ( WidgetTester tester, ) async { - final CameraWebException exception = CameraWebException( + final exception = CameraWebException( cameraId, CameraErrorCode.permissionDenied, 'description', @@ -929,7 +927,7 @@ void main() { testWidgets('when camera throws DomException', ( WidgetTester tester, ) async { - final DOMException exception = DOMException('NotAllowedError'); + final exception = DOMException('NotAllowedError'); when(camera.initialize()).thenAnswer((_) => Future.value()); when(camera.play()).thenThrow(exception); @@ -960,7 +958,7 @@ void main() { testWidgets('requests full-screen mode ' 'on documentElement', (WidgetTester tester) async { - int fullscreenCalls = 0; + var fullscreenCalls = 0; mockDocumentElement.requestFullscreen = ([FullscreenOptions? options]) { fullscreenCalls++; return Future.value().toJS; @@ -982,7 +980,7 @@ void main() { ), ).thenReturn(OrientationType.landscapeSecondary); - final List capturedTypes = []; + final capturedTypes = []; mockScreenOrientation.lock = (OrientationLockType orientation) { capturedTypes.add(orientation); return Future.value().toJS; @@ -1030,7 +1028,7 @@ void main() { testWidgets('when lock throws DomException', ( WidgetTester tester, ) async { - final DOMException exception = DOMException('NotAllowedError'); + final exception = DOMException('NotAllowedError'); mockScreenOrientation.lock = (OrientationLockType orientation) { throw exception; @@ -1065,7 +1063,7 @@ void main() { testWidgets('unlocks the capture orientation', ( WidgetTester tester, ) async { - int unlocks = 0; + var unlocks = 0; mockScreenOrientation.unlock = () { unlocks++; }.toJS; @@ -1099,7 +1097,7 @@ void main() { testWidgets('when unlock throws DomException', ( WidgetTester tester, ) async { - final DOMException exception = DOMException('NotAllowedError'); + final exception = DOMException('NotAllowedError'); mockScreenOrientation.unlock = () { throw exception; @@ -1123,8 +1121,8 @@ void main() { group('takePicture', () { testWidgets('captures a picture', (WidgetTester tester) async { - final MockCamera camera = MockCamera(); - final XFile capturedPicture = XFile('/bogus/test'); + final camera = MockCamera(); + final capturedPicture = XFile('/bogus/test'); when(camera.takePicture()).thenAnswer((_) async => capturedPicture); @@ -1158,8 +1156,8 @@ void main() { testWidgets('when takePicture throws DomException', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final DOMException exception = DOMException('NotSupportedError'); + final camera = MockCamera(); + final exception = DOMException('NotSupportedError'); when(camera.takePicture()).thenThrow(exception); @@ -1181,8 +1179,8 @@ void main() { testWidgets('when takePicture throws CameraWebException', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final CameraWebException exception = CameraWebException( + final camera = MockCamera(); + final exception = CameraWebException( cameraId, CameraErrorCode.notStarted, 'description', @@ -1232,8 +1230,7 @@ void main() { testWidgets('listens to the onVideoRecordingError stream', ( WidgetTester tester, ) async { - final StreamController videoRecordingErrorController = - StreamController(); + final videoRecordingErrorController = StreamController(); when( camera.onVideoRecordingError, @@ -1265,7 +1262,7 @@ void main() { testWidgets('when startVideoRecording throws DomException', ( WidgetTester tester, ) async { - final DOMException exception = DOMException('InvalidStateError'); + final exception = DOMException('InvalidStateError'); when(camera.startVideoRecording()).thenThrow(exception); @@ -1287,7 +1284,7 @@ void main() { testWidgets('when startVideoRecording throws CameraWebException', ( WidgetTester tester, ) async { - final CameraWebException exception = CameraWebException( + final exception = CameraWebException( cameraId, CameraErrorCode.notStarted, 'description', @@ -1343,8 +1340,8 @@ void main() { group('stopVideoRecording', () { testWidgets('stops a video recording', (WidgetTester tester) async { - final MockCamera camera = MockCamera(); - final XFile capturedVideo = XFile('/bogus/test'); + final camera = MockCamera(); + final capturedVideo = XFile('/bogus/test'); when( camera.stopVideoRecording(), @@ -1365,10 +1362,9 @@ void main() { testWidgets('stops listening to the onVideoRecordingError stream', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final StreamController videoRecordingErrorController = - StreamController(); - final XFile capturedVideo = XFile('/bogus/test'); + final camera = MockCamera(); + final videoRecordingErrorController = StreamController(); + final capturedVideo = XFile('/bogus/test'); when(camera.startVideoRecording()).thenAnswer((_) async {}); @@ -1409,8 +1405,8 @@ void main() { testWidgets('when stopVideoRecording throws DomException', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final DOMException exception = DOMException('InvalidStateError'); + final camera = MockCamera(); + final exception = DOMException('InvalidStateError'); when(camera.stopVideoRecording()).thenThrow(exception); @@ -1432,8 +1428,8 @@ void main() { testWidgets('when stopVideoRecording throws CameraWebException', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final CameraWebException exception = CameraWebException( + final camera = MockCamera(); + final exception = CameraWebException( cameraId, CameraErrorCode.notStarted, 'description', @@ -1460,7 +1456,7 @@ void main() { group('pauseVideoRecording', () { testWidgets('pauses a video recording', (WidgetTester tester) async { - final MockCamera camera = MockCamera(); + final camera = MockCamera(); when(camera.pauseVideoRecording()).thenAnswer((_) async {}); @@ -1490,8 +1486,8 @@ void main() { testWidgets('when pauseVideoRecording throws DomException', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final DOMException exception = DOMException('InvalidStateError'); + final camera = MockCamera(); + final exception = DOMException('InvalidStateError'); when(camera.pauseVideoRecording()).thenThrow(exception); @@ -1513,8 +1509,8 @@ void main() { testWidgets('when pauseVideoRecording throws CameraWebException', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final CameraWebException exception = CameraWebException( + final camera = MockCamera(); + final exception = CameraWebException( cameraId, CameraErrorCode.notStarted, 'description', @@ -1541,7 +1537,7 @@ void main() { group('resumeVideoRecording', () { testWidgets('resumes a video recording', (WidgetTester tester) async { - final MockCamera camera = MockCamera(); + final camera = MockCamera(); when(camera.resumeVideoRecording()).thenAnswer((_) async {}); @@ -1571,8 +1567,8 @@ void main() { testWidgets('when resumeVideoRecording throws DomException', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final DOMException exception = DOMException('InvalidStateError'); + final camera = MockCamera(); + final exception = DOMException('InvalidStateError'); when(camera.resumeVideoRecording()).thenThrow(exception); @@ -1594,8 +1590,8 @@ void main() { testWidgets('when resumeVideoRecording throws CameraWebException', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final CameraWebException exception = CameraWebException( + final camera = MockCamera(); + final exception = CameraWebException( cameraId, CameraErrorCode.notStarted, 'description', @@ -1624,7 +1620,7 @@ void main() { testWidgets('calls setFlashMode on the camera', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); + final camera = MockCamera(); const FlashMode flashMode = FlashMode.always; // Save the camera in the camera plugin. @@ -1656,8 +1652,8 @@ void main() { testWidgets('when setFlashMode throws DomException', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final DOMException exception = DOMException('NotSupportedError'); + final camera = MockCamera(); + final exception = DOMException('NotSupportedError'); when(camera.setFlashMode(any)).thenThrow(exception); @@ -1682,8 +1678,8 @@ void main() { testWidgets('when setFlashMode throws CameraWebException', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final CameraWebException exception = CameraWebException( + final camera = MockCamera(); + final exception = CameraWebException( cameraId, CameraErrorCode.notStarted, 'description', @@ -1794,8 +1790,8 @@ void main() { testWidgets('calls getMaxZoomLevel on the camera', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - const double maximumZoomLevel = 100.0; + final camera = MockCamera(); + const maximumZoomLevel = 100.0; when(camera.getMaxZoomLevel()).thenReturn(maximumZoomLevel); @@ -1828,8 +1824,8 @@ void main() { testWidgets('when getMaxZoomLevel throws DomException', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final DOMException exception = DOMException('NotSupportedError'); + final camera = MockCamera(); + final exception = DOMException('NotSupportedError'); when(camera.getMaxZoomLevel()).thenThrow(exception); @@ -1851,8 +1847,8 @@ void main() { testWidgets('when getMaxZoomLevel throws CameraWebException', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final CameraWebException exception = CameraWebException( + final camera = MockCamera(); + final exception = CameraWebException( cameraId, CameraErrorCode.notStarted, 'description', @@ -1881,8 +1877,8 @@ void main() { testWidgets('calls getMinZoomLevel on the camera', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - const double minimumZoomLevel = 100.0; + final camera = MockCamera(); + const minimumZoomLevel = 100.0; when(camera.getMinZoomLevel()).thenReturn(minimumZoomLevel); @@ -1915,8 +1911,8 @@ void main() { testWidgets('when getMinZoomLevel throws DomException', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final DOMException exception = DOMException('NotSupportedError'); + final camera = MockCamera(); + final exception = DOMException('NotSupportedError'); when(camera.getMinZoomLevel()).thenThrow(exception); @@ -1938,8 +1934,8 @@ void main() { testWidgets('when getMinZoomLevel throws CameraWebException', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final CameraWebException exception = CameraWebException( + final camera = MockCamera(); + final exception = CameraWebException( cameraId, CameraErrorCode.notStarted, 'description', @@ -1968,12 +1964,12 @@ void main() { testWidgets('calls setZoomLevel on the camera', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); + final camera = MockCamera(); // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; - const double zoom = 100.0; + const zoom = 100.0; await CameraPlatform.instance.setZoomLevel(cameraId, zoom); @@ -1998,8 +1994,8 @@ void main() { testWidgets('when setZoomLevel throws DomException', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final DOMException exception = DOMException('NotSupportedError'); + final camera = MockCamera(); + final exception = DOMException('NotSupportedError'); when(camera.setZoomLevel(any)).thenThrow(exception); @@ -2021,8 +2017,8 @@ void main() { testWidgets('when setZoomLevel throws PlatformException', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final PlatformException exception = PlatformException( + final camera = MockCamera(); + final exception = PlatformException( code: CameraErrorCode.notSupported.toString(), message: 'message', ); @@ -2047,8 +2043,8 @@ void main() { testWidgets('when setZoomLevel throws CameraWebException', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final CameraWebException exception = CameraWebException( + final camera = MockCamera(); + final exception = CameraWebException( cameraId, CameraErrorCode.notStarted, 'description', @@ -2075,7 +2071,7 @@ void main() { group('pausePreview', () { testWidgets('calls pause on the camera', (WidgetTester tester) async { - final MockCamera camera = MockCamera(); + final camera = MockCamera(); // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; @@ -2103,8 +2099,8 @@ void main() { testWidgets('when pause throws DomException', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final DOMException exception = DOMException('NotSupportedError'); + final camera = MockCamera(); + final exception = DOMException('NotSupportedError'); when(camera.pause()).thenThrow(exception); @@ -2127,7 +2123,7 @@ void main() { group('resumePreview', () { testWidgets('calls play on the camera', (WidgetTester tester) async { - final MockCamera camera = MockCamera(); + final camera = MockCamera(); when(camera.play()).thenAnswer((_) async {}); @@ -2157,8 +2153,8 @@ void main() { testWidgets('when play throws DomException', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final DOMException exception = DOMException('NotSupportedError'); + final camera = MockCamera(); + final exception = DOMException('NotSupportedError'); when(camera.play()).thenThrow(exception); @@ -2180,8 +2176,8 @@ void main() { testWidgets('when play throws CameraWebException', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final CameraWebException exception = CameraWebException( + final camera = MockCamera(); + final exception = CameraWebException( cameraId, CameraErrorCode.unknown, 'description', @@ -2208,10 +2204,7 @@ void main() { testWidgets('buildPreview returns an HtmlElementView ' 'with an appropriate view type', (WidgetTester tester) async { - final Camera camera = Camera( - textureId: cameraId, - cameraService: cameraService, - ); + final camera = Camera(textureId: cameraId, cameraService: cameraService); // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; @@ -2253,10 +2246,8 @@ void main() { when(camera.videoElement).thenReturn(videoElement); - final MockEventStreamProvider errorProvider = - MockEventStreamProvider(); - final MockEventStreamProvider abortProvider = - MockEventStreamProvider(); + final errorProvider = MockEventStreamProvider(); + final abortProvider = MockEventStreamProvider(); (CameraPlatform.instance as CameraPlugin).videoElementOnErrorProvider = errorProvider; @@ -2280,11 +2271,11 @@ void main() { }); testWidgets('disposes the correct camera', (WidgetTester tester) async { - const int firstCameraId = 0; - const int secondCameraId = 1; + const firstCameraId = 0; + const secondCameraId = 1; - final MockCamera firstCamera = MockCamera(); - final MockCamera secondCamera = MockCamera(); + final firstCamera = MockCamera(); + final secondCamera = MockCamera(); when(firstCamera.dispose()).thenAnswer((_) => Future.value()); when(secondCamera.dispose()).thenAnswer((_) => Future.value()); @@ -2365,8 +2356,8 @@ void main() { testWidgets('when dispose throws DomException', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final DOMException exception = DOMException('InvalidAccessError'); + final camera = MockCamera(); + final exception = DOMException('InvalidAccessError'); when(camera.dispose()).thenThrow(exception); @@ -2389,7 +2380,7 @@ void main() { group('getCamera', () { testWidgets('returns the correct camera', (WidgetTester tester) async { - final Camera camera = Camera( + final camera = Camera( textureId: cameraId, cameraService: cameraService, ); @@ -2445,10 +2436,8 @@ void main() { when(camera.videoElement).thenReturn(videoElement); - final MockEventStreamProvider errorProvider = - MockEventStreamProvider(); - final MockEventStreamProvider abortProvider = - MockEventStreamProvider(); + final errorProvider = MockEventStreamProvider(); + final abortProvider = MockEventStreamProvider(); (CameraPlatform.instance as CameraPlugin).videoElementOnErrorProvider = errorProvider; @@ -2474,7 +2463,7 @@ void main() { testWidgets('onCameraInitialized emits a CameraInitializedEvent ' 'on initializeCamera', (WidgetTester tester) async { // Mock the camera to use a blank video stream of size 1280x720. - const Size videoSize = Size(1280, 720); + const videoSize = Size(1280, 720); videoElement = getVideoElementWithBlankStream(videoSize); @@ -2482,7 +2471,7 @@ void main() { cameraService.getMediaStreamForOptions(any, cameraId: cameraId), ).thenAnswer((_) async => videoElement.captureStream()); - final Camera camera = Camera( + final camera = Camera( textureId: cameraId, cameraService: cameraService, ); @@ -2494,8 +2483,7 @@ void main() { .instance .onCameraInitialized(cameraId); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); await CameraPlatform.instance.initializeCamera(cameraId); @@ -2534,8 +2522,7 @@ void main() { final Stream eventStream = CameraPlatform.instance .onCameraClosing(cameraId); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); await CameraPlatform.instance.initializeCamera(cameraId); @@ -2563,12 +2550,11 @@ void main() { final Stream eventStream = CameraPlatform.instance .onCameraError(cameraId); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); await CameraPlatform.instance.initializeCamera(cameraId); - final MediaError error = + final error = createJSInteropWrapper( FakeMediaError( MediaError.MEDIA_ERR_NETWORK, @@ -2603,12 +2589,11 @@ void main() { final Stream eventStream = CameraPlatform.instance .onCameraError(cameraId); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); await CameraPlatform.instance.initializeCamera(cameraId); - final MediaError error = + final error = createJSInteropWrapper( FakeMediaError(MediaError.MEDIA_ERR_NETWORK), ) @@ -2638,8 +2623,7 @@ void main() { final Stream eventStream = CameraPlatform.instance .onCameraError(cameraId); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); await CameraPlatform.instance.initializeCamera(cameraId); @@ -2660,7 +2644,7 @@ void main() { testWidgets('emits a CameraErrorEvent ' 'on takePicture error', (WidgetTester tester) async { - final CameraWebException exception = CameraWebException( + final exception = CameraWebException( cameraId, CameraErrorCode.notStarted, 'description', @@ -2671,8 +2655,7 @@ void main() { final Stream eventStream = CameraPlatform.instance .onCameraError(cameraId); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); expect( () async => CameraPlatform.instance.takePicture(cameraId), @@ -2694,7 +2677,7 @@ void main() { testWidgets('emits a CameraErrorEvent ' 'on setFlashMode error', (WidgetTester tester) async { - final CameraWebException exception = CameraWebException( + final exception = CameraWebException( cameraId, CameraErrorCode.notStarted, 'description', @@ -2705,8 +2688,7 @@ void main() { final Stream eventStream = CameraPlatform.instance .onCameraError(cameraId); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); expect( () async => CameraPlatform.instance.setFlashMode( @@ -2731,7 +2713,7 @@ void main() { testWidgets('emits a CameraErrorEvent ' 'on getMaxZoomLevel error', (WidgetTester tester) async { - final CameraWebException exception = CameraWebException( + final exception = CameraWebException( cameraId, CameraErrorCode.zoomLevelNotSupported, 'description', @@ -2742,8 +2724,7 @@ void main() { final Stream eventStream = CameraPlatform.instance .onCameraError(cameraId); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); expect( () async => CameraPlatform.instance.getMaxZoomLevel(cameraId), @@ -2765,7 +2746,7 @@ void main() { testWidgets('emits a CameraErrorEvent ' 'on getMinZoomLevel error', (WidgetTester tester) async { - final CameraWebException exception = CameraWebException( + final exception = CameraWebException( cameraId, CameraErrorCode.zoomLevelNotSupported, 'description', @@ -2776,8 +2757,7 @@ void main() { final Stream eventStream = CameraPlatform.instance .onCameraError(cameraId); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); expect( () async => CameraPlatform.instance.getMinZoomLevel(cameraId), @@ -2799,7 +2779,7 @@ void main() { testWidgets('emits a CameraErrorEvent ' 'on setZoomLevel error', (WidgetTester tester) async { - final CameraWebException exception = CameraWebException( + final exception = CameraWebException( cameraId, CameraErrorCode.zoomLevelNotSupported, 'description', @@ -2810,8 +2790,7 @@ void main() { final Stream eventStream = CameraPlatform.instance .onCameraError(cameraId); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); expect( () async => CameraPlatform.instance.setZoomLevel(cameraId, 100.0), @@ -2833,7 +2812,7 @@ void main() { testWidgets('emits a CameraErrorEvent ' 'on resumePreview error', (WidgetTester tester) async { - final CameraWebException exception = CameraWebException( + final exception = CameraWebException( cameraId, CameraErrorCode.unknown, 'description', @@ -2844,8 +2823,7 @@ void main() { final Stream eventStream = CameraPlatform.instance .onCameraError(cameraId); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); expect( () async => CameraPlatform.instance.resumePreview(cameraId), @@ -2867,7 +2845,7 @@ void main() { testWidgets('emits a CameraErrorEvent ' 'on startVideoRecording error', (WidgetTester tester) async { - final CameraWebException exception = CameraWebException( + final exception = CameraWebException( cameraId, CameraErrorCode.notStarted, 'description', @@ -2882,8 +2860,7 @@ void main() { final Stream eventStream = CameraPlatform.instance .onCameraError(cameraId); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); expect( () async => CameraPlatform.instance.startVideoRecording(cameraId), @@ -2910,13 +2887,12 @@ void main() { final Stream eventStream = CameraPlatform.instance .onCameraError(cameraId); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); await CameraPlatform.instance.initializeCamera(cameraId); await CameraPlatform.instance.startVideoRecording(cameraId); - final ErrorEvent errorEvent = + final errorEvent = createJSInteropWrapper(FakeErrorEvent('type', 'message')) as ErrorEvent; @@ -2937,7 +2913,7 @@ void main() { testWidgets('emits a CameraErrorEvent ' 'on stopVideoRecording error', (WidgetTester tester) async { - final CameraWebException exception = CameraWebException( + final exception = CameraWebException( cameraId, CameraErrorCode.notStarted, 'description', @@ -2948,8 +2924,7 @@ void main() { final Stream eventStream = CameraPlatform.instance .onCameraError(cameraId); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); expect( () async => CameraPlatform.instance.stopVideoRecording(cameraId), @@ -2971,7 +2946,7 @@ void main() { testWidgets('emits a CameraErrorEvent ' 'on pauseVideoRecording error', (WidgetTester tester) async { - final CameraWebException exception = CameraWebException( + final exception = CameraWebException( cameraId, CameraErrorCode.notStarted, 'description', @@ -2982,8 +2957,7 @@ void main() { final Stream eventStream = CameraPlatform.instance .onCameraError(cameraId); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); expect( () async => CameraPlatform.instance.pauseVideoRecording(cameraId), @@ -3005,7 +2979,7 @@ void main() { testWidgets('emits a CameraErrorEvent ' 'on resumeVideoRecording error', (WidgetTester tester) async { - final CameraWebException exception = CameraWebException( + final exception = CameraWebException( cameraId, CameraErrorCode.notStarted, 'description', @@ -3016,8 +2990,7 @@ void main() { final Stream eventStream = CameraPlatform.instance .onCameraError(cameraId); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); expect( () async => CameraPlatform.instance.resumeVideoRecording(cameraId), @@ -3041,21 +3014,19 @@ void main() { testWidgets('onVideoRecordedEvent emits a VideoRecordedEvent', ( WidgetTester tester, ) async { - final MockCamera camera = MockCamera(); - final XFile capturedVideo = XFile('/bogus/test'); - final Stream stream = - Stream.value( - VideoRecordedEvent(cameraId, capturedVideo, Duration.zero), - ); + final camera = MockCamera(); + final capturedVideo = XFile('/bogus/test'); + final stream = Stream.value( + VideoRecordedEvent(cameraId, capturedVideo, Duration.zero), + ); when(camera.onVideoRecordedEvent).thenAnswer((_) => stream); // Save the camera in the camera plugin. (CameraPlatform.instance as CameraPlugin).cameras[cameraId] = camera; - final StreamQueue streamQueue = - StreamQueue( - CameraPlatform.instance.onVideoRecordedEvent(cameraId), - ); + final streamQueue = StreamQueue( + CameraPlatform.instance.onVideoRecordedEvent(cameraId), + ); expect( await streamQueue.next, @@ -3064,12 +3035,10 @@ void main() { }); group('onDeviceOrientationChanged', () { - final StreamController eventStreamController = - StreamController(); + final eventStreamController = StreamController(); setUp(() { - final MockEventStreamProvider provider = - MockEventStreamProvider(); + final provider = MockEventStreamProvider(); (CameraPlatform.instance as CameraPlugin) .orientationOnChangeProvider = provider; @@ -3093,8 +3062,9 @@ void main() { final Stream eventStream = CameraPlatform.instance.onDeviceOrientationChanged(); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue( + eventStream, + ); expect( await streamQueue.next, @@ -3125,8 +3095,9 @@ void main() { final Stream eventStream = CameraPlatform.instance.onDeviceOrientationChanged(); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue( + eventStream, + ); // Change the screen orientation to landscapePrimary and // emit an event on the screenOrientation.onChange stream. diff --git a/packages/camera/camera_web/example/integration_test/helpers/mocks.dart b/packages/camera/camera_web/example/integration_test/helpers/mocks.dart index 5bb6d11dfb40..fa5c35214e9b 100644 --- a/packages/camera/camera_web/example/integration_test/helpers/mocks.dart +++ b/packages/camera/camera_web/example/integration_test/helpers/mocks.dart @@ -8,15 +8,12 @@ import 'dart:async'; import 'dart:js_interop'; import 'dart:ui'; -// ignore_for_file: implementation_imports import 'package:camera_web/src/camera.dart'; import 'package:camera_web/src/camera_service.dart'; import 'package:camera_web/src/shims/dart_js_util.dart'; import 'package:camera_web/src/types/types.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; -// TODO(srujzs): This is exported in `package:web` 0.6.0. Remove this when it is available. -import 'package:web/src/helpers/events/streams.dart'; import 'package:web/web.dart' as web; @GenerateNiceMocks(>[ @@ -80,12 +77,12 @@ class MockScreen { @JSExport() class MockScreenOrientation { - /// JSPromise Function(web.OrientationLockType orientation) + /// `JSPromise Function(web.OrientationLockType orientation)` JSFunction lock = (web.OrientationLockType orientation) { return Future.value().toJS; }.toJS; - /// void Function() + /// `void Function()` late JSFunction unlock; late web.OrientationType type; } @@ -97,7 +94,7 @@ class MockDocument { @JSExport() class MockElement { - /// JSPromise Function([FullscreenOptions options]) + /// `JSPromise Function([FullscreenOptions options])` JSFunction requestFullscreen = ([web.FullscreenOptions? options]) { return Future.value().toJS; }.toJS; @@ -110,30 +107,30 @@ class MockNavigator { @JSExport() class MockMediaDevices { - /// JSPromise Function([web.MediaStreamConstraints? constraints]) + /// `JSPromise Function([web.MediaStreamConstraints? constraints])` late JSFunction getUserMedia; - /// web.MediaTrackSupportedConstraints Function() + /// `web.MediaTrackSupportedConstraints Function()` late JSFunction getSupportedConstraints; - /// JSPromise> Function() + /// `JSPromise> Function()` late JSFunction enumerateDevices; } @JSExport() class MockMediaStreamTrack { - /// web.MediaTrackCapabilities Function(); + /// `web.MediaTrackCapabilities Function()` late JSFunction getCapabilities; - /// web.MediaTrackSettings Function() + /// `web.MediaTrackSettings Function()` JSFunction getSettings = () { return web.MediaTrackSettings(); }.toJS; - /// JSPromise Function([web.MediaTrackConstraints? constraints]) + /// `JSPromise Function([web.MediaTrackConstraints? constraints])` late JSFunction applyConstraints; - /// void Function() + /// `void Function()` JSFunction stop = () {}.toJS; } @@ -145,24 +142,24 @@ class MockVideoElement { @JSExport() class MockMediaRecorder { - /// void Function(String type, web.EventListener? callback, [JSAny options]) + /// `void Function(String type, web.EventListener? callback, [JSAny options])` JSFunction addEventListener = (String type, web.EventListener? callback, [JSAny? options]) {}.toJS; - /// void Function(String type, web.EventListener? callback, [JSAny options]) + /// `void Function(String type, web.EventListener? callback, [JSAny options])` JSFunction removeEventListener = (String type, web.EventListener? callback, [JSAny? options]) {}.toJS; - /// void Function([int timeslice]) + /// `void Function([int timeslice])` JSFunction start = ([int? timeslice]) {}.toJS; - /// void Function() + /// `void Function()` JSFunction pause = () {}.toJS; - /// void Function() + /// `void Function()` JSFunction resume = () {}.toJS; - /// void Function() + /// `void Function()` JSFunction stop = () {}.toJS; web.RecordingState state = 'inactive'; @@ -197,9 +194,9 @@ class FakeMediaError { final String message; } -/// A fake [ElementStream] that listens to the provided [_stream] on [listen]. +/// A fake [web.ElementStream] that listens to the provided [_stream] on [listen]. class FakeElementStream extends Fake - implements ElementStream { + implements web.ElementStream { FakeElementStream(this._stream); final Stream _stream; @@ -220,7 +217,7 @@ class FakeElementStream extends Fake } } -/// A fake [BlobEvent] that returns the provided blob [data]. +/// A fake [web.BlobEvent] that returns the provided blob [data]. @JSExport() class FakeBlobEvent { FakeBlobEvent(this.data); @@ -228,7 +225,7 @@ class FakeBlobEvent { final web.Blob? data; } -/// A fake [DomException] that returns the provided error [_name] and [_message]. +/// A fake [web.DomException] that returns the provided error [_name] and [_message]. @JSExport() class FakeErrorEvent { FakeErrorEvent(this.type, [this.message = '']); @@ -245,12 +242,12 @@ class FakeErrorEvent { /// final videoStream = videoElement.captureStream(); /// ``` web.HTMLVideoElement getVideoElementWithBlankStream(Size videoSize) { - final web.HTMLCanvasElement canvasElement = web.HTMLCanvasElement() + final canvasElement = web.HTMLCanvasElement() ..width = videoSize.width.toInt() ..height = videoSize.height.toInt() ..context2D.fillRect(0, 0, videoSize.width, videoSize.height); - final web.HTMLVideoElement videoElement = web.HTMLVideoElement() + final videoElement = web.HTMLVideoElement() ..srcObject = canvasElement.captureStream(); return videoElement; @@ -272,7 +269,7 @@ class MockEventStreamProvider extends Mock } @override - ElementStream forElement(web.Element? e, {bool? useCapture = false}) { + web.ElementStream forElement(web.Element? e, {bool? useCapture = false}) { return super.noSuchMethod( Invocation.method( #forElement, @@ -281,6 +278,26 @@ class MockEventStreamProvider extends Mock ), returnValue: FakeElementStream(Stream.empty()), ) - as ElementStream; + as web.ElementStream; } } + +/// A fake [web.MediaTrackCapabilities] where facingMode is null/undefined. +/// +/// Used to test null-safe handling when the browser doesn't provide +/// the facingMode capability. +@JSExport() +class FakeMediaTrackCapabilities { + // Dummy property required by @JSExport + bool get dummy => true; +} + +/// A fake [web.MediaTrackSettings] where facingMode is null/undefined. +/// +/// Used to test null-safe handling when the browser doesn't provide +/// the facingMode capability. +@JSExport() +class FakeMediaTrackSettings { + // Dummy property required by @JSExport + bool get dummy => true; +} diff --git a/packages/camera/camera_web/example/integration_test/zoom_level_capability_test.dart b/packages/camera/camera_web/example/integration_test/zoom_level_capability_test.dart index 8ee05b059436..dc938d40c3ab 100644 --- a/packages/camera/camera_web/example/integration_test/zoom_level_capability_test.dart +++ b/packages/camera/camera_web/example/integration_test/zoom_level_capability_test.dart @@ -17,12 +17,12 @@ void main() { group('ZoomLevelCapability', () { testWidgets('sets all properties', (WidgetTester tester) async { - const double minimum = 100.0; - const double maximum = 400.0; - final MediaStreamTrack videoTrack = + const minimum = 100.0; + const maximum = 400.0; + final videoTrack = createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack; - final ZoomLevelCapability capability = ZoomLevelCapability( + final capability = ZoomLevelCapability( minimum: minimum, maximum: maximum, videoTrack: videoTrack, @@ -34,7 +34,7 @@ void main() { }); testWidgets('supports value equality', (WidgetTester tester) async { - final MediaStreamTrack videoTrack = + final videoTrack = createJSInteropWrapper(MockMediaStreamTrack()) as MediaStreamTrack; expect( diff --git a/packages/camera/camera_web/example/pubspec.yaml b/packages/camera/camera_web/example/pubspec.yaml index fff2e4ce9d6c..ef786ec3cb1f 100644 --- a/packages/camera/camera_web/example/pubspec.yaml +++ b/packages/camera/camera_web/example/pubspec.yaml @@ -2,8 +2,8 @@ name: camera_web_integration_tests publish_to: none environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" dependencies: camera_platform_interface: ^2.6.0 diff --git a/packages/camera/camera_web/lib/src/camera.dart b/packages/camera/camera_web/lib/src/camera.dart index bbfe18b491fa..dd773d380c73 100644 --- a/packages/camera/camera_web/lib/src/camera.dart +++ b/packages/camera/camera_web/lib/src/camera.dart @@ -255,10 +255,10 @@ class Camera { final int videoWidth = videoElement.videoWidth; final int videoHeight = videoElement.videoHeight; - final web.HTMLCanvasElement canvas = web.HTMLCanvasElement() + final canvas = web.HTMLCanvasElement() ..width = videoWidth ..height = videoHeight; - final bool isBackCamera = getLensDirection() == CameraLensDirection.back; + final isBackCamera = getLensDirection() == CameraLensDirection.back; // Flip the picture horizontally if it is not taken from a back camera. if (!isBackCamera) { @@ -275,7 +275,7 @@ class Camera { videoHeight.toDouble(), ); - final Completer blobCompleter = Completer(); + final blobCompleter = Completer(); canvas.toBlob( (web.Blob blob) { blobCompleter.complete(blob); @@ -456,9 +456,7 @@ class Camera { /// Throws a [CameraWebException] if the browser does not support any of the /// available video mime types from [_videoMimeType]. Future startVideoRecording() async { - final web.MediaRecorderOptions options = web.MediaRecorderOptions( - mimeType: _videoMimeType, - ); + final options = web.MediaRecorderOptions(mimeType: _videoMimeType); if (recorderOptions.audioBitrate != null) { options.audioBitsPerSecond = recorderOptions.audioBitrate!; } @@ -492,7 +490,7 @@ class Camera { _onVideoRecordingErrorSubscription = mediaRecorderOnErrorProvider .forTarget(mediaRecorder) .listen((web.Event event) { - final web.ErrorEvent error = event as web.ErrorEvent; + final error = event as web.ErrorEvent; videoRecordingErrorController.add(error); }); @@ -511,7 +509,7 @@ class Camera { final web.Blob videoBlob = blobBuilder(_videoData, videoType); // Create a file containing the video blob. - final XFile file = XFile( + final file = XFile( web.URL.createObjectURL(videoBlob), mimeType: _videoMimeType, name: videoBlob.hashCode.toString(), @@ -605,7 +603,7 @@ class Camera { /// Throws a [CameraWebException] if the browser does not support /// any of the available video mime types. String get _videoMimeType { - const List types = [ + const types = [ 'video/webm;codecs="vp9,opus"', 'video/mp4', 'video/webm', @@ -630,7 +628,7 @@ class Camera { /// Applies default styles to the video [element]. void _applyDefaultVideoStyles(web.HTMLVideoElement element) { - final bool isBackCamera = getLensDirection() == CameraLensDirection.back; + final isBackCamera = getLensDirection() == CameraLensDirection.back; // Flip the video horizontally if it is not taken from a back camera. if (!isBackCamera) { diff --git a/packages/camera/camera_web/lib/src/camera_service.dart b/packages/camera/camera_web/lib/src/camera_service.dart index 828f53914818..9bf588a456da 100644 --- a/packages/camera/camera_web/lib/src/camera_service.dart +++ b/packages/camera/camera_web/lib/src/camera_service.dart @@ -200,11 +200,11 @@ class CameraService { // A list of facing mode capabilities as // the camera may support multiple facing modes. - final List facingModeCapabilities = videoTrackCapabilities - .facingMode - .toDart - .map((JSString e) => e.toDart) - .toList(); + final List facingModeCapabilities = + videoTrackCapabilities.facingModeNullable?.toDart + .map((JSString e) => e.toDart) + .toList() ?? + []; if (facingModeCapabilities.isNotEmpty) { final String facingModeCapability = facingModeCapabilities.first; diff --git a/packages/camera/camera_web/lib/src/camera_web.dart b/packages/camera/camera_web/lib/src/camera_web.dart index 2210a4ecba2d..90033681d28a 100644 --- a/packages/camera/camera_web/lib/src/camera_web.dart +++ b/packages/camera/camera_web/lib/src/camera_web.dart @@ -99,7 +99,7 @@ class CameraPlugin extends CameraPlatform { Future> availableCameras() async { try { final web.MediaDevices mediaDevices = window.navigator.mediaDevices; - final List cameras = []; + final cameras = []; // Request video permissions only. final web.MediaStream cameraStream = await _cameraService @@ -125,7 +125,7 @@ class CameraPlugin extends CameraPlatform { .where((web.MediaDeviceInfo device) => device.deviceId.isNotEmpty); // Map video input devices to camera descriptions. - for (final web.MediaDeviceInfo videoInputDevice in videoInputDevices) { + for (final videoInputDevice in videoInputDevices) { // Get the video stream for the current video input device // to later use for the available video tracks. final web.MediaStream videoStream = await _getVideoStreamForDevice( @@ -160,13 +160,13 @@ class CameraPlugin extends CameraPlatform { // https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo/label // // Sensor orientation is currently not supported. - final CameraDescription camera = CameraDescription( + final camera = CameraDescription( name: videoInputDevice.label, lensDirection: lensDirection, sensorOrientation: 0, ); - final CameraMetadata cameraMetadata = CameraMetadata( + final cameraMetadata = CameraMetadata( deviceId: videoInputDevice.deviceId, facingMode: facingMode, ); @@ -176,7 +176,7 @@ class CameraPlugin extends CameraPlatform { camerasMetadata[camera] = cameraMetadata; // Release the camera stream of the current video input device. - for (final web.MediaStreamTrack videoTrack in videoTracks) { + for (final videoTrack in videoTracks) { videoTrack.stop(); } } else { @@ -236,7 +236,7 @@ class CameraPlugin extends CameraPlatform { // Create a camera with the given audio and video constraints. // Sensor orientation is currently not supported. - final Camera camera = Camera( + final camera = Camera( textureId: textureId, cameraService: _cameraService, options: CameraOptions( @@ -381,7 +381,7 @@ class CameraPlugin extends CameraPlatform { // Create an initial orientation event that emits the device orientation // as soon as subscribed to this stream. - final web.Event initialOrientationEvent = web.Event('change'); + final initialOrientationEvent = web.Event('change'); return orientationOnChangeProvider .forTarget(orientation) @@ -677,7 +677,7 @@ class CameraPlugin extends CameraPlatform { /// Returns a media video stream for the device with the given [deviceId]. Future _getVideoStreamForDevice(String deviceId) { // Create camera options with the desired device id. - final CameraOptions cameraOptions = CameraOptions( + final cameraOptions = CameraOptions( video: VideoConstraints(deviceId: deviceId), ); diff --git a/packages/camera/camera_web/lib/src/pkg_web_tweaks.dart b/packages/camera/camera_web/lib/src/pkg_web_tweaks.dart index 4657e9fdff90..f5d54d7dfdfc 100644 --- a/packages/camera/camera_web/lib/src/pkg_web_tweaks.dart +++ b/packages/camera/camera_web/lib/src/pkg_web_tweaks.dart @@ -31,6 +31,9 @@ extension NonStandardFieldsOnMediaTrackCapabilities on MediaTrackCapabilities { @JS('torch') external JSArray? get torchNullable; + + @JS('facingMode') + external JSArray? get facingModeNullable; } /// Adds missing fields to [MediaTrackSettings] diff --git a/packages/camera/camera_web/lib/src/types/camera_options.dart b/packages/camera/camera_web/lib/src/types/camera_options.dart index 49572724b0a1..fe3953fd5a25 100644 --- a/packages/camera/camera_web/lib/src/types/camera_options.dart +++ b/packages/camera/camera_web/lib/src/types/camera_options.dart @@ -108,12 +108,16 @@ class VideoConstraints { // TODO(dit): package:web has a class for this. Use it instead of jsify and toJson. /// Convert `this` to something that can be used on the browser. JSAny toMediaStreamConstraints() { - return { + final constraints = { if (width != null) 'width': width!.toJson(), if (height != null) 'height': height!.toJson(), if (facingMode != null) 'facingMode': facingMode!.toJson(), if (deviceId != null) 'deviceId': {'exact': deviceId!}, - }.jsify()!; + }; + + // Return true instead of empty object for better browser compatibility. + // Firefox Android rejects getUserMedia({video: {}}) but accepts {video: true}. + return constraints.isEmpty ? true.toJS : constraints.jsify()!; } @override @@ -238,7 +242,7 @@ class VideoSizeConstraint { // TODO(dit): package:web has a class for this. Use it instead of toJson. /// Converts the current instance to a Map. Object toJson() { - final Map json = {}; + final json = {}; if (ideal != null) { json['ideal'] = ideal; diff --git a/packages/camera/camera_web/pubspec.yaml b/packages/camera/camera_web/pubspec.yaml index 0b8f161a6e04..4b3603756387 100644 --- a/packages/camera/camera_web/pubspec.yaml +++ b/packages/camera/camera_web/pubspec.yaml @@ -2,11 +2,11 @@ name: camera_web description: A Flutter plugin for getting information about and controlling the camera on Web. repository: https://github.com/flutter/packages/tree/main/packages/camera/camera_web issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+camera%22 -version: 0.3.5+1 +version: 0.3.5+3 environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" flutter: plugin: diff --git a/packages/camera/camera_windows/CHANGELOG.md b/packages/camera/camera_windows/CHANGELOG.md index 7316cdb8b1ee..f679977a75e7 100644 --- a/packages/camera/camera_windows/CHANGELOG.md +++ b/packages/camera/camera_windows/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. + ## 0.2.6+4 * Removes usage of the deprecated and ignored `maxVideoDuration` in the example. diff --git a/packages/camera/camera_windows/example/integration_test/camera_test.dart b/packages/camera/camera_windows/example/integration_test/camera_test.dart index 03b791503c53..f26b7c67f5f2 100644 --- a/packages/camera/camera_windows/example/integration_test/camera_test.dart +++ b/packages/camera/camera_windows/example/integration_test/camera_test.dart @@ -104,8 +104,9 @@ void main() { .instance .onDeviceOrientationChanged(); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue( + eventStream, + ); expect( await streamQueue.next, diff --git a/packages/camera/camera_windows/example/lib/main.dart b/packages/camera/camera_windows/example/lib/main.dart index 3957fe27c0b4..215ecb981309 100644 --- a/packages/camera/camera_windows/example/lib/main.dart +++ b/packages/camera/camera_windows/example/lib/main.dart @@ -60,9 +60,9 @@ class _MyAppState extends State { /// Fetches list of available cameras from camera_windows plugin. Future _fetchCameras() async { String cameraInfo; - List cameras = []; + var cameras = []; - int cameraIndex = 0; + var cameraIndex = 0; try { cameras = await CameraPlatform.instance.availableCameras(); if (cameras.isEmpty) { @@ -92,7 +92,7 @@ class _MyAppState extends State { return; } - int cameraId = -1; + var cameraId = -1; try { final int cameraIndex = _cameraIndex % _cameras.length; final CameraDescription camera = _cameras[cameraIndex]; diff --git a/packages/camera/camera_windows/example/pubspec.yaml b/packages/camera/camera_windows/example/pubspec.yaml index 87ede11c4bc0..de8fa54b7a90 100644 --- a/packages/camera/camera_windows/example/pubspec.yaml +++ b/packages/camera/camera_windows/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the camera_windows plugin. publish_to: 'none' environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" dependencies: camera_platform_interface: ^2.6.0 diff --git a/packages/camera/camera_windows/pubspec.yaml b/packages/camera/camera_windows/pubspec.yaml index ab42277ea399..bb0cffda6756 100644 --- a/packages/camera/camera_windows/pubspec.yaml +++ b/packages/camera/camera_windows/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.2.6+4 environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" flutter: plugin: diff --git a/packages/camera/camera_windows/test/camera_windows_test.dart b/packages/camera/camera_windows/test/camera_windows_test.dart index a3b0e0e98ab8..dcd35d3d3fa2 100644 --- a/packages/camera/camera_windows/test/camera_windows_test.dart +++ b/packages/camera/camera_windows/test/camera_windows_test.dart @@ -27,10 +27,10 @@ void main() { group('Creation, Initialization & Disposal Tests', () { test('Should send creation data and receive back a camera id', () async { // Arrange - final MockCameraApi mockApi = MockCameraApi(); + final mockApi = MockCameraApi(); when(mockApi.create(any, any)).thenAnswer((_) async => 1); - final CameraWindows plugin = CameraWindows(api: mockApi); - const String cameraName = 'Test'; + final plugin = CameraWindows(api: mockApi); + const cameraName = 'Test'; // Act final int cameraId = await plugin.createCameraWithSettings( @@ -52,8 +52,7 @@ void main() { mockApi.create(captureAny, captureAny), ); expect(verification.captured[0], cameraName); - final PlatformMediaSettings? settings = - verification.captured[1] as PlatformMediaSettings?; + final settings = verification.captured[1] as PlatformMediaSettings?; expect(settings, isNotNull); expect(settings?.resolutionPreset, PlatformResolutionPreset.low); expect(cameraId, 1); @@ -63,17 +62,16 @@ void main() { 'Should throw CameraException when create throws a PlatformException', () { // Arrange - const String exceptionCode = 'TESTING_ERROR_CODE'; - const String exceptionMessage = - 'Mock error message used during testing.'; - final MockCameraApi mockApi = MockCameraApi(); + const exceptionCode = 'TESTING_ERROR_CODE'; + const exceptionMessage = 'Mock error message used during testing.'; + final mockApi = MockCameraApi(); when(mockApi.create(any, any)).thenAnswer((_) async { throw PlatformException( code: exceptionCode, message: exceptionMessage, ); }); - final CameraWindows camera = CameraWindows(api: mockApi); + final camera = CameraWindows(api: mockApi); // Act expect( @@ -102,17 +100,16 @@ void main() { 'Should throw CameraException when initialize throws a PlatformException', () { // Arrange - const String exceptionCode = 'TESTING_ERROR_CODE'; - const String exceptionMessage = - 'Mock error message used during testing.'; - final MockCameraApi mockApi = MockCameraApi(); + const exceptionCode = 'TESTING_ERROR_CODE'; + const exceptionMessage = 'Mock error message used during testing.'; + final mockApi = MockCameraApi(); when(mockApi.initialize(any)).thenAnswer((_) async { throw PlatformException( code: exceptionCode, message: exceptionMessage, ); }); - final CameraWindows plugin = CameraWindows(api: mockApi); + final plugin = CameraWindows(api: mockApi); // Act expect( @@ -136,11 +133,11 @@ void main() { test('Should send initialization data', () async { // Arrange - final MockCameraApi mockApi = MockCameraApi(); + final mockApi = MockCameraApi(); when( mockApi.initialize(any), ).thenAnswer((_) async => PlatformSize(width: 1920, height: 1080)); - final CameraWindows plugin = CameraWindows(api: mockApi); + final plugin = CameraWindows(api: mockApi); final int cameraId = await plugin.createCameraWithSettings( const CameraDescription( name: 'Test', @@ -168,11 +165,11 @@ void main() { test('Should send a disposal call on dispose', () async { // Arrange - final MockCameraApi mockApi = MockCameraApi(); + final mockApi = MockCameraApi(); when( mockApi.initialize(any), ).thenAnswer((_) async => PlatformSize(width: 1920, height: 1080)); - final CameraWindows plugin = CameraWindows(api: mockApi); + final plugin = CameraWindows(api: mockApi); final int cameraId = await plugin.createCameraWithSettings( const CameraDescription( name: 'Test', @@ -204,7 +201,7 @@ void main() { late CameraWindows plugin; late int cameraId; setUp(() async { - final MockCameraApi mockApi = MockCameraApi(); + final mockApi = MockCameraApi(); when(mockApi.create(any, any)).thenAnswer((_) async => 1); when( mockApi.initialize(any), @@ -232,11 +229,10 @@ void main() { final Stream eventStream = plugin.onCameraClosing( cameraId, ); - final StreamQueue streamQueue = - StreamQueue(eventStream); + final streamQueue = StreamQueue(eventStream); // Emit test events - final CameraClosingEvent event = CameraClosingEvent(cameraId); + final event = CameraClosingEvent(cameraId); plugin.hostCameraHandlers[cameraId]!.cameraClosing(); plugin.hostCameraHandlers[cameraId]!.cameraClosing(); plugin.hostCameraHandlers[cameraId]!.cameraClosing(); @@ -255,12 +251,11 @@ void main() { final Stream errorStream = plugin.onCameraError( cameraId, ); - final StreamQueue streamQueue = - StreamQueue(errorStream); + final streamQueue = StreamQueue(errorStream); // Emit test events - const String errorMessage = 'Error Description'; - final CameraErrorEvent event = CameraErrorEvent(cameraId, errorMessage); + const errorMessage = 'Error Description'; + final event = CameraErrorEvent(cameraId, errorMessage); plugin.hostCameraHandlers[cameraId]!.error(errorMessage); plugin.hostCameraHandlers[cameraId]!.error(errorMessage); plugin.hostCameraHandlers[cameraId]!.error(errorMessage); @@ -309,7 +304,7 @@ void main() { 'Should fetch CameraDescription instances for available cameras', () async { // Arrange - final List returnData = ['Test 1', 'Test 2']; + final returnData = ['Test 1', 'Test 2']; when( mockApi.getAvailableCameras(), ).thenAnswer((_) async => returnData); @@ -320,7 +315,7 @@ void main() { // Assert expect(cameras.length, returnData.length); - for (int i = 0; i < returnData.length; i++) { + for (var i = 0; i < returnData.length; i++) { expect(cameras[i].name, returnData[i]); // This value isn't provided by the platform, so is hard-coded to front. expect(cameras[i].lensDirection, CameraLensDirection.front); @@ -334,8 +329,8 @@ void main() { 'Should throw CameraException when availableCameras throws a PlatformException', () { // Arrange - const String code = 'TESTING_ERROR_CODE'; - const String message = 'Mock error message used during testing.'; + const code = 'TESTING_ERROR_CODE'; + const message = 'Mock error message used during testing.'; when(mockApi.getAvailableCameras()).thenAnswer( (_) async => throw PlatformException(code: code, message: message), ); @@ -362,7 +357,7 @@ void main() { test('Should take a picture and return an XFile instance', () async { // Arrange - const String stubPath = '/test/path.jpg'; + const stubPath = '/test/path.jpg'; when(mockApi.takePicture(any)).thenAnswer((_) async => stubPath); // Act @@ -403,7 +398,7 @@ void main() { test('Should stop a video recording and return the file', () async { // Arrange - const String stubPath = '/test/path.mp4'; + const stubPath = '/test/path.mp4'; when(mockApi.stopVideoRecording(any)).thenAnswer((_) async => stubPath); // Act diff --git a/packages/cross_file/CHANGELOG.md b/packages/cross_file/CHANGELOG.md index 7f37f7bd53df..039afe45a3e2 100644 --- a/packages/cross_file/CHANGELOG.md +++ b/packages/cross_file/CHANGELOG.md @@ -1,3 +1,11 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. + +## 0.3.5+2 + +* Separates "Save As" implementation details from XFile web class. + ## 0.3.5+1 * Replaces README mentions of `dart:html` with `package:web`. diff --git a/packages/cross_file/README.md b/packages/cross_file/README.md index 5fc52b5e6447..290295571877 100644 --- a/packages/cross_file/README.md +++ b/packages/cross_file/README.md @@ -12,7 +12,7 @@ Example: ```dart -final XFile file = XFile('assets/hello.txt'); +final file = XFile('assets/hello.txt'); print('File information:'); print('- Path: ${file.path}'); diff --git a/packages/cross_file/example/lib/readme_excerpts.dart b/packages/cross_file/example/lib/readme_excerpts.dart index e8c4ea2c2cb4..94e3c879b87c 100644 --- a/packages/cross_file/example/lib/readme_excerpts.dart +++ b/packages/cross_file/example/lib/readme_excerpts.dart @@ -9,7 +9,7 @@ import 'package:cross_file/cross_file.dart'; /// Demonstrate instantiating an XFile for the README. Future instantiateXFile() async { // #docregion Instantiate - final XFile file = XFile('assets/hello.txt'); + final file = XFile('assets/hello.txt'); print('File information:'); print('- Path: ${file.path}'); diff --git a/packages/cross_file/example/pubspec.yaml b/packages/cross_file/example/pubspec.yaml index aec48e35e3ce..591212e013ca 100644 --- a/packages/cross_file/example/pubspec.yaml +++ b/packages/cross_file/example/pubspec.yaml @@ -3,7 +3,7 @@ description: Demonstrates how to use cross files. publish_to: none environment: - sdk: ^3.8.0 + sdk: ^3.9.0 dependencies: cross_file: diff --git a/packages/cross_file/lib/src/types/html.dart b/packages/cross_file/lib/src/types/html.dart index a8047e6a9263..40703aa754fc 100644 --- a/packages/cross_file/lib/src/types/html.dart +++ b/packages/cross_file/lib/src/types/html.dart @@ -7,7 +7,6 @@ import 'dart:convert'; import 'dart:js_interop'; import 'dart:typed_data'; -import 'package:meta/meta.dart'; import 'package:web/web.dart'; import '../web_helpers/web_helpers.dart'; @@ -35,11 +34,9 @@ class XFile extends XFileBase { int? length, Uint8List? bytes, DateTime? lastModified, - @visibleForTesting CrossFileTestOverrides? overrides, }) : _mimeType = mimeType, _path = path, _length = length, - _overrides = overrides, _lastModified = lastModified ?? DateTime.fromMillisecondsSinceEpoch(0), _name = name ?? '', super(path) { @@ -57,10 +54,8 @@ class XFile extends XFileBase { int? length, DateTime? lastModified, String? path, - @visibleForTesting CrossFileTestOverrides? overrides, }) : _mimeType = mimeType, _length = length, - _overrides = overrides, _lastModified = lastModified ?? DateTime.fromMillisecondsSinceEpoch(0), _name = name ?? '', super(path) { @@ -82,12 +77,16 @@ class XFile extends XFileBase { // MimeType of the file (eg: "image/gif"). final String? _mimeType; + // Name (with extension) of the file (eg: "anim.gif") final String _name; + // Path of the file (must be a valid Blob URL, when set manually!) late String _path; + // The size of the file (in bytes). final int? _length; + // The time the file was last modified. final DateTime _lastModified; @@ -97,17 +96,6 @@ class XFile extends XFileBase { // (Similar to a (read-only) dart:io File.) Blob? _browserBlob; - // An html Element that will be used to trigger a "save as" dialog later. - // TODO(dit): https://github.com/flutter/flutter/issues/91400 Remove this _target. - late Element _target; - - // Overrides for testing - // TODO(dit): https://github.com/flutter/flutter/issues/91400 Remove these _overrides, - // they're only used to Save As... - final CrossFileTestOverrides? _overrides; - - bool get _hasTestOverrides => _overrides != null; - @override String? get mimeType => _mimeType; @@ -131,7 +119,7 @@ class XFile extends XFileBase { throw Exception('Safari cannot handle XFiles larger than 4GB.'); } - final Completer blobCompleter = Completer(); + final blobCompleter = Completer(); late XMLHttpRequest request; request = XMLHttpRequest() @@ -183,7 +171,7 @@ class XFile extends XFileBase { // Converts an html Blob object to a Uint8List, through a FileReader. Future _blobToByteBuffer(Blob blob) async { - final FileReader reader = FileReader(); + final reader = FileReader(); reader.readAsArrayBuffer(blob); await reader.onLoadEnd.first; @@ -200,35 +188,8 @@ class XFile extends XFileBase { /// Saves the data of this CrossFile at the location indicated by path. /// For the web implementation, the path variable is ignored. - // TODO(dit): https://github.com/flutter/flutter/issues/91400 - // Move implementation to web_helpers.dart @override Future saveTo(String path) async { - // Create a DOM container where the anchor can be injected. - _target = ensureInitialized('__x_file_dom_element'); - - // Create an tag with the appropriate download attributes and click it - // May be overridden with CrossFileTestOverrides - final HTMLAnchorElement element = _hasTestOverrides - ? _overrides!.createAnchorElement(this.path, name) as HTMLAnchorElement - : createAnchorElement(this.path, name); - - // Clear the children in _target and add an element to click - while (_target.children.length > 0) { - _target.removeChild(_target.children.item(0)!); - } - addElementToContainerAndClick(_target, element); + await saveFileAs(this); } } - -/// Overrides some functions to allow testing -// TODO(dit): https://github.com/flutter/flutter/issues/91400 -// Move this to web_helpers_test.dart -@visibleForTesting -class CrossFileTestOverrides { - /// Default constructor for overrides - CrossFileTestOverrides({required this.createAnchorElement}); - - /// For overriding the creation of the file input element. - Element Function(String href, String suggestedName) createAnchorElement; -} diff --git a/packages/cross_file/lib/src/types/io.dart b/packages/cross_file/lib/src/types/io.dart index 74ca1806cc3a..c1931a743a89 100644 --- a/packages/cross_file/lib/src/types/io.dart +++ b/packages/cross_file/lib/src/types/io.dart @@ -81,7 +81,7 @@ class XFile extends XFileBase { if (_bytes == null) { await _file.copy(path); } else { - final File fileToSave = File(path); + final fileToSave = File(path); // TODO(kevmoo): Remove ignore and fix when the MIN Dart SDK is 3.3 // ignore: unnecessary_non_null_assertion await fileToSave.writeAsBytes(_bytes!); diff --git a/packages/cross_file/lib/src/web_helpers/web_helpers.dart b/packages/cross_file/lib/src/web_helpers/web_helpers.dart index daac03159509..58231dd8c30e 100644 --- a/packages/cross_file/lib/src/web_helpers/web_helpers.dart +++ b/packages/cross_file/lib/src/web_helpers/web_helpers.dart @@ -2,13 +2,26 @@ // 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'; import 'package:web/web.dart'; +import '../types/html.dart'; + +/// Type definition for function that creates anchor elements +typedef CreateAnchorElement = + HTMLAnchorElement Function(String href, String? suggestedName); + /// Create anchor element with download attribute -HTMLAnchorElement createAnchorElement(String href, String? suggestedName) => - (document.createElement('a') as HTMLAnchorElement) - ..href = href - ..download = suggestedName ?? 'download'; +HTMLAnchorElement _createAnchorElementImpl( + String href, + String? suggestedName, +) => (document.createElement('a') as HTMLAnchorElement) + ..href = href + ..download = suggestedName ?? 'download'; + +/// Function for creating anchor elements. Can be overridden for testing. +@visibleForTesting +CreateAnchorElement createAnchorElementFunction = _createAnchorElementImpl; /// Add an element to a container and click it void addElementToContainerAndClick(Element container, HTMLElement element) { @@ -35,3 +48,23 @@ Element ensureInitialized(String id) { bool isSafari() { return window.navigator.vendor == 'Apple Computer, Inc.'; } + +/// Saves the given [XFile] to user's device ("Save As" dialog). +Future saveFileAs(XFile file) async { + // Create container element. + final Element target = ensureInitialized('__x_file_dom_element'); + + // Create element. + final HTMLAnchorElement element = createAnchorElementFunction( + file.path, + file.name, + ); + + // Clear existing children before appending new one. + while (target.children.length > 0) { + target.removeChild(target.children.item(0)!); + } + + // Add and click. + addElementToContainerAndClick(target, element); +} diff --git a/packages/cross_file/pubspec.yaml b/packages/cross_file/pubspec.yaml index 532f392faef8..b8cdbf1719c5 100644 --- a/packages/cross_file/pubspec.yaml +++ b/packages/cross_file/pubspec.yaml @@ -2,10 +2,10 @@ name: cross_file description: An abstraction to allow working with files across multiple platforms. repository: https://github.com/flutter/packages/tree/main/packages/cross_file issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+cross_file%22 -version: 0.3.5+1 +version: 0.3.5+2 environment: - sdk: ^3.8.0 + sdk: ^3.9.0 dependencies: meta: ^1.3.0 diff --git a/packages/cross_file/test/x_file_html_test.dart b/packages/cross_file/test/x_file_html_test.dart index f71f1271829a..e57e36c285c7 100644 --- a/packages/cross_file/test/x_file_html_test.dart +++ b/packages/cross_file/test/x_file_html_test.dart @@ -10,6 +10,7 @@ import 'dart:js_interop'; import 'dart:typed_data'; import 'package:cross_file/cross_file.dart'; +import 'package:cross_file/src/web_helpers/web_helpers.dart' as helpers; import 'package:test/test.dart'; import 'package:web/web.dart' as html; @@ -26,7 +27,7 @@ final String textFileUrl = void main() { group('Create with an objectUrl', () { - final XFile file = XFile(textFileUrl); + final file = XFile(textFileUrl); test('Can be read as a string', () async { expect(await file.readAsString(), equals(expectedStringContents)); @@ -46,7 +47,7 @@ void main() { }); group('Create from data', () { - final XFile file = XFile.fromData(bytes); + final file = XFile.fromData(bytes); test('Can be read as a string', () async { expect(await file.readAsString(), equals(expectedStringContents)); @@ -65,10 +66,10 @@ void main() { }); test('Prefers local bytes over path if both are provided', () async { - const String text = 'Hello World'; - const String path = 'test/x_file_html_test.dart'; + const text = 'Hello World'; + const path = 'test/x_file_html_test.dart'; - final XFile file = XFile.fromData( + final file = XFile.fromData( utf8.encode(text), path: path, name: 'x_file_html_test.dart', @@ -84,7 +85,7 @@ void main() { }); group('Blob backend', () { - final XFile file = XFile(textFileUrl); + final file = XFile(textFileUrl); test('Stores data as a Blob', () async { // Read the blob from its path 'natively' @@ -107,11 +108,11 @@ void main() { }); group('saveTo(..)', () { - const String crossFileDomElementId = '__x_file_dom_element'; + const crossFileDomElementId = '__x_file_dom_element'; group('CrossFile saveTo(..)', () { test('creates a DOM container', () async { - final XFile file = XFile.fromData(bytes); + final file = XFile.fromData(bytes); await file.saveTo(''); @@ -123,7 +124,7 @@ void main() { }); test('create anchor element', () async { - final XFile file = XFile.fromData(bytes, name: textFile.name); + final file = XFile.fromData(bytes, name: textFile.name); await file.saveTo('path'); @@ -132,7 +133,7 @@ void main() { )!; late html.HTMLAnchorElement element; - for (int i = 0; i < container.childNodes.length; i++) { + for (var i = 0; i < container.childNodes.length; i++) { final html.Element test = container.children.item(i)!; if (test.tagName == 'A') { element = test as html.HTMLAnchorElement; @@ -146,20 +147,21 @@ void main() { }); test('anchor element is clicked', () async { - final html.HTMLAnchorElement mockAnchor = + final mockAnchor = html.document.createElement('a') as html.HTMLAnchorElement; - final CrossFileTestOverrides overrides = CrossFileTestOverrides( - createAnchorElement: (_, __) => mockAnchor, - ); + // Save original function so we can restore it + final helpers.CreateAnchorElement original = + helpers.createAnchorElementFunction; - final XFile file = XFile.fromData( - bytes, - name: textFile.name, - overrides: overrides, - ); + addTearDown(() { + helpers.createAnchorElementFunction = original; + }); + helpers.createAnchorElementFunction = (_, __) => mockAnchor; + + final file = XFile.fromData(bytes, name: textFile.name); - bool clicked = false; + var clicked = false; mockAnchor.onClick.listen((html.MouseEvent event) => clicked = true); await file.saveTo('path'); diff --git a/packages/cross_file/test/x_file_io_test.dart b/packages/cross_file/test/x_file_io_test.dart index 56a3b8cb9cc8..904a5c08c507 100644 --- a/packages/cross_file/test/x_file_io_test.dart +++ b/packages/cross_file/test/x_file_io_test.dart @@ -24,28 +24,28 @@ final String textFilePath = textFile.path; void main() { group('Create with a path', () { test('Can be read as a string', () async { - final XFile file = XFile(textFilePath); + final file = XFile(textFilePath); expect(await file.readAsString(), equals(expectedStringContents)); }); test('Can be read as bytes', () async { - final XFile file = XFile(textFilePath); + final file = XFile(textFilePath); expect(await file.readAsBytes(), equals(bytes)); }); test('Can be read as a stream', () async { - final XFile file = XFile(textFilePath); + final file = XFile(textFilePath); expect(await file.openRead().first, equals(bytes)); }); test('Stream can be sliced', () async { - final XFile file = XFile(textFilePath); + final file = XFile(textFilePath); expect(await file.openRead(2, 5).first, equals(bytes.sublist(2, 5))); }); test('saveTo(..) creates file', () async { - final XFile file = XFile(textFilePath); + final file = XFile(textFilePath); final Directory tempDir = Directory.systemTemp.createTempSync(); - final File targetFile = File('${tempDir.path}/newFilePath.txt'); + final targetFile = File('${tempDir.path}/newFilePath.txt'); if (targetFile.existsSync()) { await targetFile.delete(); } @@ -59,9 +59,9 @@ void main() { }); test('saveTo(..) does not load the file into memory', () async { - final TestXFile file = TestXFile(textFilePath); + final file = TestXFile(textFilePath); final Directory tempDir = Directory.systemTemp.createTempSync(); - final File targetFile = File('${tempDir.path}/newFilePath.txt'); + final targetFile = File('${tempDir.path}/newFilePath.txt'); if (targetFile.existsSync()) { await targetFile.delete(); } @@ -79,7 +79,7 @@ void main() { }); group('Create with data', () { - final XFile file = XFile.fromData(bytes); + final file = XFile.fromData(bytes); test('Can be read as a string', () async { expect(await file.readAsString(), equals(expectedStringContents)); @@ -98,7 +98,7 @@ void main() { test('Function saveTo(..) creates file', () async { final Directory tempDir = Directory.systemTemp.createTempSync(); - final File targetFile = File('${tempDir.path}/newFilePath.txt'); + final targetFile = File('${tempDir.path}/newFilePath.txt'); if (targetFile.existsSync()) { await targetFile.delete(); } diff --git a/packages/cupertino_ui/.gitignore b/packages/cupertino_ui/.gitignore new file mode 100644 index 000000000000..dd5eb98951f2 --- /dev/null +++ b/packages/cupertino_ui/.gitignore @@ -0,0 +1,31 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +.flutter-plugins-dependencies +/build/ +/coverage/ diff --git a/packages/cupertino_ui/.metadata b/packages/cupertino_ui/.metadata new file mode 100644 index 000000000000..e44d1b1ea178 --- /dev/null +++ b/packages/cupertino_ui/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "4d0d113b75746f1ec1d93a976f0f02f6bb61dc2d" + channel: "[user-branch]" + +project_type: package diff --git a/packages/cupertino_ui/AUTHORS b/packages/cupertino_ui/AUTHORS new file mode 100644 index 000000000000..557dff97933b --- /dev/null +++ b/packages/cupertino_ui/AUTHORS @@ -0,0 +1,6 @@ +# Below is a list of people and organizations that have contributed +# to the Flutter project. Names should be added to the list like so: +# +# Name/Organization + +Google Inc. diff --git a/packages/cupertino_ui/CHANGELOG.md b/packages/cupertino_ui/CHANGELOG.md new file mode 100644 index 000000000000..de9bfc1600b8 --- /dev/null +++ b/packages/cupertino_ui/CHANGELOG.md @@ -0,0 +1,3 @@ +## 0.0.1 + +* Initial setup of the `cupertino_ui` package, preparing for decoupling Cupertino widgets from the Flutter framework. diff --git a/packages/cupertino_ui/LICENSE b/packages/cupertino_ui/LICENSE new file mode 100644 index 000000000000..29b709dac6c7 --- /dev/null +++ b/packages/cupertino_ui/LICENSE @@ -0,0 +1,25 @@ +Copyright 2013 The Flutter Authors + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of Google Inc. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/packages/cupertino_ui/README.md b/packages/cupertino_ui/README.md new file mode 100644 index 000000000000..b63de4598733 --- /dev/null +++ b/packages/cupertino_ui/README.md @@ -0,0 +1,24 @@ +# cupertino\_ui + +**Coming soon \- the official Cupertino widget library for Flutter as its own standalone package\!** + +`cupertino_ui` will contain the standard collection of high-fidelity visual components that implement the latest iOS design language (buttons, navigation bars, pickers, etc.). + +**Note:** This package will contain the cupertino library previously part of the Flutter framework itself (`package:flutter/cupertino.dart`). It is being decoupled to allow for faster iteration and a more modular ecosystem. + +## What's (going to be) inside? + +This package will provide the Cupertino widgets you know and love, including but not limited to: + +* **Structure:** `CupertinoPageScaffold`, `CupertinoNavigationBar` +* **Inputs:** `CupertinoButton`, `CupertinoTextField`, `CupertinoSwitch` +* **Dialogs:** `CupertinoAlertDialog`, `CupertinoActionSheet` + +Once landed and published, look forward to updates from [iOS26](https://github.com/flutter/flutter/issues/170310)\! 🚀 + +## Feedback & roadmap + +We are currently migrating the Cupertino library out of the core framework. + +* **Follow the progress:** [Decoupling Github Project](https://github.com/orgs/flutter/projects/220) +* **Report bugs:** [Cupertino issues in Flutter](https://github.com/flutter/flutter/issues?q=is%3Aopen%20is%3Aissue%20label%3A%22f%3A%20cupertino%22) diff --git a/packages/cupertino_ui/lib/cupertino_ui.dart b/packages/cupertino_ui/lib/cupertino_ui.dart new file mode 100644 index 000000000000..44384ed9496e --- /dev/null +++ b/packages/cupertino_ui/lib/cupertino_ui.dart @@ -0,0 +1,10 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/// The Flutter Cupertino Design library. +/// +/// To use, import `package:cupertino_ui/cupertino_ui.dart`. +library cupertino_ui; + +export 'package:flutter/cupertino.dart'; diff --git a/packages/cupertino_ui/pubspec.yaml b/packages/cupertino_ui/pubspec.yaml new file mode 100644 index 000000000000..df913bbfc049 --- /dev/null +++ b/packages/cupertino_ui/pubspec.yaml @@ -0,0 +1,23 @@ +name: cupertino_ui +description: The official Flutter Cupertino Design Library, implementing the iOS design system. +version: 0.0.1 +repository: https://github.com/flutter/packages/tree/main/packages/cupertino_ui +issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A%20cupertino%22 + +environment: + sdk: ^3.9.0 + flutter: ">=3.35.0" + +dependencies: + flutter: + sdk: flutter + +dev_dependencies: + flutter_test: + sdk: flutter + +topics: + - ui + - widgets + - cupertino + - ios diff --git a/packages/cupertino_ui/test/cupertino_ui_test.dart b/packages/cupertino_ui/test/cupertino_ui_test.dart new file mode 100644 index 000000000000..88e2c4b6754f --- /dev/null +++ b/packages/cupertino_ui/test/cupertino_ui_test.dart @@ -0,0 +1,12 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:cupertino_ui/cupertino_ui.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('Cupertino library is exported', (WidgetTester tester) async { + await tester.pumpWidget(const CupertinoApp(home: SizedBox.shrink())); + }); +} diff --git a/packages/espresso/CHANGELOG.md b/packages/espresso/CHANGELOG.md index 571b3af64b04..a48867160766 100644 --- a/packages/espresso/CHANGELOG.md +++ b/packages/espresso/CHANGELOG.md @@ -1,10 +1,28 @@ +## 0.4.0+24 + +* Updates build files from Groovy to Kotlin. + +## 0.4.0+23 + +* Removed the unused `io.flutter.network-policy` metadata tag from the README and example application. + +## 0.4.0+22 + +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. +* Updates README to remove usesCleartextTraffic. Users should use + network security configuration instead. + +## 0.4.0+21 + +* Updates README to reflect currently supported OS version. +* Bumps `com.squareup.okhttp3:okhttp` from 5.3.1 to 5.3.2. + ## 0.4.0+20 * Bumps com.android.tools.build:gradle from 8.12.1 to 8.13.1. ## 0.4.0+19 -* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. * Bumps `com.squareup.okhttp3:okhttp` from 5.3.0 to 5.3.1. ## 0.4.0+18 diff --git a/packages/espresso/README.md b/packages/espresso/README.md index ecab75506c5e..d7c61dc9e407 100644 --- a/packages/espresso/README.md +++ b/packages/espresso/README.md @@ -4,14 +4,32 @@ Provides bindings for Espresso tests of Flutter Android apps. | | Android | |-------------|---------| -| **Support** | SDK 21+ | +| **Support** | SDK 24+ | ## Installation Add the `espresso` package as a `dev_dependency` in your app's pubspec.yaml. If you're testing the example app of a package, add it as a dev_dependency of the main package as well. -Add ```android:usesCleartextTraffic="true"``` in the `````` in the AndroidManifest.xml -of the Android app used for testing. It's best to put this in a debug or androidTest +Since Espresso uses cleartext traffic via a websocket to coordinate +testing, cleartext traffic will need to be enabled for testing. Please +only do this for testing (in debug or androidTest). + +Add ```android:networkSecurityConfig="@xml/network_security_config"``` in the `````` in the AndroidManifest.xml of the Android app used for testing. + +Then you will need to create a `network_security_config.xml` in the `res/xml/` directory. + +```xml + + + + + + +``` + +For example, the Espresso example app has this file in the location `example/android/app/src/debug/res/xml/network_security_config.xml`. + +It is best to put this in a debug or androidTest AndroidManifest.xml so that you don't ship it to end users. (See the example app of this package.) Add the following dependencies in android/app/build.gradle: diff --git a/packages/espresso/android/build.gradle b/packages/espresso/android/build.gradle deleted file mode 100644 index de995198d737..000000000000 --- a/packages/espresso/android/build.gradle +++ /dev/null @@ -1,96 +0,0 @@ -group = 'com.example.espresso' -version = '1.0' - -buildscript { - repositories { - google() - mavenCentral() - } - - dependencies { - classpath 'com.android.tools.build:gradle:8.13.1' - } -} - -rootProject.allprojects { - repositories { - google() - mavenCentral() - } -} - -apply plugin: 'com.android.library' - -android { - namespace = "com.example.espresso" - compileSdk = flutter.compileSdkVersion - - defaultConfig { - minSdkVersion 21 - testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - } - - compileOptions { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 - } - - lintOptions { - checkAllWarnings = true - warningsAsErrors = true - disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency', 'NewerVersionAvailable' - baseline file("lint-baseline.xml") - } - - - testOptions { - unitTests.includeAndroidResources = true - unitTests.returnDefaultValues = true - unitTests.all { - testLogging { - events "passed", "skipped", "failed", "standardOut", "standardError" - outputs.upToDateWhen {false} - showStandardStreams = true - } - } - } -} - -dependencies { - implementation 'com.google.guava:guava:33.5.0-android' - implementation 'com.squareup.okhttp3:okhttp:5.3.1' - implementation 'com.google.code.gson:gson:2.13.2' - androidTestImplementation 'org.hamcrest:hamcrest:3.0' - - testImplementation("junit:junit:4.13.2") - testImplementation("com.google.truth:truth:1.4.5") - api("androidx.test.espresso:espresso-core:3.7.0") - - // Core library - api("androidx.test:core:1.7.0") - - // AndroidJUnitRunner and JUnit Rules - api("androidx.test:runner:1.7.0") - api("androidx.test:rules:1.7.0") - - // Assertions - api("androidx.test.ext:junit:1.3.0") - api("androidx.test.ext:truth:1.7.0") - api("com.google.truth:truth:1.4.5") - - // Espresso dependencies - api("androidx.test.espresso:espresso-core:3.7.0") - api("androidx.test.espresso:espresso-contrib:3.7.0") - api("androidx.test.espresso:espresso-intents:3.7.0") - api("androidx.test.espresso:espresso-accessibility:3.7.0") - api("androidx.test.espresso:espresso-web:3.7.0") - api("androidx.test.espresso.idling:idling-concurrent:3.7.0") - - // The following Espresso dependency can be either "implementation" - // or "androidTestImplementation", depending on whether you want the - // dependency to appear on your APK's compile classpath or the test APK - // classpath. - api("androidx.test.espresso:espresso-idling-resource:3.7.0") -} - - diff --git a/packages/espresso/android/build.gradle.kts b/packages/espresso/android/build.gradle.kts new file mode 100644 index 000000000000..db131e30cfdd --- /dev/null +++ b/packages/espresso/android/build.gradle.kts @@ -0,0 +1,97 @@ +group = "com.example.espresso" +version = "1.0" + +buildscript { + repositories { + google() + mavenCentral() + } + + dependencies { + classpath("com.android.tools.build:gradle:8.13.1") + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +plugins { + id("com.android.library") +} + +android { + namespace = "com.example.espresso" + compileSdk = flutter.compileSdkVersion + + defaultConfig { + minSdk = 24 + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + lint { + checkAllWarnings = true + warningsAsErrors = true + disable.addAll(setOf("AndroidGradlePluginVersion", "InvalidPackage", "GradleDependency", "NewerVersionAvailable")) + baseline = file("lint-baseline.xml") + } + + testOptions { + unitTests { + isIncludeAndroidResources = true + isReturnDefaultValues = true + all { + it.outputs.upToDateWhen { false } + it.testLogging { + events("passed", "skipped", "failed", "standardOut", "standardError") + showStandardStreams = true + } + } + } + } +} + +dependencies { + implementation("com.google.guava:guava:33.5.0-android") + implementation("com.squareup.okhttp3:okhttp:5.3.2") + implementation("com.google.code.gson:gson:2.13.2") + androidTestImplementation("org.hamcrest:hamcrest:3.0") + + testImplementation("junit:junit:4.13.2") + testImplementation("com.google.truth:truth:1.4.5") + api("androidx.test.espresso:espresso-core:3.7.0") + + // Core library + api("androidx.test:core:1.7.0") + + // AndroidJUnitRunner and JUnit Rules + api("androidx.test:runner:1.7.0") + api("androidx.test:rules:1.7.0") + + // Assertions + api("androidx.test.ext:junit:1.3.0") + api("androidx.test.ext:truth:1.7.0") + api("com.google.truth:truth:1.4.5") + + // Espresso dependencies + api("androidx.test.espresso:espresso-core:3.7.0") + api("androidx.test.espresso:espresso-contrib:3.7.0") + api("androidx.test.espresso:espresso-intents:3.7.0") + api("androidx.test.espresso:espresso-accessibility:3.7.0") + api("androidx.test.espresso:espresso-web:3.7.0") + api("androidx.test.espresso.idling:idling-concurrent:3.7.0") + + // The following Espresso dependency can be either "implementation" + // or "androidTestImplementation", depending on whether you want the + // dependency to appear on your APK's compile classpath or the test APK + // classpath. + api("androidx.test.espresso:espresso-idling-resource:3.7.0") +} diff --git a/packages/espresso/android/settings.gradle b/packages/espresso/android/settings.gradle deleted file mode 100644 index 46643c1c5e02..000000000000 --- a/packages/espresso/android/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'espresso' diff --git a/packages/espresso/android/settings.gradle.kts b/packages/espresso/android/settings.gradle.kts new file mode 100644 index 000000000000..ecf97c03a52c --- /dev/null +++ b/packages/espresso/android/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "espresso" diff --git a/packages/espresso/example/android/app/src/debug/AndroidManifest.xml b/packages/espresso/example/android/app/src/debug/AndroidManifest.xml index 482305471f0a..437b06c69bca 100644 --- a/packages/espresso/example/android/app/src/debug/AndroidManifest.xml +++ b/packages/espresso/example/android/app/src/debug/AndroidManifest.xml @@ -3,5 +3,5 @@ to allow setting breakpoints, to provide hot reload, etc. --> - + diff --git a/packages/espresso/example/android/app/src/debug/res/xml/network_security_config.xml b/packages/espresso/example/android/app/src/debug/res/xml/network_security_config.xml new file mode 100644 index 000000000000..3032fe019b57 --- /dev/null +++ b/packages/espresso/example/android/app/src/debug/res/xml/network_security_config.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/packages/espresso/example/android/settings.gradle b/packages/espresso/example/android/settings.gradle index d00a6cf2438a..d7ba8d54ffbc 100644 --- a/packages/espresso/example/android/settings.gradle +++ b/packages/espresso/example/android/settings.gradle @@ -19,8 +19,8 @@ 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.11.0" apply false - id "org.jetbrains.kotlin.android" version "2.2.0" apply false + id "com.android.application" version "8.11.1" apply false + id "org.jetbrains.kotlin.android" version "2.2.20" apply false id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1" } diff --git a/packages/espresso/example/pubspec.yaml b/packages/espresso/example/pubspec.yaml index 895750e7aae5..9a1f546ec4b4 100644 --- a/packages/espresso/example/pubspec.yaml +++ b/packages/espresso/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the espresso plugin. publish_to: none environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" dependencies: flutter: diff --git a/packages/espresso/pubspec.yaml b/packages/espresso/pubspec.yaml index 0e831141c24c..785f52f716f6 100644 --- a/packages/espresso/pubspec.yaml +++ b/packages/espresso/pubspec.yaml @@ -3,7 +3,7 @@ description: Java classes for testing Flutter apps using Espresso. Allows driving Flutter widgets from a native Espresso test. repository: https://github.com/flutter/packages/tree/main/packages/espresso issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+espresso%22 -version: 0.4.0+20 +version: 0.4.0+24 environment: sdk: ^3.9.0 diff --git a/packages/extension_google_sign_in_as_googleapis_auth/CHANGELOG.md b/packages/extension_google_sign_in_as_googleapis_auth/CHANGELOG.md index f9a3e0cb4a86..da46587ad602 100644 --- a/packages/extension_google_sign_in_as_googleapis_auth/CHANGELOG.md +++ b/packages/extension_google_sign_in_as_googleapis_auth/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. ## 3.0.0 diff --git a/packages/extension_google_sign_in_as_googleapis_auth/README.md b/packages/extension_google_sign_in_as_googleapis_auth/README.md index 6490974fd30b..66c9562e388c 100644 --- a/packages/extension_google_sign_in_as_googleapis_auth/README.md +++ b/packages/extension_google_sign_in_as_googleapis_auth/README.md @@ -25,7 +25,7 @@ import 'package:googleapis_auth/googleapis_auth.dart' as auth show AuthClient; final auth.AuthClient client = authorization.authClient(scopes: scopes); // Prepare a People Service authenticated client. - final PeopleServiceApi peopleApi = PeopleServiceApi(client); + final peopleApi = PeopleServiceApi(client); // Retrieve a list of connected contacts' names. final ListConnectionsResponse response = await peopleApi.people.connections .list('people/me', personFields: 'names'); diff --git a/packages/extension_google_sign_in_as_googleapis_auth/example/.metadata b/packages/extension_google_sign_in_as_googleapis_auth/example/.metadata new file mode 100644 index 000000000000..9fb00192b70a --- /dev/null +++ b/packages/extension_google_sign_in_as_googleapis_auth/example/.metadata @@ -0,0 +1,30 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "582a0e7c5581dc0ca5f7bfd8662bb8db6f59d536" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 582a0e7c5581dc0ca5f7bfd8662bb8db6f59d536 + base_revision: 582a0e7c5581dc0ca5f7bfd8662bb8db6f59d536 + - platform: android + create_revision: 582a0e7c5581dc0ca5f7bfd8662bb8db6f59d536 + base_revision: 582a0e7c5581dc0ca5f7bfd8662bb8db6f59d536 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/packages/extension_google_sign_in_as_googleapis_auth/example/android/.gitignore b/packages/extension_google_sign_in_as_googleapis_auth/example/android/.gitignore index 55afd919c659..be3943c96d8e 100644 --- a/packages/extension_google_sign_in_as_googleapis_auth/example/android/.gitignore +++ b/packages/extension_google_sign_in_as_googleapis_auth/example/android/.gitignore @@ -5,6 +5,7 @@ gradle-wrapper.jar /gradlew.bat /local.properties GeneratedPluginRegistrant.java +.cxx/ # Remember to never publicly share your keystore. # See https://flutter.dev/to/reference-keystore diff --git a/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/build.gradle b/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/build.gradle deleted file mode 100644 index 74f99b1b5464..000000000000 --- a/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/build.gradle +++ /dev/null @@ -1,55 +0,0 @@ -plugins { - id "com.android.application" - id "org.jetbrains.kotlin.android" - id "dev.flutter.flutter-gradle-plugin" - id "com.google.gms.google-services" -} - -def localProperties = new Properties() -def localPropertiesFile = rootProject.file('local.properties') -if (localPropertiesFile.exists()) { - localPropertiesFile.withReader('UTF-8') { reader -> - localProperties.load(reader) - } -} - -def flutterVersionCode = localProperties.getProperty('flutter.versionCode') -if (flutterVersionCode == null) { - flutterVersionCode = '1' -} - -def flutterVersionName = localProperties.getProperty('flutter.versionName') -if (flutterVersionName == null) { - flutterVersionName = '1.0' -} - -android { - compileSdk = flutter.compileSdkVersion - - compileOptions { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 - } - - defaultConfig { - // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). - applicationId "io.flutter.plugins.googlesigninexample" - minSdkVersion flutter.minSdkVersion - targetSdkVersion flutter.targetSdkVersion - versionCode flutterVersionCode.toInteger() - versionName flutterVersionName - } - - buildTypes { - release { - // TODO: Add your own signing config for the release build. - // Signing with the debug keys for now, so `flutter run --release` works. - signingConfig = signingConfigs.debug - } - } - namespace = "io.flutter.plugins.googlesigninexample" -} - -flutter { - source = '../..' -} diff --git a/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/build.gradle.kts b/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/build.gradle.kts new file mode 100644 index 000000000000..e9262e9bebd1 --- /dev/null +++ b/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/build.gradle.kts @@ -0,0 +1,39 @@ +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "dev.flutter.extension_google_sign_in_example" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_17.toString() + } + + defaultConfig { + applicationId = "dev.flutter.extension_google_sign_in_example" + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + signingConfig = signingConfigs.getByName("debug") + } + } +} + +flutter { + source = "../.." +} diff --git a/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/src/debug/AndroidManifest.xml b/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/src/debug/AndroidManifest.xml index f880684a6a9c..399f6981d5d3 100644 --- a/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/src/debug/AndroidManifest.xml +++ b/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/src/debug/AndroidManifest.xml @@ -1,5 +1,6 @@ - diff --git a/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/src/main/AndroidManifest.xml b/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/src/main/AndroidManifest.xml index c1040e04aa95..6c2fedd29c99 100644 --- a/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/src/main/AndroidManifest.xml +++ b/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/src/main/AndroidManifest.xml @@ -1,14 +1,16 @@ - + + + + + + diff --git a/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/src/main/java/io/flutter/plugins/googlesigninexample/MainActivity.java b/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/src/main/java/io/flutter/plugins/googlesigninexample/MainActivity.java deleted file mode 100644 index 399b341fae33..000000000000 --- a/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/src/main/java/io/flutter/plugins/googlesigninexample/MainActivity.java +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package io.flutter.plugins.googlesigninexample; - -import io.flutter.embedding.android.FlutterActivity; - -public class MainActivity extends FlutterActivity {} diff --git a/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/src/main/kotlin/dev/flutter/extension_google_sign_in_example/MainActivity.kt b/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/src/main/kotlin/dev/flutter/extension_google_sign_in_example/MainActivity.kt new file mode 100644 index 000000000000..e409703572ef --- /dev/null +++ b/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/src/main/kotlin/dev/flutter/extension_google_sign_in_example/MainActivity.kt @@ -0,0 +1,9 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package dev.flutter.extension_google_sign_in_example + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/src/main/res/values-night/styles.xml b/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/src/main/res/values-night/styles.xml index 449a9f930826..06952be745f9 100644 --- a/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/src/main/res/values-night/styles.xml +++ b/packages/extension_google_sign_in_as_googleapis_auth/example/android/app/src/main/res/values-night/styles.xml @@ -3,14 +3,14 @@ - ... - -... -``` - -If you don't have a `styles.xml` file for your Android project you can set up -the Android theme directly in `android/app/src/main/AndroidManifest.xml`: - -```xml -... - - - -... -``` diff --git a/packages/local_auth/local_auth/example/android/app/gradle/wrapper/gradle-wrapper.properties b/packages/local_auth/local_auth/example/android/app/gradle/wrapper/gradle-wrapper.properties index 0c68fbc1dadd..4a647536b632 100644 --- a/packages/local_auth/local_auth/example/android/app/gradle/wrapper/gradle-wrapper.properties +++ b/packages/local_auth/local_auth/example/android/app/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.0-all.zip +networkTimeout=10000 zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists - diff --git a/packages/local_auth/local_auth/example/android/settings.gradle b/packages/local_auth/local_auth/example/android/settings.gradle index d00a6cf2438a..d7ba8d54ffbc 100644 --- a/packages/local_auth/local_auth/example/android/settings.gradle +++ b/packages/local_auth/local_auth/example/android/settings.gradle @@ -19,8 +19,8 @@ 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.11.0" apply false - id "org.jetbrains.kotlin.android" version "2.2.0" apply false + id "com.android.application" version "8.11.1" apply false + id "org.jetbrains.kotlin.android" version "2.2.20" apply false id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1" } diff --git a/packages/local_auth/local_auth/example/ios/Flutter/AppFrameworkInfo.plist b/packages/local_auth/local_auth/example/ios/Flutter/AppFrameworkInfo.plist index 7c5696400627..391a902b2beb 100644 --- a/packages/local_auth/local_auth/example/ios/Flutter/AppFrameworkInfo.plist +++ b/packages/local_auth/local_auth/example/ios/Flutter/AppFrameworkInfo.plist @@ -20,7 +20,5 @@ ???? CFBundleVersion 1.0 - MinimumOSVersion - 12.0 diff --git a/packages/local_auth/local_auth/example/ios/Flutter/Debug.xcconfig b/packages/local_auth/local_auth/example/ios/Flutter/Debug.xcconfig index ec97fc6f3021..592ceee85b89 100644 --- a/packages/local_auth/local_auth/example/ios/Flutter/Debug.xcconfig +++ b/packages/local_auth/local_auth/example/ios/Flutter/Debug.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" diff --git a/packages/local_auth/local_auth/example/ios/Flutter/Release.xcconfig b/packages/local_auth/local_auth/example/ios/Flutter/Release.xcconfig index c4855bfe2000..592ceee85b89 100644 --- a/packages/local_auth/local_auth/example/ios/Flutter/Release.xcconfig +++ b/packages/local_auth/local_auth/example/ios/Flutter/Release.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" diff --git a/packages/local_auth/local_auth/example/ios/Podfile b/packages/local_auth/local_auth/example/ios/Podfile deleted file mode 100644 index 01d4aa611bb9..000000000000 --- a/packages/local_auth/local_auth/example/ios/Podfile +++ /dev/null @@ -1,40 +0,0 @@ -# Uncomment this line to define a global platform for your project -# platform :ios, '12.0' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_ios_podfile_setup - -target 'Runner' do - use_frameworks! - - flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_ios_build_settings(target) - end -end diff --git a/packages/local_auth/local_auth/example/ios/Runner.xcodeproj/project.pbxproj b/packages/local_auth/local_auth/example/ios/Runner.xcodeproj/project.pbxproj index a20e9aef4f83..20a6988a2688 100644 --- a/packages/local_auth/local_auth/example/ios/Runner.xcodeproj/project.pbxproj +++ b/packages/local_auth/local_auth/example/ios/Runner.xcodeproj/project.pbxproj @@ -11,7 +11,6 @@ 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; - 905EA9BD53427D1D5E0201A2 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 169A659354207B8020CBAFB2 /* Pods_Runner.framework */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; @@ -33,10 +32,10 @@ /* Begin PBXFileReference section */ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; - 169A659354207B8020CBAFB2 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; @@ -45,9 +44,6 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - AECAD9C32C456B72E1EF15CD /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; - CDAA31899F46B683C7DF728E /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; - F0A765C02B9418ADA41B9FA9 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -56,7 +52,6 @@ buildActionMask = 2147483647; files = ( 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, - 905EA9BD53427D1D5E0201A2 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -66,24 +61,14 @@ 2059D689E1C5DE4B00CC4552 /* Pods */ = { isa = PBXGroup; children = ( - AECAD9C32C456B72E1EF15CD /* Pods-Runner.debug.xcconfig */, - F0A765C02B9418ADA41B9FA9 /* Pods-Runner.release.xcconfig */, - CDAA31899F46B683C7DF728E /* Pods-Runner.profile.xcconfig */, ); path = Pods; sourceTree = ""; }; - 746CA8E7C5F07CD712AE0A0A /* Frameworks */ = { - isa = PBXGroup; - children = ( - 169A659354207B8020CBAFB2 /* Pods_Runner.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, 9740EEB21CF90195004384FC /* Debug.xcconfig */, 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, @@ -99,7 +84,6 @@ 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, 2059D689E1C5DE4B00CC4552 /* Pods */, - 746CA8E7C5F07CD712AE0A0A /* Frameworks */, ); sourceTree = ""; }; @@ -133,7 +117,6 @@ isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - 3CA2A081CA18BC0C652EA199 /* [CP] Check Pods Manifest.lock */, 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, @@ -221,28 +204,6 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; }; - 3CA2A081CA18BC0C652EA199 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; 9740EEB61CF901F6004384FC /* Run Script */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; @@ -335,7 +296,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -414,7 +375,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -465,7 +426,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; diff --git a/packages/local_auth/local_auth/example/lib/main.dart b/packages/local_auth/local_auth/example/lib/main.dart index 384f71f801c3..4dfc1b86b791 100644 --- a/packages/local_auth/local_auth/example/lib/main.dart +++ b/packages/local_auth/local_auth/example/lib/main.dart @@ -76,7 +76,7 @@ class _MyAppState extends State { } Future _authenticate() async { - bool authenticated = false; + var authenticated = false; try { setState(() { _isAuthenticating = true; @@ -118,7 +118,7 @@ class _MyAppState extends State { } Future _authenticateWithBiometrics() async { - bool authenticated = false; + var authenticated = false; try { setState(() { _isAuthenticating = true; @@ -157,7 +157,7 @@ class _MyAppState extends State { return; } - final String message = authenticated ? 'Authorized' : 'Not Authorized'; + final message = authenticated ? 'Authorized' : 'Not Authorized'; setState(() { _authorized = message; }); diff --git a/packages/local_auth/local_auth/example/macos/Flutter/Flutter-Debug.xcconfig b/packages/local_auth/local_auth/example/macos/Flutter/Flutter-Debug.xcconfig index 4b81f9b2d200..c2efd0b608ba 100644 --- a/packages/local_auth/local_auth/example/macos/Flutter/Flutter-Debug.xcconfig +++ b/packages/local_auth/local_auth/example/macos/Flutter/Flutter-Debug.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" diff --git a/packages/local_auth/local_auth/example/macos/Flutter/Flutter-Release.xcconfig b/packages/local_auth/local_auth/example/macos/Flutter/Flutter-Release.xcconfig index 5caa9d1579e4..c2efd0b608ba 100644 --- a/packages/local_auth/local_auth/example/macos/Flutter/Flutter-Release.xcconfig +++ b/packages/local_auth/local_auth/example/macos/Flutter/Flutter-Release.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" diff --git a/packages/local_auth/local_auth/example/macos/Podfile b/packages/local_auth/local_auth/example/macos/Podfile deleted file mode 100644 index ae77cc1d4269..000000000000 --- a/packages/local_auth/local_auth/example/macos/Podfile +++ /dev/null @@ -1,39 +0,0 @@ -platform :osx, '10.14' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\"" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_macos_podfile_setup - -target 'Runner' do - use_frameworks! - - flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__)) -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_macos_build_settings(target) - end -end diff --git a/packages/local_auth/local_auth/example/macos/Runner.xcodeproj/project.pbxproj b/packages/local_auth/local_auth/example/macos/Runner.xcodeproj/project.pbxproj index bd43df3d0713..c4a9fd421b0f 100644 --- a/packages/local_auth/local_auth/example/macos/Runner.xcodeproj/project.pbxproj +++ b/packages/local_auth/local_auth/example/macos/Runner.xcodeproj/project.pbxproj @@ -21,7 +21,6 @@ /* End PBXAggregateTarget section */ /* Begin PBXBuildFile section */ - 1BC2DC09A8E94B377F42CF98 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AE72E01DCF4158EA81E6F9AC /* Pods_Runner.framework */; }; 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; @@ -54,8 +53,6 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 09A2351319B85EBB2712065D /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; - 206B53A30EED4EAA41637C9C /* 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 = ""; }; 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; 33CC10ED2044A3C60003C045 /* example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = example.app; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -70,14 +67,9 @@ 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; - 48ED168D9C105B30C2229B4F /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; - 84B2F8C324D0BC6169CF7C4A /* 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 = ""; }; - 8FAE613E79CDA0335C27BB71 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; - 941800DCC46CF3A6E134F013 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; - AE72E01DCF4158EA81E6F9AC /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - C0EE013DE4EFF82F20A45B81 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -86,7 +78,6 @@ buildActionMask = 2147483647; files = ( 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, - 1BC2DC09A8E94B377F42CF98 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -110,7 +101,6 @@ 33FAB671232836740065AC1E /* Runner */, 33CEB47122A05771004F2AC0 /* Flutter */, 33CC10EE2044A3C60003C045 /* Products */, - D73912EC22F37F3D000D13A0 /* Frameworks */, F749529E0EAC4E62673B56C1 /* Pods */, ); sourceTree = ""; @@ -137,6 +127,7 @@ 33CEB47122A05771004F2AC0 /* Flutter */ = { isa = PBXGroup; children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, @@ -158,24 +149,9 @@ path = Runner; sourceTree = ""; }; - D73912EC22F37F3D000D13A0 /* Frameworks */ = { - isa = PBXGroup; - children = ( - AE72E01DCF4158EA81E6F9AC /* Pods_Runner.framework */, - 941800DCC46CF3A6E134F013 /* Pods_RunnerTests.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; F749529E0EAC4E62673B56C1 /* Pods */ = { isa = PBXGroup; children = ( - C0EE013DE4EFF82F20A45B81 /* Pods-Runner.debug.xcconfig */, - 8FAE613E79CDA0335C27BB71 /* Pods-Runner.release.xcconfig */, - 48ED168D9C105B30C2229B4F /* Pods-Runner.profile.xcconfig */, - 206B53A30EED4EAA41637C9C /* Pods-RunnerTests.debug.xcconfig */, - 84B2F8C324D0BC6169CF7C4A /* Pods-RunnerTests.release.xcconfig */, - 09A2351319B85EBB2712065D /* Pods-RunnerTests.profile.xcconfig */, ); path = Pods; sourceTree = ""; @@ -187,7 +163,6 @@ isa = PBXNativeTarget; buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - 43C24571E48B9A5309B915D5 /* [CP] Check Pods Manifest.lock */, 33CC10E92044A3C60003C045 /* Sources */, 33CC10EA2044A3C60003C045 /* Frameworks */, 33CC10EB2044A3C60003C045 /* Resources */, @@ -307,28 +282,6 @@ shellPath = /bin/sh; shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; }; - 43C24571E48B9A5309B915D5 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -406,7 +359,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; + MACOSX_DEPLOYMENT_TARGET = 10.15; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; @@ -488,7 +441,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; + MACOSX_DEPLOYMENT_TARGET = 10.15; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = macosx; @@ -538,7 +491,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; + MACOSX_DEPLOYMENT_TARGET = 10.15; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; diff --git a/packages/local_auth/local_auth/pubspec.yaml b/packages/local_auth/local_auth/pubspec.yaml index 60921b1afd90..e1a68b7c7fe0 100644 --- a/packages/local_auth/local_auth/pubspec.yaml +++ b/packages/local_auth/local_auth/pubspec.yaml @@ -2,7 +2,7 @@ name: local_auth description: Flutter plugin to allow local authentication via biometrics, passcode, pin, or pattern. repository: https://github.com/flutter/packages/tree/main/packages/local_auth/local_auth issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+local_auth%22 -version: 3.0.0 +version: 3.0.1 environment: sdk: ^3.9.0 diff --git a/packages/local_auth/local_auth_android/CHANGELOG.md b/packages/local_auth/local_auth_android/CHANGELOG.md index 920c11cae754..5e329a9a2d26 100644 --- a/packages/local_auth/local_auth_android/CHANGELOG.md +++ b/packages/local_auth/local_auth_android/CHANGELOG.md @@ -1,3 +1,19 @@ +## 2.0.7 + +* Updates build files from Groovy to Kotlin. + +## 2.0.6 + +* Bumps androidx.core:core from 1.17.0 to 1.18.0. + +## 2.0.5 + +* Adds platform-specific setup instructions to README. + +## 2.0.4 + +* Bumps androidx.core:core from 1.13.1 to 1.17.0. + ## 2.0.3 * Bumps com.android.tools.build:gradle from 8.12.1 to 8.13.1. diff --git a/packages/local_auth/local_auth_android/README.md b/packages/local_auth/local_auth_android/README.md index d9e3b8bba796..023c74592ac7 100644 --- a/packages/local_auth/local_auth_android/README.md +++ b/packages/local_auth/local_auth_android/README.md @@ -11,5 +11,75 @@ so you do not need to add it to your `pubspec.yaml`. However, if you `import` this package to use any of its APIs directly, you should add it to your `pubspec.yaml` as usual. +## Setup + +### Activity Changes + +`local_auth` requires the use of a `FragmentActivity` instead of an +`Activity`. To update your application: + +* If you are using `FlutterActivity` directly, change it to +`FlutterFragmentActivity` in your `AndroidManifest.xml`. +* If you are using a custom activity, update your `MainActivity.kt` to + inherit from `FlutterFragmentActivity`: + + ```kotlin + import io.flutter.embedding.android.FlutterFragmentActivity + + class MainActivity: FlutterFragmentActivity() { + // ... + } + ``` + +### Permissions + +Update your project's `AndroidManifest.xml` file to include the +[`USE_BIOMETRIC` permission][3]: + +```xml + + + +``` + +### Android theme + +Your `LaunchTheme`'s parent must be a valid `Theme.AppCompat` theme to prevent +crashes on Android 8 and below. For example, use `Theme.AppCompat.DayNight` to +enable light/dark modes for the biometric dialog. To do that go to +`android/app/src/main/res/values/styles.xml` and look for the style with name +`LaunchTheme`. Then change the parent for that style as follows: + +```xml +... + + + ... + +... +``` + +If you don't have a `styles.xml` file for your Android project you can set up +the Android theme directly in `android/app/src/main/AndroidManifest.xml`: + +```xml +... + + + +... +``` + + [1]: https://pub.dev/packages/local_auth [2]: https://flutter.dev/to/endorsed-federated-plugin +[3]: https://developer.android.com/reference/android/Manifest.permission#USE_BIOMETRIC diff --git a/packages/local_auth/local_auth_android/android/build.gradle b/packages/local_auth/local_auth_android/android/build.gradle deleted file mode 100644 index 6ab31901258a..000000000000 --- a/packages/local_auth/local_auth_android/android/build.gradle +++ /dev/null @@ -1,68 +0,0 @@ -group = 'io.flutter.plugins.localauth' -version = '1.0-SNAPSHOT' - -buildscript { - repositories { - google() - mavenCentral() - } - - dependencies { - classpath 'com.android.tools.build:gradle:8.13.1' - } -} - -rootProject.allprojects { - repositories { - google() - mavenCentral() - } -} - -apply plugin: 'com.android.library' - -android { - namespace = "io.flutter.plugins.localauth" - compileSdk = flutter.compileSdkVersion - - defaultConfig { - minSdkVersion 24 - testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - } - - compileOptions { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 - } - - lintOptions { - checkAllWarnings = true - warningsAsErrors = true - disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency', 'NewerVersionAvailable' - } - - - testOptions { - unitTests.includeAndroidResources = true - unitTests.returnDefaultValues = true - unitTests.all { - testLogging { - events "passed", "skipped", "failed", "standardOut", "standardError" - outputs.upToDateWhen {false} - showStandardStreams = true - } - } - } -} - -dependencies { - api("androidx.core:core:1.13.1") - api("androidx.biometric:biometric:1.1.0") - api("androidx.fragment:fragment:1.8.9") - testImplementation("junit:junit:4.13.2") - testImplementation("org.mockito:mockito-core:5.20.0") - testImplementation("org.robolectric:robolectric:4.16") - androidTestImplementation("androidx.test:runner:1.7.0") - androidTestImplementation("androidx.test:rules:1.7.0") - androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0") -} diff --git a/packages/local_auth/local_auth_android/android/build.gradle.kts b/packages/local_auth/local_auth_android/android/build.gradle.kts new file mode 100644 index 000000000000..11af0e4afa4e --- /dev/null +++ b/packages/local_auth/local_auth_android/android/build.gradle.kts @@ -0,0 +1,71 @@ +group = "io.flutter.plugins.localauth" +version = "1.0-SNAPSHOT" + +buildscript { + repositories { + google() + mavenCentral() + } + + dependencies { + classpath("com.android.tools.build:gradle:8.13.1") + } +} + +rootProject.allprojects { + repositories { + google() + mavenCentral() + } +} + +plugins { + id("com.android.library") +} + +android { + namespace = "io.flutter.plugins.localauth" + compileSdk = flutter.compileSdkVersion + + defaultConfig { + minSdk = 24 + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + lint { + checkAllWarnings = true + warningsAsErrors = true + disable.addAll(setOf("AndroidGradlePluginVersion", "InvalidPackage", "GradleDependency", "NewerVersionAvailable")) + } + + testOptions { + unitTests { + isIncludeAndroidResources = true + isReturnDefaultValues = true + all { + it.outputs.upToDateWhen { false } + it.testLogging { + events("passed", "skipped", "failed", "standardOut", "standardError") + showStandardStreams = true + } + } + } + } +} + +dependencies { + api("androidx.core:core:1.18.0") + api("androidx.biometric:biometric:1.1.0") + api("androidx.fragment:fragment:1.8.9") + testImplementation("junit:junit:4.13.2") + testImplementation("org.mockito:mockito-core:5.23.0") + testImplementation("org.robolectric:robolectric:4.16") + androidTestImplementation("androidx.test:runner:1.7.0") + androidTestImplementation("androidx.test:rules:1.7.0") + androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0") +} diff --git a/packages/local_auth/local_auth_android/android/settings.gradle b/packages/local_auth/local_auth_android/android/settings.gradle deleted file mode 100644 index dca8c623fdf6..000000000000 --- a/packages/local_auth/local_auth_android/android/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'local_auth' diff --git a/packages/local_auth/local_auth_android/android/settings.gradle.kts b/packages/local_auth/local_auth_android/android/settings.gradle.kts new file mode 100644 index 000000000000..3d731a10b076 --- /dev/null +++ b/packages/local_auth/local_auth_android/android/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "local_auth" diff --git a/packages/local_auth/local_auth_android/example/android/app/gradle/wrapper/gradle-wrapper.properties b/packages/local_auth/local_auth_android/example/android/app/gradle/wrapper/gradle-wrapper.properties index 0c68fbc1dadd..5f27b2cde1bb 100644 --- a/packages/local_auth/local_auth_android/example/android/app/gradle/wrapper/gradle-wrapper.properties +++ b/packages/local_auth/local_auth_android/example/android/app/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-all.zip +networkTimeout=10000 zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists - diff --git a/packages/local_auth/local_auth_android/example/android/settings.gradle b/packages/local_auth/local_auth_android/example/android/settings.gradle index d00a6cf2438a..d7ba8d54ffbc 100644 --- a/packages/local_auth/local_auth_android/example/android/settings.gradle +++ b/packages/local_auth/local_auth_android/example/android/settings.gradle @@ -19,8 +19,8 @@ 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.11.0" apply false - id "org.jetbrains.kotlin.android" version "2.2.0" apply false + id "com.android.application" version "8.11.1" apply false + id "org.jetbrains.kotlin.android" version "2.2.20" apply false id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1" } diff --git a/packages/local_auth/local_auth_android/example/lib/main.dart b/packages/local_auth/local_auth_android/example/lib/main.dart index 7e1ac81d1b1b..ed2cfea72162 100644 --- a/packages/local_auth/local_auth_android/example/lib/main.dart +++ b/packages/local_auth/local_auth_android/example/lib/main.dart @@ -78,7 +78,7 @@ class _MyAppState extends State { } Future _authenticate() async { - bool authenticated = false; + var authenticated = false; try { setState(() { _isAuthenticating = true; @@ -120,7 +120,7 @@ class _MyAppState extends State { } Future _authenticateWithBiometrics() async { - bool authenticated = false; + var authenticated = false; try { setState(() { _isAuthenticating = true; @@ -161,7 +161,7 @@ class _MyAppState extends State { return; } - final String message = authenticated ? 'Authorized' : 'Not Authorized'; + final message = authenticated ? 'Authorized' : 'Not Authorized'; setState(() { _authorized = message; }); diff --git a/packages/local_auth/local_auth_android/lib/local_auth_android.dart b/packages/local_auth/local_auth_android/lib/local_auth_android.dart index af9289be3f22..017eb07a897d 100644 --- a/packages/local_auth/local_auth_android/lib/local_auth_android.dart +++ b/packages/local_auth/local_auth_android/lib/local_auth_android.dart @@ -148,7 +148,7 @@ class LocalAuthAndroid extends LocalAuthPlatform { Iterable messagesList, ) { AndroidAuthMessages? messages; - for (final AuthMessages entry in messagesList) { + for (final entry in messagesList) { if (entry is AndroidAuthMessages) { messages = entry; } diff --git a/packages/local_auth/local_auth_android/pubspec.yaml b/packages/local_auth/local_auth_android/pubspec.yaml index e3f1c1440515..a53ab31388ce 100644 --- a/packages/local_auth/local_auth_android/pubspec.yaml +++ b/packages/local_auth/local_auth_android/pubspec.yaml @@ -2,7 +2,7 @@ name: local_auth_android description: Android implementation of the local_auth plugin. repository: https://github.com/flutter/packages/tree/main/packages/local_auth/local_auth_android issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+local_auth%22 -version: 2.0.3 +version: 2.0.7 environment: sdk: ^3.9.0 diff --git a/packages/local_auth/local_auth_android/test/local_auth_test.dart b/packages/local_auth/local_auth_android/test/local_auth_test.dart index 8b2a109f96ac..ffc36392ade5 100644 --- a/packages/local_auth/local_auth_android/test/local_auth_test.dart +++ b/packages/local_auth/local_auth_android/test/local_auth_test.dart @@ -109,7 +109,7 @@ void main() { api.authenticate(any, any), ).thenAnswer((_) async => AuthResult(code: AuthResultCode.success)); - const String reason = 'test reason'; + const reason = 'test reason'; await plugin.authenticate( localizedReason: reason, authMessages: [], @@ -118,7 +118,7 @@ void main() { final VerificationResult result = verify( api.authenticate(any, captureAny), ); - final AuthStrings strings = result.captured[0] as AuthStrings; + final strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); // These should all be the default values from // auth_messages_android.dart @@ -134,7 +134,7 @@ void main() { api.authenticate(any, any), ).thenAnswer((_) async => AuthResult(code: AuthResultCode.success)); - const String reason = 'test reason'; + const reason = 'test reason'; await plugin.authenticate( localizedReason: reason, authMessages: [AnotherPlatformAuthMessages()], @@ -143,7 +143,7 @@ void main() { final VerificationResult result = verify( api.authenticate(any, captureAny), ); - final AuthStrings strings = result.captured[0] as AuthStrings; + final strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); // These should all be the default values from // auth_messages_android.dart @@ -161,10 +161,10 @@ void main() { // These are arbitrary values; all that matters is that: // - they are different from the defaults, and // - they are different from each other. - const String reason = 'A'; - const String hint = 'B'; - const String cancel = 'C'; - const String signInTitle = 'D'; + const reason = 'A'; + const hint = 'B'; + const cancel = 'C'; + const signInTitle = 'D'; await plugin.authenticate( localizedReason: reason, authMessages: [ @@ -180,7 +180,7 @@ void main() { final VerificationResult result = verify( api.authenticate(any, captureAny), ); - final AuthStrings strings = result.captured[0] as AuthStrings; + final strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); expect(strings.signInHint, hint); expect(strings.cancelButton, cancel); @@ -195,9 +195,9 @@ void main() { // These are arbitrary values; all that matters is that: // - they are different from the defaults, and // - they are different from each other. - const String reason = 'A'; - const String hint = 'B'; - const String cancel = 'C'; + const reason = 'A'; + const hint = 'B'; + const cancel = 'C'; await plugin.authenticate( localizedReason: reason, authMessages: [ @@ -208,7 +208,7 @@ void main() { final VerificationResult result = verify( api.authenticate(any, captureAny), ); - final AuthStrings strings = result.captured[0] as AuthStrings; + final strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); // These should all be the provided values. expect(strings.signInHint, hint); @@ -233,7 +233,7 @@ void main() { final VerificationResult result = verify( api.authenticate(captureAny, any), ); - final AuthOptions options = result.captured[0] as AuthOptions; + final options = result.captured[0] as AuthOptions; expect(options.biometricOnly, false); expect(options.sensitiveTransaction, true); expect(options.sticky, false); @@ -257,7 +257,7 @@ void main() { final VerificationResult result = verify( api.authenticate(captureAny, any), ); - final AuthOptions options = result.captured[0] as AuthOptions; + final options = result.captured[0] as AuthOptions; expect(options.biometricOnly, true); expect(options.sensitiveTransaction, false); expect(options.sticky, true); @@ -630,7 +630,7 @@ void main() { test( 'converts unknownError to unknownError LocalAuthException, passing error message', () async { - const String errorMessage = 'Some error message'; + const errorMessage = 'Some error message'; when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResult( code: AuthResultCode.unknownError, diff --git a/packages/local_auth/local_auth_darwin/CHANGELOG.md b/packages/local_auth/local_auth_darwin/CHANGELOG.md index 082a2438c3f9..f91a397810a7 100644 --- a/packages/local_auth/local_auth_darwin/CHANGELOG.md +++ b/packages/local_auth/local_auth_darwin/CHANGELOG.md @@ -1,3 +1,12 @@ +## 2.0.3 + +* Adds iOS setup instructions to README. + +## 2.0.2 + +* Improves compatibility with UIScene. +* Updates minimum supported SDK version to Flutter 3.38/Dart 3.10. + ## 2.0.1 * Updates to Pigeon 26. diff --git a/packages/local_auth/local_auth_darwin/README.md b/packages/local_auth/local_auth_darwin/README.md index 39650ce1110f..e56cc4c98086 100644 --- a/packages/local_auth/local_auth_darwin/README.md +++ b/packages/local_auth/local_auth_darwin/README.md @@ -11,5 +11,16 @@ so you do not need to add it to your `pubspec.yaml`. However, if you `import` this package to use any of its APIs directly, you should add it to your `pubspec.yaml` as usual. +## Setup + +To support Face ID on iOS devices, you must add an +[`NSFaceIDUsageDescription`][3] entry to your `Info.plist` file: + +```xml +NSFaceIDUsageDescription +Explain why your app needs Face ID access here. +``` + [1]: https://pub.dev/packages/local_auth [2]: https://flutter.dev/to/endorsed-federated-plugin +[3]: https://developer.apple.com/documentation/bundleresources/information-property-list/nsfaceidusagedescription diff --git a/packages/local_auth/local_auth_darwin/darwin/Tests/FLALocalAuthPluginTests.swift b/packages/local_auth/local_auth_darwin/darwin/Tests/FLALocalAuthPluginTests.swift index 719839797334..492a949dacd1 100644 --- a/packages/local_auth/local_auth_darwin/darwin/Tests/FLALocalAuthPluginTests.swift +++ b/packages/local_auth/local_auth_darwin/darwin/Tests/FLALocalAuthPluginTests.swift @@ -3,7 +3,7 @@ // found in the LICENSE file. import LocalAuthentication -import XCTest +import Testing @testable import local_auth_darwin @@ -25,12 +25,12 @@ final class StubAuthContextFactory: AuthContextFactory { } func createAuthContext() -> AuthContext { - XCTAssert(self.contexts.count > 0, "Insufficient test contexts provided") + #expect(self.contexts.count > 0, "Insufficient test contexts provided") return self.contexts.removeFirst() } } -final class StubAuthContext: NSObject, AuthContext { +final class StubAuthContext: NSObject, AuthContext, @unchecked Sendable { /// Whether calls to this stub are expected to be for biometric authentication. /// /// While this object could be set up to return different values for different policies, in @@ -49,9 +49,11 @@ final class StubAuthContext: NSObject, AuthContext { var localizedFallbackTitle: String? func canEvaluatePolicy(_ policy: LAPolicy, error: NSErrorPointer) -> Bool { - XCTAssertEqual( - policy, - expectBiometrics ? .deviceOwnerAuthenticationWithBiometrics : .deviceOwnerAuthentication) + #expect( + policy + == (expectBiometrics + ? .deviceOwnerAuthenticationWithBiometrics : .deviceOwnerAuthentication) + ) if let canEvaluateError = canEvaluateError { error?.pointee = canEvaluateError } @@ -59,11 +61,13 @@ final class StubAuthContext: NSObject, AuthContext { } func evaluatePolicy( - _ policy: LAPolicy, localizedReason: String, reply: @escaping (Bool, Error?) -> Void + _ policy: LAPolicy, localizedReason: String, reply: @escaping @Sendable (Bool, Error?) -> Void ) { - XCTAssertEqual( - policy, - expectBiometrics ? .deviceOwnerAuthenticationWithBiometrics : .deviceOwnerAuthentication) + #expect( + policy + == (expectBiometrics + ? .deviceOwnerAuthenticationWithBiometrics : .deviceOwnerAuthentication) + ) // evaluatePolicy:localizedReason:reply: calls back on an internal queue, which is not // guaranteed to be on the main thread. Ensure that's handled correctly by calling back on // a background thread. @@ -75,10 +79,11 @@ final class StubAuthContext: NSObject, AuthContext { // MARK: - -class LocalAuthPluginTests: XCTestCase { +@MainActor +struct LocalAuthPluginTests { - @MainActor - func testSuccessfullAuthWithBiometrics() throws { + @Test + func successfullAuthWithBiometrics() async { let stubAuthContext = StubAuthContext() let plugin = LocalAuthPlugin( contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) @@ -86,182 +91,93 @@ class LocalAuthPluginTests: XCTestCase { let strings = createAuthStrings() stubAuthContext.expectBiometrics = true stubAuthContext.evaluateResponse = true - let expectation = expectation(description: "Result is called") - plugin.authenticate( - options: AuthOptions(biometricOnly: true, sticky: false), - strings: strings - ) { resultDetails in - switch resultDetails { - case .success(let successDetails): - XCTAssertEqual(successDetails.result, .success) - case .failure(let error): - XCTFail("Unexpected error: \(error)") - } - expectation.fulfill() - } - self.waitForExpectations(timeout: timeout) - } - - @MainActor - func testSuccessfullAuthWithoutBiometrics() { - let stubAuthContext = StubAuthContext() - let plugin = LocalAuthPlugin( - contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) - - let strings = createAuthStrings() - stubAuthContext.evaluateResponse = true - let expectation = expectation(description: "Result is called") - plugin.authenticate( - options: AuthOptions(biometricOnly: false, sticky: false), - strings: strings - ) { resultDetails in - switch resultDetails { - case .success(let successDetails): - XCTAssertEqual(successDetails.result, .success) - case .failure(let error): - XCTFail("Unexpected error: \(error)") - } - expectation.fulfill() - } - self.waitForExpectations(timeout: timeout) - } - - @MainActor - func testFailedAuthWithBiometrics() { - let stubAuthContext = StubAuthContext() - let plugin = LocalAuthPlugin( - contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) - - let strings = createAuthStrings() - stubAuthContext.expectBiometrics = true - stubAuthContext.evaluateError = NSError( - domain: "error", code: LAError.authenticationFailed.rawValue) - - let expectation = expectation(description: "Result is called") - plugin.authenticate( - options: AuthOptions(biometricOnly: true, sticky: false), - strings: strings - ) { resultDetails in - switch resultDetails { - case .success(let successDetails): - XCTAssertEqual(successDetails.result, .authenticationFailed) - case .failure(let error): - XCTFail("Unexpected error: \(error)") + await withCheckedContinuation { continuation in + plugin.authenticate( + options: AuthOptions(biometricOnly: true, sticky: false), + strings: strings + ) { resultDetails in + switch resultDetails { + case .success(let successDetails): + #expect(successDetails.result == .success) + case .failure(let error): + Issue.record("Unexpected error: \(error)") + } + continuation.resume() } - expectation.fulfill() } - self.waitForExpectations(timeout: timeout) } - @MainActor - func testFailedAuthWithErrorAppCancel() { + @Test + func successfulAuthWithoutBiometrics() async { let stubAuthContext = StubAuthContext() let plugin = LocalAuthPlugin( contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) let strings = createAuthStrings() - stubAuthContext.evaluateError = NSError( - domain: "LocalAuthentication", code: LAError.appCancel.rawValue) - - let expectation = expectation(description: "Result is called") - plugin.authenticate( - options: AuthOptions(biometricOnly: false, sticky: false), - strings: strings - ) { resultDetails in - switch resultDetails { - case .success(let successDetails): - XCTAssertEqual(successDetails.result, .appCancel) - case .failure(let error): - XCTFail("Unexpected error: \(error)") - } - expectation.fulfill() - } - self.waitForExpectations(timeout: timeout) - } - - @MainActor - func testFailedAuthWithErrorSystemCancel() { - let stubAuthContext = StubAuthContext() - let plugin = LocalAuthPlugin( - contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) + stubAuthContext.evaluateResponse = true - let strings = createAuthStrings() - stubAuthContext.evaluateError = NSError( - domain: "LocalAuthentication", code: LAError.systemCancel.rawValue) - - let expectation = expectation(description: "Result is called") - plugin.authenticate( - options: AuthOptions(biometricOnly: false, sticky: false), - strings: strings - ) { resultDetails in - switch resultDetails { - case .success(let successDetails): - XCTAssertEqual(successDetails.result, .systemCancel) - case .failure(let error): - XCTFail("Unexpected error: \(error)") + await withCheckedContinuation { continuation in + plugin.authenticate( + options: AuthOptions(biometricOnly: false, sticky: false), + strings: strings + ) { resultDetails in + switch resultDetails { + case .success(let successDetails): + #expect(successDetails.result == .success) + case .failure(let error): + Issue.record("Unexpected error: \(error)") + } + continuation.resume() } - expectation.fulfill() } - self.waitForExpectations(timeout: timeout) } - @MainActor - func testFailedAuthWithErrorUserCancel() { + @Test(arguments: [ + (LAError.authenticationFailed.rawValue, AuthResult.authenticationFailed, true), + (LAError.appCancel.rawValue, .appCancel, false), + (LAError.systemCancel.rawValue, .systemCancel, false), + (LAError.userCancel.rawValue, .userCancel, false), + (LAError.userFallback.rawValue, .userFallback, false), + (99, .unknownError, false), + (LAError.authenticationFailed.rawValue, .authenticationFailed, false), + ]) + func failedAuthWithEvaluateError( + errorCode: Int, + expectedResult: AuthResult, + expectBiometrics: Bool + ) async { let stubAuthContext = StubAuthContext() let plugin = LocalAuthPlugin( contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) let strings = createAuthStrings() + stubAuthContext.expectBiometrics = expectBiometrics stubAuthContext.evaluateError = NSError( - domain: "LocalAuthentication", code: LAError.userCancel.rawValue) - - let expectation = expectation(description: "Result is called") - plugin.authenticate( - options: AuthOptions(biometricOnly: false, sticky: false), - strings: strings - ) { resultDetails in - switch resultDetails { - case .success(let successDetails): - XCTAssertEqual(successDetails.result, .userCancel) - case .failure(let error): - XCTFail("Unexpected error: \(error)") - } - expectation.fulfill() - } - self.waitForExpectations(timeout: timeout) - } - - @MainActor - func testFailedAuthWithErrorUserFallback() { - let stubAuthContext = StubAuthContext() - let plugin = LocalAuthPlugin( - contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) + domain: (errorCode == 99) ? "error" : "LocalAuthentication", + code: errorCode + ) - let strings = createAuthStrings() - stubAuthContext.evaluateError = NSError( - domain: "LocalAuthentication", code: LAError.userFallback.rawValue) - - let expectation = expectation(description: "Result is called") - plugin.authenticate( - options: AuthOptions(biometricOnly: false, sticky: false), - strings: strings - ) { resultDetails in - switch resultDetails { - case .success(let successDetails): - XCTAssertEqual(successDetails.result, .userFallback) - case .failure(let error): - XCTFail("Unexpected error: \(error)") + await withCheckedContinuation { continuation in + plugin.authenticate( + options: AuthOptions(biometricOnly: expectBiometrics, sticky: false), + strings: strings + ) { resultDetails in + switch resultDetails { + case .success(let successDetails): + #expect(successDetails.result == expectedResult) + case .failure(let error): + Issue.record("Unexpected error: \(error)") + } + continuation.resume() } - expectation.fulfill() } - self.waitForExpectations(timeout: timeout) } #if os(macOS) @available(macOS 11.2, *) - @MainActor - func testFailedAuthWithErrorBiometricDisconnected() { + @Test + func failedAuthWithErrorBiometricDisconnected() async { let stubAuthContext = StubAuthContext() let plugin = LocalAuthPlugin( contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) @@ -270,25 +186,25 @@ class LocalAuthPluginTests: XCTestCase { stubAuthContext.canEvaluateError = NSError( domain: "LocalAuthentication", code: LAError.biometryDisconnected.rawValue) - let expectation = expectation(description: "Result is called") - plugin.authenticate( - options: AuthOptions(biometricOnly: false, sticky: false), - strings: strings - ) { resultDetails in - switch resultDetails { - case .success(let successDetails): - XCTAssertEqual(successDetails.result, .biometryDisconnected) - case .failure(let error): - XCTFail("Unexpected error: \(error)") + await withCheckedContinuation { continuation in + plugin.authenticate( + options: AuthOptions(biometricOnly: false, sticky: false), + strings: strings + ) { resultDetails in + switch resultDetails { + case .success(let successDetails): + #expect(successDetails.result == .biometryDisconnected) + case .failure(let error): + Issue.record("Unexpected error: \(error)") + } + continuation.resume() } - expectation.fulfill() } - self.waitForExpectations(timeout: timeout) } @available(macOS 11.2, *) - @MainActor - func testFailedAuthWithErrorBiometricNotPaired() { + @Test + func failedAuthWithErrorBiometricNotPaired() async { let stubAuthContext = StubAuthContext() let plugin = LocalAuthPlugin( contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) @@ -297,25 +213,25 @@ class LocalAuthPluginTests: XCTestCase { stubAuthContext.canEvaluateError = NSError( domain: "LocalAuthentication", code: LAError.biometryNotPaired.rawValue) - let expectation = expectation(description: "Result is called") - plugin.authenticate( - options: AuthOptions(biometricOnly: false, sticky: false), - strings: strings - ) { resultDetails in - switch resultDetails { - case .success(let successDetails): - XCTAssertEqual(successDetails.result, .biometryNotPaired) - case .failure(let error): - XCTFail("Unexpected error: \(error)") + await withCheckedContinuation { continuation in + plugin.authenticate( + options: AuthOptions(biometricOnly: false, sticky: false), + strings: strings + ) { resultDetails in + switch resultDetails { + case .success(let successDetails): + #expect(successDetails.result == .biometryNotPaired) + case .failure(let error): + Issue.record("Unexpected error: \(error)") + } + continuation.resume() } - expectation.fulfill() } - self.waitForExpectations(timeout: timeout) } @available(macOS 12.0, *) - @MainActor - func testFailedAuthWithErrorBiometricInvalidDimensions() { + @Test + func failedAuthWithErrorBiometricInvalidDimensions() async { let stubAuthContext = StubAuthContext() let plugin = LocalAuthPlugin( contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) @@ -324,257 +240,61 @@ class LocalAuthPluginTests: XCTestCase { stubAuthContext.canEvaluateError = NSError( domain: "LocalAuthentication", code: LAError.invalidDimensions.rawValue) - let expectation = expectation(description: "Result is called") - plugin.authenticate( - options: AuthOptions(biometricOnly: false, sticky: false), - strings: strings - ) { resultDetails in - switch resultDetails { - case .success(let successDetails): - XCTAssertEqual(successDetails.result, .invalidDimensions) - case .failure(let error): - XCTFail("Unexpected error: \(error)") + await withCheckedContinuation { continuation in + plugin.authenticate( + options: AuthOptions(biometricOnly: false, sticky: false), + strings: strings + ) { resultDetails in + switch resultDetails { + case .success(let successDetails): + #expect(successDetails.result == .invalidDimensions) + case .failure(let error): + Issue.record("Unexpected error: \(error)") + } + continuation.resume() } - expectation.fulfill() } - self.waitForExpectations(timeout: timeout) } #endif - @MainActor - func testFailedAuthWithErrorBiometricLockout() { + @Test(arguments: [ + (LAError.biometryLockout, AuthResult.biometryLockout), + (.biometryNotAvailable, .biometryNotAvailable), + (.biometryNotEnrolled, .biometryNotEnrolled), + (.invalidContext, .invalidContext), + (.notInteractive, .notInteractive), + (.passcodeNotSet, .passcodeNotSet), + ]) + func failedAuthWithCanEvaluateError( + error: LAError.Code, + expectedResult: AuthResult + ) async { let stubAuthContext = StubAuthContext() let plugin = LocalAuthPlugin( contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) let strings = createAuthStrings() stubAuthContext.canEvaluateError = NSError( - domain: "LocalAuthentication", code: LAError.biometryLockout.rawValue) - - let expectation = expectation(description: "Result is called") - plugin.authenticate( - options: AuthOptions(biometricOnly: false, sticky: false), - strings: strings - ) { resultDetails in - switch resultDetails { - case .success(let successDetails): - XCTAssertEqual(successDetails.result, .biometryLockout) - case .failure(let error): - XCTFail("Unexpected error: \(error)") - } - expectation.fulfill() - } - self.waitForExpectations(timeout: timeout) - } + domain: "LocalAuthentication", code: error.rawValue) - @MainActor - func testFailedAuthWithErrorBiometricNotAvailable() { - let stubAuthContext = StubAuthContext() - let plugin = LocalAuthPlugin( - contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) - - let strings = createAuthStrings() - stubAuthContext.canEvaluateError = NSError( - domain: "LocalAuthentication", code: LAError.biometryNotAvailable.rawValue) - - let expectation = expectation(description: "Result is called") - plugin.authenticate( - options: AuthOptions(biometricOnly: false, sticky: false), - strings: strings - ) { resultDetails in - switch resultDetails { - case .success(let successDetails): - XCTAssertEqual(successDetails.result, .biometryNotAvailable) - case .failure(let error): - XCTFail("Unexpected error: \(error)") - } - expectation.fulfill() - } - self.waitForExpectations(timeout: timeout) - } - - @MainActor - func testFailedAuthWithErrorBiometricNotEnrolled() { - let stubAuthContext = StubAuthContext() - let plugin = LocalAuthPlugin( - contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) - - let strings = createAuthStrings() - stubAuthContext.canEvaluateError = NSError( - domain: "LocalAuthentication", code: LAError.biometryNotEnrolled.rawValue) - - let expectation = expectation(description: "Result is called") - plugin.authenticate( - options: AuthOptions(biometricOnly: false, sticky: false), - strings: strings - ) { resultDetails in - switch resultDetails { - case .success(let successDetails): - XCTAssertEqual(successDetails.result, .biometryNotEnrolled) - case .failure(let error): - XCTFail("Unexpected error: \(error)") - } - expectation.fulfill() - } - self.waitForExpectations(timeout: timeout) - } - - @MainActor - func testFailedAuthWithErrorBiometricInvalidContext() { - let stubAuthContext = StubAuthContext() - let plugin = LocalAuthPlugin( - contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) - - let strings = createAuthStrings() - stubAuthContext.canEvaluateError = NSError( - domain: "LocalAuthentication", code: LAError.invalidContext.rawValue) - - let expectation = expectation(description: "Result is called") - plugin.authenticate( - options: AuthOptions(biometricOnly: false, sticky: false), - strings: strings - ) { resultDetails in - switch resultDetails { - case .success(let successDetails): - XCTAssertEqual(successDetails.result, .invalidContext) - case .failure(let error): - XCTFail("Unexpected error: \(error)") - } - expectation.fulfill() - } - self.waitForExpectations(timeout: timeout) - } - - @MainActor - func testFailedAuthWithErrorBiometricNotInteractive() { - let stubAuthContext = StubAuthContext() - let plugin = LocalAuthPlugin( - contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) - - let strings = createAuthStrings() - stubAuthContext.canEvaluateError = NSError( - domain: "LocalAuthentication", code: LAError.notInteractive.rawValue) - - let expectation = expectation(description: "Result is called") - plugin.authenticate( - options: AuthOptions(biometricOnly: false, sticky: false), - strings: strings - ) { resultDetails in - switch resultDetails { - case .success(let successDetails): - XCTAssertEqual(successDetails.result, .notInteractive) - case .failure(let error): - XCTFail("Unexpected error: \(error)") - } - expectation.fulfill() - } - self.waitForExpectations(timeout: timeout) - } - - @MainActor - func testFailedAuthWithErrorBiometricPasscodeNotSet() { - let stubAuthContext = StubAuthContext() - let plugin = LocalAuthPlugin( - contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) - - let strings = createAuthStrings() - stubAuthContext.canEvaluateError = NSError( - domain: "LocalAuthentication", code: LAError.passcodeNotSet.rawValue) - - let expectation = expectation(description: "Result is called") - plugin.authenticate( - options: AuthOptions(biometricOnly: false, sticky: false), - strings: strings - ) { resultDetails in - switch resultDetails { - case .success(let successDetails): - XCTAssertEqual(successDetails.result, .passcodeNotSet) - case .failure(let error): - XCTFail("Unexpected error: \(error)") - } - expectation.fulfill() - } - self.waitForExpectations(timeout: timeout) - } - - @MainActor - func testFailedWithUnknownErrorCode() { - let stubAuthContext = StubAuthContext() - let plugin = LocalAuthPlugin( - contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) - - let strings = createAuthStrings() - stubAuthContext.evaluateError = NSError(domain: "error", code: 99) - - let expectation = expectation(description: "Result is called") - plugin.authenticate( - options: AuthOptions(biometricOnly: false, sticky: false), - strings: strings - ) { resultDetails in - switch resultDetails { - case .success(let successDetails): - XCTAssertEqual(successDetails.result, .unknownError) - case .failure(let error): - XCTFail("Unexpected error: \(error)") - } - expectation.fulfill() - } - self.waitForExpectations(timeout: timeout) - } - - @MainActor - func testSystemCancelledWithoutStickyAuth() { - let stubAuthContext = StubAuthContext() - let plugin = LocalAuthPlugin( - contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) - - let strings = createAuthStrings() - stubAuthContext.evaluateError = NSError(domain: "error", code: LAError.systemCancel.rawValue) - - let expectation = expectation(description: "Result is called") - plugin.authenticate( - options: AuthOptions(biometricOnly: false, sticky: false), - strings: strings - ) { resultDetails in - switch resultDetails { - case .success(let successDetails): - XCTAssertEqual(successDetails.result, .systemCancel) - case .failure(let error): - XCTFail("Unexpected error: \(error)") - } - expectation.fulfill() - } - self.waitForExpectations(timeout: timeout) - } - - @MainActor - func testFailedAuthWithoutBiometrics() { - let stubAuthContext = StubAuthContext() - let plugin = LocalAuthPlugin( - contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) - - let strings = createAuthStrings() - stubAuthContext.evaluateError = NSError( - domain: "error", code: LAError.authenticationFailed.rawValue) - - let expectation = expectation(description: "Result is called") - plugin.authenticate( - options: AuthOptions(biometricOnly: false, sticky: false), - strings: strings - ) { resultDetails in - switch resultDetails { - case .success(let successDetails): - XCTAssertEqual(successDetails.result, .authenticationFailed) - case .failure(let error): - XCTFail("Unexpected error: \(error)") + await withCheckedContinuation { continuation in + plugin.authenticate( + options: AuthOptions(biometricOnly: false, sticky: false), + strings: strings + ) { resultDetails in + switch resultDetails { + case .success(let successDetails): + #expect(successDetails.result == expectedResult) + case .failure(let error): + Issue.record("Unexpected error: \(error)") + } + continuation.resume() } - expectation.fulfill() } - self.waitForExpectations(timeout: timeout) } - @MainActor - func testLocalizedFallbackTitle() { + @Test + func localizedFallbackTitle() async { let stubAuthContext = StubAuthContext() let plugin = LocalAuthPlugin( contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) @@ -582,19 +302,19 @@ class LocalAuthPluginTests: XCTestCase { let strings = createAuthStrings(localizedFallbackTitle: "a title") stubAuthContext.evaluateResponse = true - let expectation = expectation(description: "Result is called") - plugin.authenticate( - options: AuthOptions(biometricOnly: false, sticky: false), - strings: strings - ) { resultDetails in - XCTAssertEqual(stubAuthContext.localizedFallbackTitle, strings.localizedFallbackTitle) - expectation.fulfill() + await withCheckedContinuation { continuation in + plugin.authenticate( + options: AuthOptions(biometricOnly: false, sticky: false), + strings: strings + ) { resultDetails in + #expect(stubAuthContext.localizedFallbackTitle == strings.localizedFallbackTitle) + continuation.resume() + } } - self.waitForExpectations(timeout: timeout) } - @MainActor - func testSkippedLocalizedFallbackTitle() { + @Test + func skippedLocalizedFallbackTitle() async { let stubAuthContext = StubAuthContext() let plugin = LocalAuthPlugin( contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) @@ -602,18 +322,19 @@ class LocalAuthPluginTests: XCTestCase { let strings = createAuthStrings(localizedFallbackTitle: nil) stubAuthContext.evaluateResponse = true - let expectation = expectation(description: "Result is called") - plugin.authenticate( - options: AuthOptions(biometricOnly: false, sticky: false), - strings: strings - ) { resultDetails in - XCTAssertNil(stubAuthContext.localizedFallbackTitle) - expectation.fulfill() + await withCheckedContinuation { continuation in + plugin.authenticate( + options: AuthOptions(biometricOnly: false, sticky: false), + strings: strings + ) { resultDetails in + #expect(stubAuthContext.localizedFallbackTitle == nil) + continuation.resume() + } } - self.waitForExpectations(timeout: timeout) } - func testDeviceSupportsBiometrics_withEnrolledHardware() throws { + @Test + func deviceSupportsBiometricsWithEnrolledHardware() throws { let stubAuthContext = StubAuthContext() let plugin = LocalAuthPlugin( contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) @@ -621,10 +342,11 @@ class LocalAuthPluginTests: XCTestCase { stubAuthContext.expectBiometrics = true let result = try plugin.deviceCanSupportBiometrics() - XCTAssertTrue(result) + #expect(result) } - func testDeviceSupportsBiometrics_withNonEnrolledHardware() throws { + @Test + func deviceSupportsBiometricsWithNonEnrolledHardware() throws { let stubAuthContext = StubAuthContext() let plugin = LocalAuthPlugin( contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) @@ -634,10 +356,11 @@ class LocalAuthPluginTests: XCTestCase { domain: "error", code: LAError.biometryNotEnrolled.rawValue) let result = try plugin.deviceCanSupportBiometrics() - XCTAssertTrue(result) + #expect(result) } - func testDeviceSupportsBiometrics_withBiometryNotAvailable() throws { + @Test + func deviceSupportsBiometricsWithBiometryNotAvailable() throws { let stubAuthContext = StubAuthContext() let plugin = LocalAuthPlugin( contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) @@ -647,10 +370,11 @@ class LocalAuthPluginTests: XCTestCase { domain: "error", code: LAError.biometryNotAvailable.rawValue) let result = try plugin.deviceCanSupportBiometrics() - XCTAssertFalse(result) + #expect(!result) } - func testDeviceSupportsBiometrics_withBiometryNotAvailableWhenPermissionsDenied() throws { + @Test + func deviceSupportsBiometricsWithBiometryNotAvailableWhenPermissionsDenied() throws { let stubAuthContext = StubAuthContext() let plugin = LocalAuthPlugin( contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) @@ -661,10 +385,11 @@ class LocalAuthPluginTests: XCTestCase { domain: "error", code: LAError.biometryNotAvailable.rawValue) let result = try plugin.deviceCanSupportBiometrics() - XCTAssertTrue(result) + #expect(result) } - func testGetEnrolledBiometricsWithFaceID() throws { + @Test + func getEnrolledBiometricsWithFaceID() throws { let stubAuthContext = StubAuthContext() let plugin = LocalAuthPlugin( contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) @@ -673,11 +398,13 @@ class LocalAuthPluginTests: XCTestCase { stubAuthContext.biometryType = .faceID let result = try plugin.getEnrolledBiometrics() - XCTAssertEqual(result.count, 1) - XCTAssertEqual(result[0], .face) + #expect(result.count == 1) + let first = try #require(result.first) + #expect(first == .face) } - func testGetEnrolledBiometricsWithTouchID() throws { + @Test + func getEnrolledBiometricsWithTouchID() throws { let stubAuthContext = StubAuthContext() let plugin = LocalAuthPlugin( contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) @@ -686,11 +413,13 @@ class LocalAuthPluginTests: XCTestCase { stubAuthContext.biometryType = .touchID let result = try plugin.getEnrolledBiometrics() - XCTAssertEqual(result.count, 1) - XCTAssertEqual(result[0], .fingerprint) + #expect(result.count == 1) + let first = try #require(result.first) + #expect(first == .fingerprint) } - func testGetEnrolledBiometricsWithoutEnrolledHardware() throws { + @Test + func getEnrolledBiometricsWithoutEnrolledHardware() throws { let stubAuthContext = StubAuthContext() let plugin = LocalAuthPlugin( contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) @@ -700,19 +429,21 @@ class LocalAuthPluginTests: XCTestCase { domain: "error", code: LAError.biometryNotEnrolled.rawValue) let result = try plugin.getEnrolledBiometrics() - XCTAssertTrue(result.isEmpty) + #expect(result.isEmpty) } - func testIsDeviceSupportedHandlesSupported() throws { + @Test + func isDeviceSupportedHandlesSupported() throws { let stubAuthContext = StubAuthContext() let plugin = LocalAuthPlugin( contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) let result = try plugin.isDeviceSupported() - XCTAssertTrue(result) + #expect(result) } - func testIsDeviceSupportedHandlesUnsupported() throws { + @Test + func isDeviceSupportedHandlesUnsupported() throws { let stubAuthContext = StubAuthContext() // An arbitrary error to cause canEvaluatePolicy to return false. stubAuthContext.canEvaluateError = NSError(domain: "error", code: 1) @@ -720,7 +451,7 @@ class LocalAuthPluginTests: XCTestCase { contextFactory: StubAuthContextFactory(contexts: [stubAuthContext])) let result = try plugin.isDeviceSupported() - XCTAssertFalse(result) + #expect(!result) } // Creates an AuthStrings with placeholder values. diff --git a/packages/local_auth/local_auth_darwin/darwin/local_auth_darwin/Sources/local_auth_darwin/LocalAuthPlugin.swift b/packages/local_auth/local_auth_darwin/darwin/local_auth_darwin/Sources/local_auth_darwin/LocalAuthPlugin.swift index 3222b795eb5d..e93b1977f3c5 100644 --- a/packages/local_auth/local_auth_darwin/darwin/local_auth_darwin/Sources/local_auth_darwin/LocalAuthPlugin.swift +++ b/packages/local_auth/local_auth_darwin/darwin/local_auth_darwin/Sources/local_auth_darwin/LocalAuthPlugin.swift @@ -43,7 +43,13 @@ public final class LocalAuthPlugin: NSObject, FlutterPlugin, LocalAuthApi, @unch public static func register(with registrar: FlutterPluginRegistrar) { let instance = LocalAuthPlugin( contextFactory: DefaultAuthContextFactory()) + // Register for both application and scene delegates for backward compatibility. + // Apps using UIScene lifecycle will receive sceneDidBecomeActive, + // while apps not yet migrated will receive applicationDidBecomeActive. registrar.addApplicationDelegate(instance) + #if os(iOS) + registrar.addSceneDelegate(instance) + #endif // Workaround for https://github.com/flutter/flutter/issues/118103. #if os(iOS) let messenger = registrar.messenger() @@ -249,18 +255,36 @@ public final class LocalAuthPlugin: NSObject, FlutterPlugin, LocalAuthApi, @unch )) } + private func retryStickyAuth() { + if let lastCallState = self.lastCallState { + authenticate( + options: lastCallState.options, + strings: lastCallState.strings, + completion: lastCallState.resultHandler) + } + } + // MARK: App delegate - // This method is called when the app is resumed from the background only on iOS + // These methods are called when the app is resumed from the background only on iOS. + // Both are kept for backward compatibility: sceneDidBecomeActive for apps using UIScene lifecycle, + // and applicationDidBecomeActive for apps that haven't migrated yet. #if os(iOS) + @MainActor + public func sceneDidBecomeActive(_ scene: UIScene) { + retryStickyAuth() + } + + @MainActor public func applicationDidBecomeActive(_ application: UIApplication) { - if let lastCallState = self.lastCallState { - authenticate( - options: lastCallState.options, - strings: lastCallState.strings, - completion: lastCallState.resultHandler) - } + retryStickyAuth() } #endif // os(iOS) } + +// MARK: - FlutterSceneLifeCycleDelegate + +#if os(iOS) + extension LocalAuthPlugin: FlutterSceneLifeCycleDelegate {} +#endif diff --git a/packages/local_auth/local_auth_darwin/example/ios/.gitignore b/packages/local_auth/local_auth_darwin/example/ios/.gitignore new file mode 100644 index 000000000000..7a7f9873ad7d --- /dev/null +++ b/packages/local_auth/local_auth_darwin/example/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/packages/local_auth/local_auth_darwin/example/ios/Flutter/AppFrameworkInfo.plist b/packages/local_auth/local_auth_darwin/example/ios/Flutter/AppFrameworkInfo.plist index 1f6b98f117b2..391a902b2beb 100644 --- a/packages/local_auth/local_auth_darwin/example/ios/Flutter/AppFrameworkInfo.plist +++ b/packages/local_auth/local_auth_darwin/example/ios/Flutter/AppFrameworkInfo.plist @@ -20,11 +20,5 @@ ???? CFBundleVersion 1.0 - UIRequiredDeviceCapabilities - - arm64 - - MinimumOSVersion - 13.0 diff --git a/packages/local_auth/local_auth_darwin/example/ios/Flutter/Debug.xcconfig b/packages/local_auth/local_auth_darwin/example/ios/Flutter/Debug.xcconfig index e8efba114687..592ceee85b89 100644 --- a/packages/local_auth/local_auth_darwin/example/ios/Flutter/Debug.xcconfig +++ b/packages/local_auth/local_auth_darwin/example/ios/Flutter/Debug.xcconfig @@ -1,2 +1 @@ -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" diff --git a/packages/local_auth/local_auth_darwin/example/ios/Flutter/Release.xcconfig b/packages/local_auth/local_auth_darwin/example/ios/Flutter/Release.xcconfig index 399e9340e6f6..592ceee85b89 100644 --- a/packages/local_auth/local_auth_darwin/example/ios/Flutter/Release.xcconfig +++ b/packages/local_auth/local_auth_darwin/example/ios/Flutter/Release.xcconfig @@ -1,2 +1 @@ -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" diff --git a/packages/local_auth/local_auth_darwin/example/ios/Podfile b/packages/local_auth/local_auth_darwin/example/ios/Podfile deleted file mode 100644 index fcbeb907d4f6..000000000000 --- a/packages/local_auth/local_auth_darwin/example/ios/Podfile +++ /dev/null @@ -1,41 +0,0 @@ -# Uncomment this line to define a global platform for your project -# platform :ios, '13.0' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_ios_podfile_setup - -target 'Runner' do - flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) - target 'RunnerTests' do - inherit! :search_paths - end -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_ios_build_settings(target) - end -end diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner.xcodeproj/project.pbxproj b/packages/local_auth/local_auth_darwin/example/ios/Runner.xcodeproj/project.pbxproj index 57c9b555d49b..938fff8a4e42 100644 --- a/packages/local_auth/local_auth_darwin/example/ios/Runner.xcodeproj/project.pbxproj +++ b/packages/local_auth/local_auth_darwin/example/ios/Runner.xcodeproj/project.pbxproj @@ -7,21 +7,19 @@ objects = { /* Begin PBXBuildFile section */ - 0CCCD07A2CE24E13C9C1EEA4 /* libPods-Runner.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 9D274A3F79473B1549B2BBD5 /* libPods-Runner.a */; }; 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; - 338A5F9D2BFBA45B00DF0C4E /* FLALocalAuthPluginTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 338A5F9C2BFBA45B00DF0C4E /* FLALocalAuthPluginTests.swift */; }; + 330AD6522F3D2D32005FB0FC /* FLALocalAuthPluginTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 330AD6512F3D2D32005FB0FC /* FLALocalAuthPluginTests.swift */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; - 691CB38B382734AF80FBCA4C /* libPods-RunnerTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = ADBFA21B380E07A3A585383D /* libPods-RunnerTests.a */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; }; 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; - 978B8F6F1D3862AE00F588F7 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */; }; - 97C146F31CF9000F007C117D /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 97C146F21CF9000F007C117D /* main.m */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ - 3398D2D226163948005A052F /* PBXContainerItemProxy */ = { + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 97C146E61CF9000F007C117D /* Project object */; proxyType = 1; @@ -46,37 +44,30 @@ /* Begin PBXFileReference section */ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; - 338A5F9C2BFBA45B00DF0C4E /* FLALocalAuthPluginTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = FLALocalAuthPluginTests.swift; path = ../../../darwin/Tests/FLALocalAuthPluginTests.swift; sourceTree = ""; }; - 3398D2CD26163948005A052F /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 3398D2D126163948005A052F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 3398D2DC261649CD005A052F /* liblocal_auth.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; path = liblocal_auth.a; sourceTree = BUILT_PRODUCTS_DIR; }; - 3398D2DF26164A03005A052F /* liblocal_auth.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; path = liblocal_auth.a; sourceTree = BUILT_PRODUCTS_DIR; }; + 330AD6512F3D2D32005FB0FC /* FLALocalAuthPluginTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FLALocalAuthPluginTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; - 658CDD04B21E4EA92F8EF229 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 784666492D4C4C64000A1A5F /* FlutterFramework */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterFramework; path = Flutter/ephemeral/Packages/.packages/FlutterFramework; sourceTree = ""; }; + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 78DABEA22ED26510000E7860 /* local_auth_darwin */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = local_auth_darwin; path = ../../darwin/local_auth_darwin; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; - 7AFFD8ED1D35381100E5BB4D /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; - 7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; - 8D6545CD14E27D6F8299FFD5 /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 97C146F21CF9000F007C117D /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 9D274A3F79473B1549B2BBD5 /* libPods-Runner.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-Runner.a"; sourceTree = BUILT_PRODUCTS_DIR; }; - ADBFA21B380E07A3A585383D /* libPods-RunnerTests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-RunnerTests.a"; sourceTree = BUILT_PRODUCTS_DIR; }; - D9B3BCBC68F8928E2907FB87 /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; - EB36DF6C3F25E00DF4175422 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ - 3398D2CA26163948005A052F /* Frameworks */ = { + 5918301AD6FB1B5EA756AC61 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 691CB38B382734AF80FBCA4C /* libPods-RunnerTests.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -85,25 +76,34 @@ buildActionMask = 2147483647; files = ( 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, - 0CCCD07A2CE24E13C9C1EEA4 /* libPods-Runner.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 33BF11D226680B2E002967F3 /* RunnerTests */ = { + 330AD6502F3D2D0E005FB0FC /* RunnerTests */ = { isa = PBXGroup; children = ( - 338A5F9C2BFBA45B00DF0C4E /* FLALocalAuthPluginTests.swift */, - 3398D2D126163948005A052F /* Info.plist */, + 330AD6512F3D2D32005FB0FC /* FLALocalAuthPluginTests.swift */, ); - path = RunnerTests; + name = RunnerTests; + path = ../../darwin/Tests; + sourceTree = ""; + }; + 7E280321D48EB544D54BA36C /* Pods */ = { + isa = PBXGroup; + children = ( + ); + path = Pods; sourceTree = ""; }; 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( + 78DABEA22ED26510000E7860 /* local_auth_darwin */, + 784666492D4C4C64000A1A5F /* FlutterFramework */, + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, 9740EEB21CF90195004384FC /* Debug.xcconfig */, 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, @@ -115,12 +115,11 @@ 97C146E51CF9000F007C117D = { isa = PBXGroup; children = ( - 33BF11D226680B2E002967F3 /* RunnerTests */, 9740EEB11CF90186004384FC /* Flutter */, 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, - F8CC53B854B121315C7319D2 /* Pods */, - E2D5FA899A019BD3E0DB0917 /* Frameworks */, + 330AD6502F3D2D0E005FB0FC /* RunnerTests */, + 7E280321D48EB544D54BA36C /* Pods */, ); sourceTree = ""; }; @@ -128,7 +127,7 @@ isa = PBXGroup; children = ( 97C146EE1CF9000F007C117D /* Runner.app */, - 3398D2CD26163948005A052F /* RunnerTests.xctest */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, ); name = Products; sourceTree = ""; @@ -136,76 +135,44 @@ 97C146F01CF9000F007C117D /* Runner */ = { isa = PBXGroup; children = ( - 7AFFD8ED1D35381100E5BB4D /* AppDelegate.h */, - 7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */, 97C146FA1CF9000F007C117D /* Main.storyboard */, 97C146FD1CF9000F007C117D /* Assets.xcassets */, 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, 97C147021CF9000F007C117D /* Info.plist */, - 97C146F11CF9000F007C117D /* Supporting Files */, 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, ); path = Runner; sourceTree = ""; }; - 97C146F11CF9000F007C117D /* Supporting Files */ = { - isa = PBXGroup; - children = ( - 97C146F21CF9000F007C117D /* main.m */, - ); - name = "Supporting Files"; - sourceTree = ""; - }; - E2D5FA899A019BD3E0DB0917 /* Frameworks */ = { - isa = PBXGroup; - children = ( - 3398D2DF26164A03005A052F /* liblocal_auth.a */, - 3398D2DC261649CD005A052F /* liblocal_auth.a */, - 9D274A3F79473B1549B2BBD5 /* libPods-Runner.a */, - ADBFA21B380E07A3A585383D /* libPods-RunnerTests.a */, - ); - name = Frameworks; - sourceTree = ""; - }; - F8CC53B854B121315C7319D2 /* Pods */ = { - isa = PBXGroup; - children = ( - EB36DF6C3F25E00DF4175422 /* Pods-Runner.debug.xcconfig */, - 658CDD04B21E4EA92F8EF229 /* Pods-Runner.release.xcconfig */, - 8D6545CD14E27D6F8299FFD5 /* Pods-RunnerTests.debug.xcconfig */, - D9B3BCBC68F8928E2907FB87 /* Pods-RunnerTests.release.xcconfig */, - ); - name = Pods; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ - 3398D2CC26163948005A052F /* RunnerTests */ = { + 331C8080294A63A400263BE5 /* RunnerTests */ = { isa = PBXNativeTarget; - buildConfigurationList = 3398D2D426163948005A052F /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; buildPhases = ( - 9C21D3AD392EA849AEB09231 /* [CP] Check Pods Manifest.lock */, - 3398D2C926163948005A052F /* Sources */, - 3398D2CA26163948005A052F /* Frameworks */, - 3398D2CB26163948005A052F /* Resources */, + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + 5918301AD6FB1B5EA756AC61 /* Frameworks */, ); buildRules = ( ); dependencies = ( - 3398D2D326163948005A052F /* PBXTargetDependency */, + 331C8086294A63A400263BE5 /* PBXTargetDependency */, ); name = RunnerTests; productName = RunnerTests; - productReference = 3398D2CD26163948005A052F /* RunnerTests.xctest */; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; productType = "com.apple.product-type.bundle.unit-test"; }; 97C146ED1CF9000F007C117D /* Runner */ = { isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - 98D96A2D1A74AF66E3DD2DBC /* [CP] Check Pods Manifest.lock */, 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, @@ -231,22 +198,23 @@ 97C146E61CF9000F007C117D /* Project object */ = { isa = PBXProject; attributes = { + BuildIndependentTargetsInParallel = YES; LastUpgradeCheck = 1510; - ORGANIZATIONNAME = "The Flutter Authors"; + ORGANIZATIONNAME = ""; TargetAttributes = { - 3398D2CC26163948005A052F = { - CreatedOnToolsVersion = 12.4; - LastSwiftMigration = 1510; - ProvisioningStyle = Automatic; + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + LastSwiftMigration = 2620; TestTargetID = 97C146ED1CF9000F007C117D; }; 97C146ED1CF9000F007C117D = { CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; }; }; }; buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; - compatibilityVersion = "Xcode 3.2"; + compatibilityVersion = "Xcode 9.3"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( @@ -262,13 +230,13 @@ projectRoot = ""; targets = ( 97C146ED1CF9000F007C117D /* Runner */, - 3398D2CC26163948005A052F /* RunnerTests */, + 331C8080294A63A400263BE5 /* RunnerTests */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ - 3398D2CB26163948005A052F /* Resources */ = { + 331C807F294A63A400263BE5 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( @@ -320,54 +288,14 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; }; - 98D96A2D1A74AF66E3DD2DBC /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 9C21D3AD392EA849AEB09231 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ - 3398D2C926163948005A052F /* Sources */ = { + 331C807D294A63A400263BE5 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 338A5F9D2BFBA45B00DF0C4E /* FLALocalAuthPluginTests.swift in Sources */, + 330AD6522F3D2D32005FB0FC /* FLALocalAuthPluginTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -375,19 +303,19 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 978B8F6F1D3862AE00F588F7 /* AppDelegate.m in Sources */, - 97C146F31CF9000F007C117D /* main.m in Sources */, + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ - 3398D2D326163948005A052F /* PBXTargetDependency */ = { + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 97C146ED1CF9000F007C117D /* Runner */; - targetProxy = 3398D2D226163948005A052F /* PBXContainerItemProxy */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ @@ -411,71 +339,134 @@ /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ - 3398D2D526163948005A052F /* Debug */ = { + 249021D3217E4FDB00AE95B9 /* Profile */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 8D6545CD14E27D6F8299FFD5 /* Pods-RunnerTests.debug.xcconfig */; buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CODE_SIGN_STYLE = Automatic; - GCC_C_LANGUAGE_STANDARD = gnu11; - INFOPLIST_FILE = RunnerTests/Info.plist; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", - "@loader_path/Frameworks", ); - MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; - MTL_FAST_MATH = YES; - PRODUCT_BUNDLE_IDENTIFIER = com.google.RunnerTests; + PRODUCT_BUNDLE_IDENTIFIER = com.example.localAuthDarwinExample; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.localAuthDarwinExample.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/Runner"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; }; name = Debug; }; - 3398D2D626163948005A052F /* Release */ = { + 331C8089294A63A400263BE5 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = D9B3BCBC68F8928E2907FB87 /* Pods-RunnerTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; CODE_SIGN_STYLE = Automatic; - GCC_C_LANGUAGE_STANDARD = gnu11; - INFOPLIST_FILE = RunnerTests/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MTL_FAST_MATH = YES; - PRODUCT_BUNDLE_IDENTIFIER = com.google.RunnerTests; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.localAuthDarwinExample.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/Runner"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; }; name = Release; }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.localAuthDarwinExample.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; 97C147031CF9000F007C117D /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; @@ -505,6 +496,7 @@ DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; @@ -531,7 +523,7 @@ isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; @@ -561,6 +553,7 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; @@ -572,6 +565,9 @@ IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; @@ -582,22 +578,20 @@ baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.localAuthExample; + PRODUCT_BUNDLE_IDENTIFIER = com.example.localAuthDarwinExample; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; }; name = Debug; }; @@ -606,33 +600,31 @@ baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.localAuthExample; + PRODUCT_BUNDLE_IDENTIFIER = com.example.localAuthDarwinExample; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ - 3398D2D426163948005A052F /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { isa = XCConfigurationList; buildConfigurations = ( - 3398D2D526163948005A052F /* Debug */, - 3398D2D626163948005A052F /* Release */, + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; @@ -642,6 +634,7 @@ buildConfigurations = ( 97C147031CF9000F007C117D /* Debug */, 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; @@ -651,6 +644,7 @@ buildConfigurations = ( 97C147061CF9000F007C117D /* Debug */, 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/packages/local_auth/local_auth_darwin/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000000..18d981003d68 --- /dev/null +++ b/packages/local_auth/local_auth_darwin/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/packages/local_auth/local_auth_darwin/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 000000000000..f9b0d7c5ea15 --- /dev/null +++ b/packages/local_auth/local_auth_darwin/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/packages/local_auth/local_auth_darwin/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index 52fbc6fd946b..c3fedb29c990 100644 --- a/packages/local_auth/local_auth_darwin/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/packages/local_auth/local_auth_darwin/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -44,6 +44,7 @@ buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + customLLDBInitFile = "$(SRCROOT)/Flutter/ephemeral/flutter_lldbinit" shouldUseLaunchSchemeArgsEnv = "YES"> + skipped = "NO" + parallelizable = "YES"> @@ -71,6 +73,7 @@ buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + customLLDBInitFile = "$(SRCROOT)/Flutter/ephemeral/flutter_lldbinit" launchStyle = "0" useCustomWorkingDirectory = "NO" ignoresPersistentStateOnLaunch = "NO" @@ -90,7 +93,7 @@ + + + + PreviewsEnabled + + + diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/AppDelegate.h b/packages/local_auth/local_auth_darwin/example/ios/Runner/AppDelegate.h deleted file mode 100644 index 721cca1e11bb..000000000000 --- a/packages/local_auth/local_auth_darwin/example/ios/Runner/AppDelegate.h +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import -#import - -@interface AppDelegate : FlutterAppDelegate - -@end diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/AppDelegate.m b/packages/local_auth/local_auth_darwin/example/ios/Runner/AppDelegate.m deleted file mode 100644 index fff9545d5055..000000000000 --- a/packages/local_auth/local_auth_darwin/example/ios/Runner/AppDelegate.m +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "AppDelegate.h" -#include "GeneratedPluginRegistrant.h" - -@implementation AppDelegate - -- (BOOL)application:(UIApplication *)application - didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - [GeneratedPluginRegistrant registerWithRegistry:self]; - // Override point for customization after application launch. - return [super application:application didFinishLaunchingWithOptions:launchOptions]; -} - -@end diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/AppDelegate.swift b/packages/local_auth/local_auth_darwin/example/ios/Runner/AppDelegate.swift new file mode 100644 index 000000000000..81eca8683601 --- /dev/null +++ b/packages/local_auth/local_auth_darwin/example/ios/Runner/AppDelegate.swift @@ -0,0 +1,20 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } + + func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { + GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + } +} diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json index d22f10b2ab63..d36b1fab2d9d 100644 --- a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json +++ b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -107,6 +107,12 @@ "idiom" : "ipad", "filename" : "Icon-App-83.5x83.5@2x.png", "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" } ], "info" : { diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 000000000000..dc9ada4725e9 Binary files /dev/null and b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png index 28c6bf03016f..7353c41ecf9c 100644 Binary files a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png and b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png index 2ccbfd967d96..797d452e4589 100644 Binary files a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png and b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png index f091b6b0bca8..6ed2d933e112 100644 Binary files a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png and b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png index 4cde12118dda..4cd7b0099ca8 100644 Binary files a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png and b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png index d0ef06e7edb8..fe730945a01f 100644 Binary files a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png and b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png index dcdc2306c285..321773cd857a 100644 Binary files a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png and b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png index 2ccbfd967d96..797d452e4589 100644 Binary files a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png and b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png index c8f9ed8f5cee..502f463a9bc8 100644 Binary files a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png and b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png index a6d6b8609df0..0ec303439225 100644 Binary files a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png and b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png index a6d6b8609df0..0ec303439225 100644 Binary files a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png and b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png index 75b2d164a5a9..e9f5fea27c70 100644 Binary files a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png and b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png index c4df70d39da7..84ac32ae7d98 100644 Binary files a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png and b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png index 6a84f41e14e2..8953cba09064 100644 Binary files a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png and b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png index d0e1f5853602..0467bf12aa4d 100644 Binary files a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png and b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 000000000000..0bedcf2fd467 --- /dev/null +++ b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 000000000000..9da19eacad3b Binary files /dev/null and b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 000000000000..9da19eacad3b Binary files /dev/null and b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 000000000000..9da19eacad3b Binary files /dev/null and b/packages/local_auth/local_auth_darwin/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Base.lproj/LaunchScreen.storyboard b/packages/local_auth/local_auth_darwin/example/ios/Runner/Base.lproj/LaunchScreen.storyboard index ebf48f603974..f2e259c7c939 100644 --- a/packages/local_auth/local_auth_darwin/example/ios/Runner/Base.lproj/LaunchScreen.storyboard +++ b/packages/local_auth/local_auth_darwin/example/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -1,8 +1,8 @@ - + - + @@ -10,13 +10,20 @@ - - + + - - + + + + + + + + + @@ -24,4 +31,7 @@ + + + diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Info.plist b/packages/local_auth/local_auth_darwin/example/ios/Runner/Info.plist index 2dc92f5dff1c..5f5d64a539e7 100644 --- a/packages/local_auth/local_auth_darwin/example/ios/Runner/Info.plist +++ b/packages/local_auth/local_auth_darwin/example/ios/Runner/Info.plist @@ -2,8 +2,12 @@ + CADisableMinimumFrameDurationOnPhone + CFBundleDevelopmentRegion - en + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Local Auth Darwin Example CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier @@ -11,25 +15,46 @@ CFBundleInfoDictionaryVersion 6.0 CFBundleName - local_auth_example + local_auth_darwin_example CFBundlePackageType APPL CFBundleShortVersionString - 1.0 + $(FLUTTER_BUILD_NAME) CFBundleSignature ???? CFBundleVersion - 1 + $(FLUTTER_BUILD_NUMBER) LSRequiresIPhoneOS + NSFaceIDUsageDescription + App needs to authenticate using faces. + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneClassName + UIWindowScene + UISceneConfigurationName + flutter + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UIApplicationSupportsIndirectInputEvents + UILaunchStoryboardName LaunchScreen UIMainStoryboardFile Main - UIRequiredDeviceCapabilities - - arm64 - UISupportedInterfaceOrientations UIInterfaceOrientationPortrait @@ -43,11 +68,5 @@ UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight - NSFaceIDUsageDescription - App needs to authenticate using faces. - CADisableMinimumFrameDurationOnPhone - - UIApplicationSupportsIndirectInputEvents - diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/Runner-Bridging-Header.h b/packages/local_auth/local_auth_darwin/example/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 000000000000..ba04211afd0a --- /dev/null +++ b/packages/local_auth/local_auth_darwin/example/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1,5 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "GeneratedPluginRegistrant.h" diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/SceneDelegate.swift b/packages/local_auth/local_auth_darwin/example/ios/Runner/SceneDelegate.swift new file mode 100644 index 000000000000..8c7b10c639d1 --- /dev/null +++ b/packages/local_auth/local_auth_darwin/example/ios/Runner/SceneDelegate.swift @@ -0,0 +1,10 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import Flutter +import UIKit + +class SceneDelegate: FlutterSceneDelegate { + +} diff --git a/packages/local_auth/local_auth_darwin/example/ios/Runner/main.m b/packages/local_auth/local_auth_darwin/example/ios/Runner/main.m deleted file mode 100644 index fc7b5903f185..000000000000 --- a/packages/local_auth/local_auth_darwin/example/ios/Runner/main.m +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import -#import -#import "AppDelegate.h" - -int main(int argc, char *argv[]) { - @autoreleasepool { - return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); - } -} diff --git a/packages/local_auth/local_auth_darwin/example/lib/main.dart b/packages/local_auth/local_auth_darwin/example/lib/main.dart index 0c9fabec4132..c14e5862d97f 100644 --- a/packages/local_auth/local_auth_darwin/example/lib/main.dart +++ b/packages/local_auth/local_auth_darwin/example/lib/main.dart @@ -78,7 +78,7 @@ class _MyAppState extends State { } Future _authenticate() async { - bool authenticated = false; + var authenticated = false; try { setState(() { _isAuthenticating = true; @@ -120,7 +120,7 @@ class _MyAppState extends State { } Future _authenticateWithBiometrics() async { - bool authenticated = false; + var authenticated = false; try { setState(() { _isAuthenticating = true; @@ -161,7 +161,7 @@ class _MyAppState extends State { return; } - final String message = authenticated ? 'Authorized' : 'Not Authorized'; + final message = authenticated ? 'Authorized' : 'Not Authorized'; setState(() { _authorized = message; }); diff --git a/packages/local_auth/local_auth_darwin/example/macos/Flutter/Flutter-Debug.xcconfig b/packages/local_auth/local_auth_darwin/example/macos/Flutter/Flutter-Debug.xcconfig index 4b81f9b2d200..c2efd0b608ba 100644 --- a/packages/local_auth/local_auth_darwin/example/macos/Flutter/Flutter-Debug.xcconfig +++ b/packages/local_auth/local_auth_darwin/example/macos/Flutter/Flutter-Debug.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" diff --git a/packages/local_auth/local_auth_darwin/example/macos/Flutter/Flutter-Release.xcconfig b/packages/local_auth/local_auth_darwin/example/macos/Flutter/Flutter-Release.xcconfig index 5caa9d1579e4..c2efd0b608ba 100644 --- a/packages/local_auth/local_auth_darwin/example/macos/Flutter/Flutter-Release.xcconfig +++ b/packages/local_auth/local_auth_darwin/example/macos/Flutter/Flutter-Release.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" diff --git a/packages/local_auth/local_auth_darwin/example/macos/Podfile b/packages/local_auth/local_auth_darwin/example/macos/Podfile deleted file mode 100644 index ff5ddb3b8bdc..000000000000 --- a/packages/local_auth/local_auth_darwin/example/macos/Podfile +++ /dev/null @@ -1,42 +0,0 @@ -platform :osx, '10.15' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\"" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_macos_podfile_setup - -target 'Runner' do - use_frameworks! - - flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__)) - target 'RunnerTests' do - inherit! :search_paths - end -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_macos_build_settings(target) - end -end diff --git a/packages/local_auth/local_auth_darwin/example/macos/Runner.xcodeproj/project.pbxproj b/packages/local_auth/local_auth_darwin/example/macos/Runner.xcodeproj/project.pbxproj index b54d673878b3..d857380a42d3 100644 --- a/packages/local_auth/local_auth_darwin/example/macos/Runner.xcodeproj/project.pbxproj +++ b/packages/local_auth/local_auth_darwin/example/macos/Runner.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 54; + objectVersion = 60; objects = { /* Begin PBXAggregateTarget section */ @@ -21,13 +21,11 @@ /* End PBXAggregateTarget section */ /* Begin PBXBuildFile section */ - 274905EC52005E05DF633ACA /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 91FACED086369F6DB644E8B1 /* Pods_Runner.framework */; }; 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; - 3A858B24A41D64C4BF302405 /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CB20D00B3AAB343668A80A59 /* Pods_RunnerTests.framework */; }; 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; E62C10892C07DA2A000E3CCC /* FLALocalAuthPluginTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E62C10882C07DA2A000E3CCC /* FLALocalAuthPluginTests.swift */; }; /* End PBXBuildFile section */ @@ -63,7 +61,6 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 09A6D0964FC42F6CEB3383B0 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; @@ -79,15 +76,11 @@ 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; - 6DC2CC18007F1B81C5CD38EB /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; - 6E148E4EE27FBB2587C8CCE0 /* 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 = ""; }; + 784666492D4C4C64000A1A5F /* FlutterFramework */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterFramework; path = ephemeral/Packages/.packages/FlutterFramework; sourceTree = ""; }; + 78DABEA22ED26510000E7860 /* local_auth_darwin */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = local_auth_darwin; path = ../../../darwin/local_auth_darwin; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; - 7C88C93F66E851DCCA28120C /* 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 = ""; }; - 8CA026E1D618025C0D52DD90 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; - 91FACED086369F6DB644E8B1 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; - CB20D00B3AAB343668A80A59 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - DC8BF0B04B7666C6A6EA0D26 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; E62C10882C07DA2A000E3CCC /* FLALocalAuthPluginTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = FLALocalAuthPluginTests.swift; path = ../../../darwin/Tests/FLALocalAuthPluginTests.swift; sourceTree = ""; }; /* End PBXFileReference section */ @@ -96,7 +89,6 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 3A858B24A41D64C4BF302405 /* Pods_RunnerTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -105,7 +97,6 @@ buildActionMask = 2147483647; files = ( 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, - 274905EC52005E05DF633ACA /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -138,7 +129,6 @@ 33CEB47122A05771004F2AC0 /* Flutter */, 331C80D6294CF71000263BE5 /* RunnerTests */, 33CC10EE2044A3C60003C045 /* Products */, - D73912EC22F37F3D000D13A0 /* Frameworks */, 42D886FD4D6805989133E5D0 /* Pods */, ); sourceTree = ""; @@ -166,6 +156,9 @@ 33CEB47122A05771004F2AC0 /* Flutter */ = { isa = PBXGroup; children = ( + 78DABEA22ED26510000E7860 /* local_auth_darwin */, + 784666492D4C4C64000A1A5F /* FlutterFramework */, + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, @@ -190,25 +183,10 @@ 42D886FD4D6805989133E5D0 /* Pods */ = { isa = PBXGroup; children = ( - 09A6D0964FC42F6CEB3383B0 /* Pods-Runner.debug.xcconfig */, - 8CA026E1D618025C0D52DD90 /* Pods-Runner.release.xcconfig */, - DC8BF0B04B7666C6A6EA0D26 /* Pods-Runner.profile.xcconfig */, - 7C88C93F66E851DCCA28120C /* Pods-RunnerTests.debug.xcconfig */, - 6E148E4EE27FBB2587C8CCE0 /* Pods-RunnerTests.release.xcconfig */, - 6DC2CC18007F1B81C5CD38EB /* Pods-RunnerTests.profile.xcconfig */, ); path = Pods; sourceTree = ""; }; - D73912EC22F37F3D000D13A0 /* Frameworks */ = { - isa = PBXGroup; - children = ( - 91FACED086369F6DB644E8B1 /* Pods_Runner.framework */, - CB20D00B3AAB343668A80A59 /* Pods_RunnerTests.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -216,7 +194,6 @@ isa = PBXNativeTarget; buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; buildPhases = ( - 079FC72150E3D6C338EFB4FA /* [CP] Check Pods Manifest.lock */, 331C80D1294CF70F00263BE5 /* Sources */, 331C80D2294CF70F00263BE5 /* Frameworks */, 331C80D3294CF70F00263BE5 /* Resources */, @@ -235,7 +212,6 @@ isa = PBXNativeTarget; buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - 15765A7727B689B854708867 /* [CP] Check Pods Manifest.lock */, 33CC10E92044A3C60003C045 /* Sources */, 33CC10EA2044A3C60003C045 /* Frameworks */, 33CC10EB2044A3C60003C045 /* Resources */, @@ -330,50 +306,6 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 079FC72150E3D6C338EFB4FA /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 15765A7727B689B854708867 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; 3399D490228B24CF009A79C7 /* ShellScript */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; @@ -463,7 +395,6 @@ /* Begin XCBuildConfiguration section */ 331C80DB294CF71000263BE5 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 7C88C93F66E851DCCA28120C /* Pods-RunnerTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CLANG_ENABLE_MODULES = YES; @@ -473,14 +404,13 @@ PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.example.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 6.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/example.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/example"; }; name = Debug; }; 331C80DC294CF71000263BE5 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 6E148E4EE27FBB2587C8CCE0 /* Pods-RunnerTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CLANG_ENABLE_MODULES = YES; @@ -489,14 +419,13 @@ MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.example.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 6.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/example.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/example"; }; name = Release; }; 331C80DD294CF71000263BE5 /* Profile */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 6DC2CC18007F1B81C5CD38EB /* Pods-RunnerTests.profile.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CLANG_ENABLE_MODULES = YES; @@ -505,7 +434,7 @@ MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.example.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 6.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/example.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/example"; }; name = Profile; diff --git a/packages/local_auth/local_auth_darwin/lib/local_auth_darwin.dart b/packages/local_auth/local_auth_darwin/lib/local_auth_darwin.dart index 82ee3554e399..461c0c57c748 100644 --- a/packages/local_auth/local_auth_darwin/lib/local_auth_darwin.dart +++ b/packages/local_auth/local_auth_darwin/lib/local_auth_darwin.dart @@ -124,7 +124,7 @@ class LocalAuthDarwin extends LocalAuthPlatform { Iterable messagesList, ) { IOSAuthMessages? messages; - for (final AuthMessages entry in messagesList) { + for (final entry in messagesList) { if (entry is IOSAuthMessages) { messages = entry; break; @@ -142,7 +142,7 @@ class LocalAuthDarwin extends LocalAuthPlatform { Iterable messagesList, ) { MacOSAuthMessages? messages; - for (final AuthMessages entry in messagesList) { + for (final entry in messagesList) { if (entry is MacOSAuthMessages) { messages = entry; break; diff --git a/packages/local_auth/local_auth_darwin/pubspec.yaml b/packages/local_auth/local_auth_darwin/pubspec.yaml index 6ececfdadbfd..976f2a614523 100644 --- a/packages/local_auth/local_auth_darwin/pubspec.yaml +++ b/packages/local_auth/local_auth_darwin/pubspec.yaml @@ -2,11 +2,11 @@ name: local_auth_darwin description: iOS implementation of the local_auth plugin. repository: https://github.com/flutter/packages/tree/main/packages/local_auth/local_auth_darwin issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+local_auth%22 -version: 2.0.1 +version: 2.0.3 environment: - sdk: ^3.9.0 - flutter: ">=3.35.0" + sdk: ^3.10.0 + flutter: ">=3.38.0" flutter: plugin: diff --git a/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.dart b/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.dart index 4f6e37515e84..169cb4677880 100644 --- a/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.dart +++ b/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.dart @@ -94,7 +94,7 @@ void main() { (_) async => AuthResultDetails(result: AuthResult.success), ); - const String reason = 'test reason'; + const reason = 'test reason'; await plugin.authenticate( localizedReason: reason, authMessages: [], @@ -103,7 +103,7 @@ void main() { final VerificationResult result = verify( api.authenticate(any, captureAny), ); - final AuthStrings strings = result.captured[0] as AuthStrings; + final strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); // These should all be the default values from // auth_messages_ios.dart @@ -123,7 +123,7 @@ void main() { (_) async => AuthResultDetails(result: AuthResult.success), ); - const String reason = 'test reason'; + const reason = 'test reason'; await plugin.authenticate( localizedReason: reason, authMessages: [AnotherPlatformAuthMessages()], @@ -132,7 +132,7 @@ void main() { final VerificationResult result = verify( api.authenticate(any, captureAny), ); - final AuthStrings strings = result.captured[0] as AuthStrings; + final strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); // These should all be the default values from // auth_messages_ios.dart @@ -153,7 +153,7 @@ void main() { (_) async => AuthResultDetails(result: AuthResult.success), ); - const String reason = 'test reason'; + const reason = 'test reason'; await plugin.authenticate( localizedReason: reason, authMessages: [const MacOSAuthMessages()], @@ -162,7 +162,7 @@ void main() { final VerificationResult result = verify( api.authenticate(any, captureAny), ); - final AuthStrings strings = result.captured[0] as AuthStrings; + final strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); // These should all be the default values from // auth_messages_ios.dart @@ -186,9 +186,9 @@ void main() { // These are arbitrary values; all that matters is that: // - they are different from the defaults, and // - they are different from each other. - const String reason = 'A'; - const String cancel = 'B'; - const String localizedFallbackTitle = 'C'; + const reason = 'A'; + const cancel = 'B'; + const localizedFallbackTitle = 'C'; await plugin.authenticate( localizedReason: reason, @@ -204,7 +204,7 @@ void main() { final VerificationResult result = verify( api.authenticate(any, captureAny), ); - final AuthStrings strings = result.captured[0] as AuthStrings; + final strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); expect(strings.cancelButton, cancel); expect(strings.localizedFallbackTitle, localizedFallbackTitle); @@ -225,9 +225,9 @@ void main() { // These are arbitrary values; all that matters is that: // - they are different from the defaults, and // - they are different from each other. - const String reason = 'A'; - const String cancel = 'B'; - const String localizedFallbackTitle = 'C'; + const reason = 'A'; + const cancel = 'B'; + const localizedFallbackTitle = 'C'; await plugin.authenticate( localizedReason: reason, authMessages: [ @@ -242,7 +242,7 @@ void main() { final VerificationResult result = verify( api.authenticate(any, captureAny), ); - final AuthStrings strings = result.captured[0] as AuthStrings; + final strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); expect(strings.cancelButton, cancel); expect(strings.localizedFallbackTitle, localizedFallbackTitle); @@ -259,8 +259,8 @@ void main() { // These are arbitrary values; all that matters is that: // - they are different from the defaults, and // - they are different from each other. - const String reason = 'A'; - const String localizedFallbackTitle = 'B'; + const reason = 'A'; + const localizedFallbackTitle = 'B'; await plugin.authenticate( localizedReason: reason, authMessages: [ @@ -273,7 +273,7 @@ void main() { final VerificationResult result = verify( api.authenticate(any, captureAny), ); - final AuthStrings strings = result.captured[0] as AuthStrings; + final strings = result.captured[0] as AuthStrings; // These should all be the provided values. expect(strings.reason, reason); expect(strings.localizedFallbackTitle, localizedFallbackTitle); @@ -299,7 +299,7 @@ void main() { final VerificationResult result = verify( api.authenticate(captureAny, any), ); - final AuthOptions options = result.captured[0] as AuthOptions; + final options = result.captured[0] as AuthOptions; expect(options.biometricOnly, false); expect(options.sticky, false); }); @@ -321,7 +321,7 @@ void main() { final VerificationResult result = verify( api.authenticate(captureAny, any), ); - final AuthOptions options = result.captured[0] as AuthOptions; + final options = result.captured[0] as AuthOptions; expect(options.biometricOnly, true); expect(options.sticky, true); }); @@ -371,8 +371,8 @@ void main() { test( 'converts uiUnavailable to LocalAuthExceptionCode.uiUnavailable', () async { - const String errorMessage = 'a message'; - const String errorDetails = 'some details'; + const errorMessage = 'a message'; + const errorDetails = 'some details'; when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResultDetails( result: AuthResult.uiUnavailable, @@ -411,8 +411,8 @@ void main() { test( 'converts systemCancel to LocalAuthExceptionCode.systemCanceled', () async { - const String errorMessage = 'a message'; - const String errorDetails = 'some details'; + const errorMessage = 'a message'; + const errorDetails = 'some details'; when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResultDetails( result: AuthResult.systemCancel, @@ -451,8 +451,8 @@ void main() { test( 'converts userCancel to LocalAuthExceptionCode.userCanceled', () async { - const String errorMessage = 'a message'; - const String errorDetails = 'some details'; + const errorMessage = 'a message'; + const errorDetails = 'some details'; when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResultDetails( result: AuthResult.userCancel, @@ -491,8 +491,8 @@ void main() { test( 'converts biometryDisconnected to LocalAuthExceptionCode.biometricHardwareTemporarilyUnavailable', () async { - const String errorMessage = 'a message'; - const String errorDetails = 'some details'; + const errorMessage = 'a message'; + const errorDetails = 'some details'; when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResultDetails( result: AuthResult.biometryDisconnected, @@ -532,8 +532,8 @@ void main() { test( 'converts biometryLockout to LocalAuthExceptionCode.biometricLockout', () async { - const String errorMessage = 'a message'; - const String errorDetails = 'some details'; + const errorMessage = 'a message'; + const errorDetails = 'some details'; when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResultDetails( result: AuthResult.biometryLockout, @@ -572,8 +572,8 @@ void main() { test( 'converts biometryNotAvailable to LocalAuthExceptionCode.noBiometricHardware', () async { - const String errorMessage = 'a message'; - const String errorDetails = 'some details'; + const errorMessage = 'a message'; + const errorDetails = 'some details'; when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResultDetails( result: AuthResult.biometryNotAvailable, @@ -612,8 +612,8 @@ void main() { test( 'converts biometryNotPaired to LocalAuthExceptionCode.noBiometricHardware', () async { - const String errorMessage = 'a message'; - const String errorDetails = 'some details'; + const errorMessage = 'a message'; + const errorDetails = 'some details'; when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResultDetails( result: AuthResult.biometryNotPaired, @@ -652,8 +652,8 @@ void main() { test( 'converts biometryNotEnrolled to LocalAuthExceptionCode.noBiometricsEnrolled', () async { - const String errorMessage = 'a message'; - const String errorDetails = 'some details'; + const errorMessage = 'a message'; + const errorDetails = 'some details'; when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResultDetails( result: AuthResult.biometryNotEnrolled, @@ -692,8 +692,8 @@ void main() { test( 'converts invalidContext to LocalAuthExceptionCode.uiUnavailable', () async { - const String errorMessage = 'a message'; - const String errorDetails = 'some details'; + const errorMessage = 'a message'; + const errorDetails = 'some details'; when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResultDetails( result: AuthResult.invalidContext, @@ -732,8 +732,8 @@ void main() { test( 'converts invalidDimensions to LocalAuthExceptionCode.uiUnavailable', () async { - const String errorMessage = 'a message'; - const String errorDetails = 'some details'; + const errorMessage = 'a message'; + const errorDetails = 'some details'; when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResultDetails( result: AuthResult.invalidDimensions, @@ -772,8 +772,8 @@ void main() { test( 'converts notInteractive to LocalAuthExceptionCode.uiUnavailable', () async { - const String errorMessage = 'a message'; - const String errorDetails = 'some details'; + const errorMessage = 'a message'; + const errorDetails = 'some details'; when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResultDetails( result: AuthResult.notInteractive, @@ -812,8 +812,8 @@ void main() { test( 'converts passcodeNotSet to LocalAuthExceptionCode.noCredentialsSet', () async { - const String errorMessage = 'a message'; - const String errorDetails = 'some details'; + const errorMessage = 'a message'; + const errorDetails = 'some details'; when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResultDetails( result: AuthResult.passcodeNotSet, @@ -852,8 +852,8 @@ void main() { test( 'converts userFallback to LocalAuthExceptionCode.userRequestedFallback', () async { - const String errorMessage = 'a message'; - const String errorDetails = 'some details'; + const errorMessage = 'a message'; + const errorDetails = 'some details'; when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResultDetails( result: AuthResult.userFallback, @@ -892,8 +892,8 @@ void main() { test( 'converts unknownError to LocalAuthExceptionCode.unknownError', () async { - const String errorMessage = 'a message'; - const String errorDetails = 'some details'; + const errorMessage = 'a message'; + const errorDetails = 'some details'; when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResultDetails( result: AuthResult.unknownError, diff --git a/packages/local_auth/local_auth_platform_interface/CHANGELOG.md b/packages/local_auth/local_auth_platform_interface/CHANGELOG.md index 42419a0370e6..98a6c6344700 100644 --- a/packages/local_auth/local_auth_platform_interface/CHANGELOG.md +++ b/packages/local_auth/local_auth_platform_interface/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. ## 1.1.0 diff --git a/packages/local_auth/local_auth_platform_interface/lib/default_method_channel_platform.dart b/packages/local_auth/local_auth_platform_interface/lib/default_method_channel_platform.dart index 822b35730467..ec4606f89797 100644 --- a/packages/local_auth/local_auth_platform_interface/lib/default_method_channel_platform.dart +++ b/packages/local_auth/local_auth_platform_interface/lib/default_method_channel_platform.dart @@ -22,14 +22,14 @@ class DefaultLocalAuthPlatform extends LocalAuthPlatform { AuthenticationOptions options = const AuthenticationOptions(), }) async { assert(localizedReason.isNotEmpty); - final Map args = { + final args = { 'localizedReason': localizedReason, 'useErrorDialogs': options.useErrorDialogs, 'stickyAuth': options.stickyAuth, 'sensitiveTransaction': options.sensitiveTransaction, 'biometricOnly': options.biometricOnly, }; - for (final AuthMessages messages in authMessages) { + for (final messages in authMessages) { args.addAll(messages.args); } return (await _channel.invokeMethod('authenticate', args)) ?? false; @@ -40,8 +40,8 @@ class DefaultLocalAuthPlatform extends LocalAuthPlatform { final List result = (await _channel.invokeListMethod('getAvailableBiometrics')) ?? []; - final List biometrics = []; - for (final String value in result) { + final biometrics = []; + for (final value in result) { switch (value) { case 'face': biometrics.add(BiometricType.face); diff --git a/packages/local_auth/local_auth_platform_interface/pubspec.yaml b/packages/local_auth/local_auth_platform_interface/pubspec.yaml index b428edfcd2f0..13512c3ef123 100644 --- a/packages/local_auth/local_auth_platform_interface/pubspec.yaml +++ b/packages/local_auth/local_auth_platform_interface/pubspec.yaml @@ -7,8 +7,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 1.1.0 environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" dependencies: flutter: diff --git a/packages/local_auth/local_auth_platform_interface/test/default_method_channel_platform_test.dart b/packages/local_auth/local_auth_platform_interface/test/default_method_channel_platform_test.dart index c538336e1fc5..5372ca1b1510 100644 --- a/packages/local_auth/local_auth_platform_interface/test/default_method_channel_platform_test.dart +++ b/packages/local_auth/local_auth_platform_interface/test/default_method_channel_platform_test.dart @@ -10,7 +10,7 @@ import 'package:local_auth_platform_interface/local_auth_platform_interface.dart void main() { TestWidgetsFlutterBinding.ensureInitialized(); - const MethodChannel channel = MethodChannel('plugins.flutter.io/local_auth'); + const channel = MethodChannel('plugins.flutter.io/local_auth'); late List log; late LocalAuthPlatform localAuthentication; diff --git a/packages/local_auth/local_auth_windows/CHANGELOG.md b/packages/local_auth/local_auth_windows/CHANGELOG.md index 6eb1c4e24470..060e6d6abd81 100644 --- a/packages/local_auth/local_auth_windows/CHANGELOG.md +++ b/packages/local_auth/local_auth_windows/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. + ## 2.0.1 * Updates to Pigeon 26. diff --git a/packages/local_auth/local_auth_windows/example/lib/main.dart b/packages/local_auth/local_auth_windows/example/lib/main.dart index 1c76c6abb150..5d76d8a34de2 100644 --- a/packages/local_auth/local_auth_windows/example/lib/main.dart +++ b/packages/local_auth/local_auth_windows/example/lib/main.dart @@ -78,7 +78,7 @@ class _MyAppState extends State { } Future _authenticate() async { - bool authenticated = false; + var authenticated = false; try { setState(() { _isAuthenticating = true; diff --git a/packages/local_auth/local_auth_windows/example/pubspec.yaml b/packages/local_auth/local_auth_windows/example/pubspec.yaml index 0f4e48bfbc29..941ed568d843 100644 --- a/packages/local_auth/local_auth_windows/example/pubspec.yaml +++ b/packages/local_auth/local_auth_windows/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the local_auth_windows plugin. publish_to: none environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" dependencies: flutter: diff --git a/packages/local_auth/local_auth_windows/pubspec.yaml b/packages/local_auth/local_auth_windows/pubspec.yaml index 9853bda3864c..04a7b7b2ee02 100644 --- a/packages/local_auth/local_auth_windows/pubspec.yaml +++ b/packages/local_auth/local_auth_windows/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.0.1 environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" flutter: plugin: diff --git a/packages/material_ui/.gitignore b/packages/material_ui/.gitignore new file mode 100644 index 000000000000..dd5eb98951f2 --- /dev/null +++ b/packages/material_ui/.gitignore @@ -0,0 +1,31 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +.flutter-plugins-dependencies +/build/ +/coverage/ diff --git a/packages/material_ui/.metadata b/packages/material_ui/.metadata new file mode 100644 index 000000000000..e44d1b1ea178 --- /dev/null +++ b/packages/material_ui/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "4d0d113b75746f1ec1d93a976f0f02f6bb61dc2d" + channel: "[user-branch]" + +project_type: package diff --git a/packages/material_ui/AUTHORS b/packages/material_ui/AUTHORS new file mode 100644 index 000000000000..557dff97933b --- /dev/null +++ b/packages/material_ui/AUTHORS @@ -0,0 +1,6 @@ +# Below is a list of people and organizations that have contributed +# to the Flutter project. Names should be added to the list like so: +# +# Name/Organization + +Google Inc. diff --git a/packages/material_ui/CHANGELOG.md b/packages/material_ui/CHANGELOG.md new file mode 100644 index 000000000000..2807f26fb5c6 --- /dev/null +++ b/packages/material_ui/CHANGELOG.md @@ -0,0 +1,3 @@ +## 0.0.1 + +* Initial setup of the `material_ui` package, preparing for decoupling Material widgets from the Flutter framework. diff --git a/packages/material_ui/LICENSE b/packages/material_ui/LICENSE new file mode 100644 index 000000000000..29b709dac6c7 --- /dev/null +++ b/packages/material_ui/LICENSE @@ -0,0 +1,25 @@ +Copyright 2013 The Flutter Authors + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + * Neither the name of Google Inc. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/packages/material_ui/README.md b/packages/material_ui/README.md new file mode 100644 index 000000000000..c83917ec2baf --- /dev/null +++ b/packages/material_ui/README.md @@ -0,0 +1,25 @@ +# material\_ui + +**Coming soon \- the official Material Design widget library for Flutter as its own standalone package\!** + +`material_ui` will contain the standard collection of visual components (Buttons, Cards, AppBars, etc.) that implement Google's latest Material Design specification. + +**Note:** This package will contain the material library previously part of the Flutter framework itself (`package:flutter/material.dart`). It is being decoupled to allow for faster iteration and a more modular ecosystem. + +## What's (going to be) inside? + +This package will provide the Material widgets you know and love, including but not limited to: + +* **Structure:** `Scaffold`, `AppBar`, `Drawer` +* **Inputs:** `FloatingActionButton`, `TextField`, `Slider` +* **Display:** `Card`, `Chip`, `ListTile` +* **Theming:** `ThemeData`, `ColorScheme` + +Once landed and published, look forward to updates from [Material 3 Expressive](https://github.com/flutter/flutter/issues/168813)\! 🚀 + +## Feedback & roadmap + +We are currently migrating the Material library out of the core framework. + +* **Follow the progress:** [Decoupling Github Project](https://github.com/orgs/flutter/projects/220) +* **Report bugs:** [Material issues in Flutter](https://github.com/flutter/flutter/issues?q=is%3Aopen%20is%3Aissue%20label%3A%22f%3A%20material%20design%22) diff --git a/packages/material_ui/lib/material_ui.dart b/packages/material_ui/lib/material_ui.dart new file mode 100644 index 000000000000..1f2465f1265b --- /dev/null +++ b/packages/material_ui/lib/material_ui.dart @@ -0,0 +1,10 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +/// The Flutter Material Design library. +/// +/// To use, import `package:material_ui/material_ui.dart`. +library material_ui; + +export 'package:flutter/material.dart'; diff --git a/packages/material_ui/pubspec.yaml b/packages/material_ui/pubspec.yaml new file mode 100644 index 000000000000..1700a3878450 --- /dev/null +++ b/packages/material_ui/pubspec.yaml @@ -0,0 +1,22 @@ +name: material_ui +description: The official Flutter Material UI Library, implementing Google's Material Design design system. +version: 0.0.1 +repository: https://github.com/flutter/packages/tree/main/packages/material_ui +issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A%20material%20design%22 + +environment: + sdk: ^3.9.0 + flutter: ">=3.35.0" + +dependencies: + flutter: + sdk: flutter + +dev_dependencies: + flutter_test: + sdk: flutter + +topics: + - ui + - widgets + - material diff --git a/packages/material_ui/test/material_ui_test.dart b/packages/material_ui/test/material_ui_test.dart new file mode 100644 index 000000000000..205679858117 --- /dev/null +++ b/packages/material_ui/test/material_ui_test.dart @@ -0,0 +1,13 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter_test/flutter_test.dart'; + +import 'package:material_ui/material_ui.dart'; + +void main() { + testWidgets('Material library is exported', (WidgetTester tester) async { + await tester.pumpWidget(const MaterialApp(home: SizedBox.shrink())); + }); +} diff --git a/packages/metrics_center/CHANGELOG.md b/packages/metrics_center/CHANGELOG.md index f93b33e247bc..6f1d561d244b 100644 --- a/packages/metrics_center/CHANGELOG.md +++ b/packages/metrics_center/CHANGELOG.md @@ -1,6 +1,7 @@ -## NEXT +## 1.0.15 -* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. +* Fixes dartdoc comments that accidentally used HTML. +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. ## 1.0.14 diff --git a/packages/metrics_center/lib/src/common.dart b/packages/metrics_center/lib/src/common.dart index 126f66554ce5..ad2a1bc97443 100644 --- a/packages/metrics_center/lib/src/common.dart +++ b/packages/metrics_center/lib/src/common.dart @@ -52,15 +52,7 @@ abstract class MetricDestination { /// credentials json. It's currently the case for Chrmoium LUCI bots. AuthClient authClientFromAccessToken(String token, List scopes) { final DateTime anHourLater = DateTime.now().add(const Duration(hours: 1)); - final AccessToken accessToken = AccessToken( - 'Bearer', - token, - anHourLater.toUtc(), - ); - final AccessCredentials accessCredentials = AccessCredentials( - accessToken, - null, - scopes, - ); + final accessToken = AccessToken('Bearer', token, anHourLater.toUtc()); + final accessCredentials = AccessCredentials(accessToken, null, scopes); return authenticatedClient(Client(), accessCredentials); } diff --git a/packages/metrics_center/lib/src/gcs_lock.dart b/packages/metrics_center/lib/src/gcs_lock.dart index 0c1d05a3ed83..74a41fa7e09e 100644 --- a/packages/metrics_center/lib/src/gcs_lock.dart +++ b/packages/metrics_center/lib/src/gcs_lock.dart @@ -43,13 +43,13 @@ class GcsLock { } Future _lock(String lockFileName) async { - final Object object = Object(); + final object = Object(); object.bucket = _bucketName; object.name = lockFileName; - final Media content = Media(const Stream>.empty(), 0); + final content = Media(const Stream>.empty(), 0); - Duration waitPeriod = const Duration(milliseconds: 10); - bool locked = false; + var waitPeriod = const Duration(milliseconds: 10); + var locked = false; while (!locked) { try { await _api.objects.insert( @@ -82,8 +82,8 @@ class GcsLock { } Future _unlock(String lockFileName) async { - Duration waitPeriod = const Duration(milliseconds: 10); - bool unlocked = false; + var waitPeriod = const Duration(milliseconds: 10); + var unlocked = false; // Retry in the case of GCS returning an API error, but rethrow if unable // to unlock after a certain period of time. while (!unlocked) { diff --git a/packages/metrics_center/lib/src/google_benchmark.dart b/packages/metrics_center/lib/src/google_benchmark.dart index 8c907c214d9e..75a1f8a44982 100644 --- a/packages/metrics_center/lib/src/google_benchmark.dart +++ b/packages/metrics_center/lib/src/google_benchmark.dart @@ -41,17 +41,16 @@ const List _kContextIgnoreKeys = [ class GoogleBenchmarkParser { /// Given a Google benchmark json output, parse its content into a list of [MetricPoint]. static Future> parse(String jsonFileName) async { - final Map jsonResult = + final jsonResult = jsonDecode(File(jsonFileName).readAsStringSync()) as Map; - final Map rawContext = - jsonResult['context'] as Map; + final rawContext = jsonResult['context'] as Map; final Map context = rawContext.map( (String k, dynamic v) => MapEntry(k, v.toString()), )..removeWhere((String k, String v) => _kContextIgnoreKeys.contains(k)); - final List points = []; + final points = []; for (final dynamic item in jsonResult['benchmarks'] as List) { _parseAnItem(item as Map, points, context); } @@ -64,8 +63,8 @@ void _parseAnItem( List points, Map context, ) { - final String name = item[kNameKey] as String; - final Map timeUnitMap = { + final name = item[kNameKey] as String; + final timeUnitMap = { if (item.containsKey(_kTimeUnitKey)) kUnitKey: item[_kTimeUnitKey] as String, }; diff --git a/packages/metrics_center/lib/src/skiaperf.dart b/packages/metrics_center/lib/src/skiaperf.dart index d218e1ebbcdf..7f3b98afee6b 100644 --- a/packages/metrics_center/lib/src/skiaperf.dart +++ b/packages/metrics_center/lib/src/skiaperf.dart @@ -99,7 +99,7 @@ class SkiaPerfPoint extends MetricPoint { final String subResult = p.tags[kSubResultKey] ?? kSkiaPerfValueKey; - final Map options = {} + final options = {} ..addEntries( p.tags.entries.where( (MapEntry entry) => @@ -126,7 +126,7 @@ class SkiaPerfPoint extends MetricPoint { ); } - /// In the format of '/' such as 'flutter/flutter' or + /// In the format of `/` such as 'flutter/flutter' or /// 'flutter/engine'. final String githubRepo; @@ -169,7 +169,7 @@ class SkiaPerfPoint extends MetricPoint { static Map toSkiaPerfJson(List points) { assert(points.isNotEmpty); assert(() { - for (final SkiaPerfPoint p in points) { + for (final p in points) { if (p.githubRepo != points[0].githubRepo || p.gitHash != points[0].gitHash) { return false; @@ -178,8 +178,8 @@ class SkiaPerfPoint extends MetricPoint { return true; }(), 'All points must have same githubRepo and gitHash'); - final Map results = {}; - for (final SkiaPerfPoint p in points) { + final results = {}; + for (final p in points) { final Map subResultJson = p._toSubResultJson(); if (results[p.testName] == null) { results[p.testName] = { @@ -238,7 +238,7 @@ class SkiaPerfGcsAdaptor { final List content = utf8.encode(jsonString); // Retry multiple times as GCS may return 504 timeout. - for (int retry = 0; retry < 5; retry += 1) { + for (var retry = 0; retry < 5; retry += 1) { try { await _gcsBucket.writeBytes(objectName, content); return; @@ -265,7 +265,7 @@ class SkiaPerfGcsAdaptor { /// 504 happens. Future> readPoints(String objectName) async { // Retry multiple times as GCS may return 504 timeout. - for (int retry = 0; retry < 5; retry += 1) { + for (var retry = 0; retry < 5; retry += 1) { try { return await _readPointsWithoutRetry(objectName); } catch (e) { @@ -294,21 +294,20 @@ class SkiaPerfGcsAdaptor { final Stream> stream = _gcsBucket.read(objectName); final Stream byteStream = stream.expand((List x) => x); - final Map decodedJson = + final decodedJson = jsonDecode(utf8.decode(await byteStream.toList())) as Map; - final List points = []; + final points = []; final String firstGcsNameComponent = objectName.split('/')[0]; _populateGcsNameToGithubRepoMapIfNeeded(); final String githubRepo = _gcsNameToGithubRepo[firstGcsNameComponent]!; - final String? gitHash = decodedJson[kSkiaPerfGitHashKey] as String?; - final Map results = - decodedJson[kSkiaPerfResultsKey] as Map; + final gitHash = decodedJson[kSkiaPerfGitHashKey] as String?; + final results = decodedJson[kSkiaPerfResultsKey] as Map; for (final String name in results.keys) { - final Map subResultMap = + final subResultMap = results[name][kSkiaPerfDefaultConfig] as Map; for (final String subResult in subResultMap.keys.where( (String s) => s != kSkiaPerfOptionsKey, @@ -352,7 +351,7 @@ class SkiaPerfGcsAdaptor { final String month = commitUtcTime.month.toString().padLeft(2, '0'); final String day = commitUtcTime.day.toString().padLeft(2, '0'); final String hour = commitUtcTime.hour.toString().padLeft(2, '0'); - final String dateComponents = '${commitUtcTime.year}/$month/$day/$hour'; + final dateComponents = '${commitUtcTime.year}/$month/$day/$hour'; return '$topComponent/$dateComponents/$revision/${taskName}_values.json'; } @@ -414,15 +413,13 @@ class SkiaPerfDestination extends MetricDestination { String projectId, { bool isTesting = false, }) async { - final Storage storage = Storage(client, projectId); + final storage = Storage(client, projectId); final String bucketName = isTesting ? kTestBucketName : kBucketName; if (!await storage.bucketExists(bucketName)) { throw StateError('Bucket $bucketName does not exist.'); } - final SkiaPerfGcsAdaptor adaptor = SkiaPerfGcsAdaptor( - storage.bucket(bucketName), - ); - final GcsLock lock = GcsLock(StorageApi(client), bucketName); + final adaptor = SkiaPerfGcsAdaptor(storage.bucket(bucketName)); + final lock = GcsLock(StorageApi(client), bucketName); return SkiaPerfDestination(adaptor, lock); } @@ -446,7 +443,7 @@ class SkiaPerfDestination extends MetricDestination { } // All created locks must be released before returning - final List> lockFutures = >[]; + final lockFutures = >[]; // 2nd, read existing points from the gcs object and update with new ones. for (final String repo in pointMap.keys) { @@ -468,7 +465,7 @@ class SkiaPerfDestination extends MetricDestination { final List oldPoints = await _gcs.readPoints( objectName, ); - for (final SkiaPerfPoint p in oldPoints) { + for (final p in oldPoints) { if (newPoints![p.id] == null) { newPoints[p.id] = p; } diff --git a/packages/metrics_center/pubspec.yaml b/packages/metrics_center/pubspec.yaml index f059b9ec32cd..04a69d21304f 100644 --- a/packages/metrics_center/pubspec.yaml +++ b/packages/metrics_center/pubspec.yaml @@ -1,12 +1,12 @@ name: metrics_center -version: 1.0.14 +version: 1.0.15 description: Support multiple performance metrics sources/formats and destinations. repository: https://github.com/flutter/packages/tree/main/packages/metrics_center issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+metrics_center%22 environment: - sdk: ^3.8.0 + sdk: ^3.9.0 dependencies: _discoveryapis_commons: ^1.0.0 diff --git a/packages/metrics_center/test/flutter_test.dart b/packages/metrics_center/test/flutter_test.dart index eb27f65ce389..44cb155d41d2 100644 --- a/packages/metrics_center/test/flutter_test.dart +++ b/packages/metrics_center/test/flutter_test.dart @@ -9,8 +9,8 @@ import 'common.dart'; import 'utility.dart'; void main() { - const String gitRevision = 'ca799fa8b2254d09664b78ee80c43b434788d112'; - final FlutterEngineMetricPoint simplePoint = FlutterEngineMetricPoint( + const gitRevision = 'ca799fa8b2254d09664b78ee80c43b434788d112'; + final simplePoint = FlutterEngineMetricPoint( 'BM_ParagraphLongLayout', 287235, gitRevision, @@ -22,7 +22,7 @@ void main() { expect(simplePoint.tags[kGitRevisionKey], gitRevision); expect(simplePoint.tags[kNameKey], 'BM_ParagraphLongLayout'); - final FlutterEngineMetricPoint detailedPoint = FlutterEngineMetricPoint( + final detailedPoint = FlutterEngineMetricPoint( 'BM_ParagraphLongLayout', 287224, 'ca799fa8b2254d09664b78ee80c43b434788d112', diff --git a/packages/metrics_center/test/gcs_lock_test.dart b/packages/metrics_center/test/gcs_lock_test.dart index 8d3180e030de..4dbbb2b1cd68 100644 --- a/packages/metrics_center/test/gcs_lock_test.dart +++ b/packages/metrics_center/test/gcs_lock_test.dart @@ -26,20 +26,20 @@ enum TestPhase { run1, run2 } ], ) void main() { - const Duration kDelayStep = Duration(milliseconds: 10); + const kDelayStep = Duration(milliseconds: 10); final Map? credentialsJson = getTestGcpCredentialsJson(); test('GcsLock prints warnings for long waits', () { // Capture print to verify error messages. - final List prints = []; - final ZoneSpecification spec = ZoneSpecification( + final prints = []; + final spec = ZoneSpecification( print: (_, __, ___, String msg) => prints.add(msg), ); Zone.current.fork(specification: spec).run(() { fakeAsync((FakeAsync fakeAsync) { - final MockAuthClient mockClient = MockAuthClient(); - final GcsLock lock = GcsLock(StorageApi(mockClient), 'mockBucket'); + final mockClient = MockAuthClient(); + final lock = GcsLock(StorageApi(mockClient), 'mockBucket'); when(mockClient.send(any)).thenThrow(DetailedApiRequestError(412, '')); final Future runFinished = lock.protectedRun( 'mock.lock', @@ -48,7 +48,7 @@ void main() { fakeAsync.elapse(const Duration(seconds: 10)); when(mockClient.send(any)).thenThrow(AssertionError('Stop!')); runFinished.catchError((dynamic e) { - final AssertionError error = e as AssertionError; + final error = e as AssertionError; expect(error.message, 'Stop!'); // TODO(goderbauer): We should not be printing from a test. // ignore: avoid_print @@ -58,7 +58,7 @@ void main() { }); }); - const String kExpectedErrorMessage = + const kExpectedErrorMessage = 'The lock is waiting for a long time: ' '0:00:10.240000. If the lock file mock.lock in bucket mockBucket ' 'seems to be stuck (i.e., it was created a long time ago and no one ' @@ -73,8 +73,8 @@ void main() { ServiceAccountCredentials.fromJson(credentialsJson), Storage.SCOPES, ); - final GcsLock lock = GcsLock(StorageApi(client), kTestBucketName); - int testValue = 0; + final lock = GcsLock(StorageApi(client), kTestBucketName); + var testValue = 0; await lock.protectedRun('test.lock', () async { testValue = 1; }); @@ -90,11 +90,11 @@ void main() { ServiceAccountCredentials.fromJson(credentialsJson), Storage.SCOPES, ); - final GcsLock lock1 = GcsLock(StorageApi(client), kTestBucketName); - final GcsLock lock2 = GcsLock(StorageApi(client), kTestBucketName); + final lock1 = GcsLock(StorageApi(client), kTestBucketName); + final lock2 = GcsLock(StorageApi(client), kTestBucketName); TestPhase phase = TestPhase.run1; - final Completer started1 = Completer(); + final started1 = Completer(); final Future finished1 = lock1.protectedRun('test.lock', () async { started1.complete(); while (phase == TestPhase.run1) { @@ -104,7 +104,7 @@ void main() { await started1.future; - final Completer started2 = Completer(); + final started2 = Completer(); final Future finished2 = lock2.protectedRun('test.lock', () async { started2.complete(); }); @@ -128,8 +128,8 @@ void main() { fakeAsync((FakeAsync fakeAsync) { final StorageApi mockStorageApi = MockStorageApi(); final ObjectsResource mockObjectsResource = MockObjectsResource(); - final GcsLock gcsLock = GcsLock(mockStorageApi, kTestBucketName); - const String lockFileName = 'test.lock'; + final gcsLock = GcsLock(mockStorageApi, kTestBucketName); + const lockFileName = 'test.lock'; when(mockStorageApi.objects).thenReturn(mockObjectsResource); // Simulate a failure to delete a lock file. diff --git a/packages/metrics_center/test/google_benchmark_test.dart b/packages/metrics_center/test/google_benchmark_test.dart index 6f856ac07ba4..8e7a76257374 100644 --- a/packages/metrics_center/test/google_benchmark_test.dart +++ b/packages/metrics_center/test/google_benchmark_test.dart @@ -43,7 +43,7 @@ void main() { 'ParagraphFixture/TextBigO_BigO', 'ParagraphFixture/TextBigO_RMS', ]); - for (final MetricPoint p in points) { + for (final p in points) { expect(p.tags.containsKey('host_name'), false); expect(p.tags.containsKey('load_avg'), false); expect(p.tags.containsKey('caches'), false); diff --git a/packages/metrics_center/test/skiaperf_test.dart b/packages/metrics_center/test/skiaperf_test.dart index 424d8b123af3..864ac46cb7a5 100644 --- a/packages/metrics_center/test/skiaperf_test.dart +++ b/packages/metrics_center/test/skiaperf_test.dart @@ -59,46 +59,43 @@ class MockSkiaPerfGcsAdaptor implements SkiaPerfGcsAdaptor { @GenerateMocks([Bucket, ObjectInfo]) Future main() async { - const double kValue1 = 1.0; - const double kValue2 = 2.0; - const double kValue3 = 3.0; - - const String kFrameworkRevision1 = '9011cece2595447eea5dd91adaa241c1c9ef9a33'; - const String kFrameworkRevision2 = '372fe290e4d4f3f97cbf02a57d235771a9412f10'; - const String kEngineRevision1 = '617938024315e205f26ed72ff0f0647775fa6a71'; - const String kEngineRevision2 = '5858519139c22484aaff1cf5b26bdf7951259344'; - const String kTaskName = 'analyzer_benchmark'; - const String kMetric1 = 'flutter_repo_batch_maximum'; - const String kMetric2 = 'flutter_repo_watch_maximum'; - - final MetricPoint cocoonPointRev1Metric1 = - MetricPoint(kValue1, const { - kGithubRepoKey: kFlutterFrameworkRepo, - kGitRevisionKey: kFrameworkRevision1, - kNameKey: kTaskName, - kSubResultKey: kMetric1, - kUnitKey: 's', - }); + const kValue1 = 1.0; + const kValue2 = 2.0; + const kValue3 = 3.0; + + const kFrameworkRevision1 = '9011cece2595447eea5dd91adaa241c1c9ef9a33'; + const kFrameworkRevision2 = '372fe290e4d4f3f97cbf02a57d235771a9412f10'; + const kEngineRevision1 = '617938024315e205f26ed72ff0f0647775fa6a71'; + const kEngineRevision2 = '5858519139c22484aaff1cf5b26bdf7951259344'; + const kTaskName = 'analyzer_benchmark'; + const kMetric1 = 'flutter_repo_batch_maximum'; + const kMetric2 = 'flutter_repo_watch_maximum'; + + final cocoonPointRev1Metric1 = MetricPoint(kValue1, const { + kGithubRepoKey: kFlutterFrameworkRepo, + kGitRevisionKey: kFrameworkRevision1, + kNameKey: kTaskName, + kSubResultKey: kMetric1, + kUnitKey: 's', + }); - final MetricPoint cocoonPointRev1Metric2 = - MetricPoint(kValue2, const { - kGithubRepoKey: kFlutterFrameworkRepo, - kGitRevisionKey: kFrameworkRevision1, - kNameKey: kTaskName, - kSubResultKey: kMetric2, - kUnitKey: 's', - }); + final cocoonPointRev1Metric2 = MetricPoint(kValue2, const { + kGithubRepoKey: kFlutterFrameworkRepo, + kGitRevisionKey: kFrameworkRevision1, + kNameKey: kTaskName, + kSubResultKey: kMetric2, + kUnitKey: 's', + }); - final MetricPoint cocoonPointRev2Metric1 = - MetricPoint(kValue3, const { - kGithubRepoKey: kFlutterFrameworkRepo, - kGitRevisionKey: kFrameworkRevision2, - kNameKey: kTaskName, - kSubResultKey: kMetric1, - kUnitKey: 's', - }); + final cocoonPointRev2Metric1 = MetricPoint(kValue3, const { + kGithubRepoKey: kFlutterFrameworkRepo, + kGitRevisionKey: kFrameworkRevision2, + kNameKey: kTaskName, + kSubResultKey: kMetric1, + kUnitKey: 's', + }); - final MetricPoint cocoonPointBetaRev1Metric1 = + final cocoonPointBetaRev1Metric1 = MetricPoint(kValue1, const { kGithubRepoKey: kFlutterFrameworkRepo, kGitRevisionKey: kFrameworkRevision1, @@ -108,8 +105,7 @@ Future main() async { 'branch': 'beta', }); - final MetricPoint - cocoonPointBetaRev1Metric1BadBranch = MetricPoint(kValue1, const < + final cocoonPointBetaRev1Metric1BadBranch = MetricPoint(kValue1, const < String, String >{ @@ -126,12 +122,12 @@ Future main() async { 'branch': 'beta', }); - const String engineMetricName = 'BM_PaintRecordInit'; - const String engineRevision = 'ca799fa8b2254d09664b78ee80c43b434788d112'; + const engineMetricName = 'BM_PaintRecordInit'; + const engineRevision = 'ca799fa8b2254d09664b78ee80c43b434788d112'; const double engineValue1 = 101; const double engineValue2 = 102; - final FlutterEngineMetricPoint enginePoint1 = FlutterEngineMetricPoint( + final enginePoint1 = FlutterEngineMetricPoint( engineMetricName, engineValue1, engineRevision, @@ -146,7 +142,7 @@ Future main() async { }, ); - final FlutterEngineMetricPoint enginePoint2 = FlutterEngineMetricPoint( + final enginePoint2 = FlutterEngineMetricPoint( engineMetricName, engineValue2, engineRevision, @@ -162,29 +158,20 @@ Future main() async { ); test('Throw if invalid points are converted to SkiaPoint', () { - final MetricPoint noGithubRepoPoint = MetricPoint( - kValue1, - const { - kGitRevisionKey: kFrameworkRevision1, - kNameKey: kTaskName, - }, - ); + final noGithubRepoPoint = MetricPoint(kValue1, const { + kGitRevisionKey: kFrameworkRevision1, + kNameKey: kTaskName, + }); - final MetricPoint noGitRevisionPoint = MetricPoint( - kValue1, - const { - kGithubRepoKey: kFlutterFrameworkRepo, - kNameKey: kTaskName, - }, - ); + final noGitRevisionPoint = MetricPoint(kValue1, const { + kGithubRepoKey: kFlutterFrameworkRepo, + kNameKey: kTaskName, + }); - final MetricPoint noTestNamePoint = MetricPoint( - kValue1, - const { - kGithubRepoKey: kFlutterFrameworkRepo, - kGitRevisionKey: kFrameworkRevision1, - }, - ); + final noTestNamePoint = MetricPoint(kValue1, const { + kGithubRepoKey: kFlutterFrameworkRepo, + kGitRevisionKey: kFrameworkRevision1, + }); expect(() => SkiaPerfPoint.fromPoint(noGithubRepoPoint), throwsA(anything)); expect( @@ -195,9 +182,7 @@ Future main() async { }); test('Correctly convert a metric point from cocoon to SkiaPoint', () { - final SkiaPerfPoint skiaPoint1 = SkiaPerfPoint.fromPoint( - cocoonPointRev1Metric1, - ); + final skiaPoint1 = SkiaPerfPoint.fromPoint(cocoonPointRev1Metric1); expect(skiaPoint1, isNotNull); expect(skiaPoint1.testName, equals(kTaskName)); expect(skiaPoint1.subResult, equals(kMetric1)); @@ -206,13 +191,11 @@ Future main() async { }); test('Cocoon points correctly encode into Skia perf json format', () { - final SkiaPerfPoint p1 = SkiaPerfPoint.fromPoint(cocoonPointRev1Metric1); - final SkiaPerfPoint p2 = SkiaPerfPoint.fromPoint(cocoonPointRev1Metric2); - final SkiaPerfPoint p3 = SkiaPerfPoint.fromPoint( - cocoonPointBetaRev1Metric1, - ); + final p1 = SkiaPerfPoint.fromPoint(cocoonPointRev1Metric1); + final p2 = SkiaPerfPoint.fromPoint(cocoonPointRev1Metric2); + final p3 = SkiaPerfPoint.fromPoint(cocoonPointBetaRev1Metric1); - const JsonEncoder encoder = JsonEncoder.withIndent(' '); + const encoder = JsonEncoder.withIndent(' '); expect( encoder.convert( @@ -246,7 +229,7 @@ Future main() async { }); test('Engine metric points correctly encode into Skia perf json format', () { - const JsonEncoder encoder = JsonEncoder.withIndent(' '); + const encoder = JsonEncoder.withIndent(' '); expect( encoder.convert( SkiaPerfPoint.toSkiaPerfJson([ @@ -280,7 +263,7 @@ Future main() async { 'Throw if engine points with the same test name but different options are converted to ' 'Skia perf points', () { - final FlutterEngineMetricPoint enginePoint1 = FlutterEngineMetricPoint( + final enginePoint1 = FlutterEngineMetricPoint( 'BM_PaintRecordInit', 101, 'ca799fa8b2254d09664b78ee80c43b434788d112', @@ -290,7 +273,7 @@ Future main() async { 'cpu_scaling_enabled': 'true', }, ); - final FlutterEngineMetricPoint enginePoint2 = FlutterEngineMetricPoint( + final enginePoint2 = FlutterEngineMetricPoint( 'BM_PaintRecordInit', 102, 'ca799fa8b2254d09664b78ee80c43b434788d112', @@ -301,7 +284,7 @@ Future main() async { }, ); - const JsonEncoder encoder = JsonEncoder.withIndent(' '); + const encoder = JsonEncoder.withIndent(' '); expect( () => encoder.convert( SkiaPerfPoint.toSkiaPerfJson([ @@ -318,10 +301,8 @@ Future main() async { 'Throw if two Cocoon metric points with the same name and subResult keys ' 'but different options are converted to Skia perf points', () { - final SkiaPerfPoint p1 = SkiaPerfPoint.fromPoint(cocoonPointRev1Metric1); - final SkiaPerfPoint p2 = SkiaPerfPoint.fromPoint( - cocoonPointBetaRev1Metric1BadBranch, - ); + final p1 = SkiaPerfPoint.fromPoint(cocoonPointRev1Metric1); + final p2 = SkiaPerfPoint.fromPoint(cocoonPointBetaRev1Metric1BadBranch); expect( () => SkiaPerfPoint.toSkiaPerfJson([p1, p2]), @@ -363,8 +344,8 @@ Future main() async { }); test('Successfully read mock GCS that fails 1st time with 504', () async { - final MockBucket testBucket = MockBucket(); - final SkiaPerfGcsAdaptor skiaPerfGcs = SkiaPerfGcsAdaptor(testBucket); + final testBucket = MockBucket(); + final skiaPerfGcs = SkiaPerfGcsAdaptor(testBucket); final String testObjectName = await SkiaPerfGcsAdaptor.computeObjectName( kFlutterFrameworkRepo, @@ -373,7 +354,7 @@ Future main() async { 'test', ); - final List writePoints = [ + final writePoints = [ SkiaPerfPoint.fromPoint(cocoonPointRev1Metric1), ]; final String skiaPerfJson = jsonEncode( @@ -390,7 +371,7 @@ Future main() async { testBucket.info(testObjectName), ).thenThrow(DetailedApiRequestError(504, 'Test Failure')); - final MockObjectInfo mockObjectInfo = MockObjectInfo(); + final mockObjectInfo = MockObjectInfo(); when( mockObjectInfo.downloadLink, ).thenReturn(Uri.https('test.com', 'mock.json')); @@ -414,8 +395,8 @@ Future main() async { }); test('Return empty list if the GCS file does not exist', () async { - final MockBucket testBucket = MockBucket(); - final SkiaPerfGcsAdaptor skiaPerfGcs = SkiaPerfGcsAdaptor(testBucket); + final testBucket = MockBucket(); + final skiaPerfGcs = SkiaPerfGcsAdaptor(testBucket); final String testObjectName = await SkiaPerfGcsAdaptor.computeObjectName( kFlutterFrameworkRepo, kFrameworkRevision1, @@ -433,19 +414,15 @@ Future main() async { GcsLock? testLock; final Map? credentialsJson = getTestGcpCredentialsJson(); if (credentialsJson != null) { - final ServiceAccountCredentials credentials = - ServiceAccountCredentials.fromJson(credentialsJson); + final credentials = ServiceAccountCredentials.fromJson(credentialsJson); final AutoRefreshingAuthClient client = await clientViaServiceAccount( credentials, Storage.SCOPES, ); - final Storage storage = Storage( - client, - credentialsJson['project_id'] as String, - ); + final storage = Storage(client, credentialsJson['project_id'] as String); - const String kTestBucketName = 'flutter-skia-perf-test'; + const kTestBucketName = 'flutter-skia-perf-test'; assert(await storage.bucketExists(kTestBucketName)); testBucket = storage.bucket(kTestBucketName); @@ -453,7 +430,7 @@ Future main() async { } Future skiaPerfGcsAdapterIntegrationTest() async { - final SkiaPerfGcsAdaptor skiaPerfGcs = SkiaPerfGcsAdaptor(testBucket!); + final skiaPerfGcs = SkiaPerfGcsAdaptor(testBucket!); final String testObjectName = await SkiaPerfGcsAdaptor.computeObjectName( kFlutterFrameworkRepo, @@ -488,13 +465,13 @@ Future main() async { expectSetMatch(points.map((SkiaPerfPoint p) => p.gitHash), [ kFrameworkRevision1, ]); - for (int i = 0; i < 2; i += 1) { + for (var i = 0; i < 2; i += 1) { expect(points[0].jsonUrl, startsWith('https://')); } } Future skiaPerfGcsIntegrationTestWithEnginePoints() async { - final SkiaPerfGcsAdaptor skiaPerfGcs = SkiaPerfGcsAdaptor(testBucket!); + final skiaPerfGcs = SkiaPerfGcsAdaptor(testBucket!); final String testObjectName = await SkiaPerfGcsAdaptor.computeObjectName( kFlutterEngineRepo, @@ -526,7 +503,7 @@ Future main() async { expectSetMatch(points.map((SkiaPerfPoint p) => p.gitHash), [ engineRevision, ]); - for (int i = 0; i < 2; i += 1) { + for (var i = 0; i < 2; i += 1) { expect(points[0].jsonUrl, startsWith('https://')); } } @@ -591,13 +568,13 @@ Future main() async { ); test('SkiaPerfDestination.update awaits locks', () async { - bool updateCompleted = false; - final Completer callbackCompleter = Completer(); + var updateCompleted = false; + final callbackCompleter = Completer(); final SkiaPerfGcsAdaptor mockGcs = MockSkiaPerfGcsAdaptor( writePointsOverride: () => callbackCompleter.future, ); final GcsLock mockLock = MockGcsLock(); - final SkiaPerfDestination dst = SkiaPerfDestination(mockGcs, mockLock); + final dst = SkiaPerfDestination(mockGcs, mockLock); final Future updateFuture = dst.update( [cocoonPointRev1Metric1], DateTime.fromMillisecondsSinceEpoch(123), @@ -620,7 +597,7 @@ Future main() async { test('SkiaPerfDestination correctly updates points', () async { final SkiaPerfGcsAdaptor mockGcs = MockSkiaPerfGcsAdaptor(); final GcsLock mockLock = MockGcsLock(); - final SkiaPerfDestination dst = SkiaPerfDestination(mockGcs, mockLock); + final dst = SkiaPerfDestination(mockGcs, mockLock); await dst.update( [cocoonPointRev1Metric1], DateTime.fromMillisecondsSinceEpoch(123), @@ -652,10 +629,7 @@ Future main() async { kValue2, ]); - final MetricPoint updated = MetricPoint( - kValue3, - cocoonPointRev1Metric1.tags, - ); + final updated = MetricPoint(kValue3, cocoonPointRev1Metric1.tags); await dst.update( [updated, cocoonPointRev2Metric1], @@ -690,7 +664,7 @@ Future main() async { }); Future skiaPerfDestinationIntegrationTest() async { - final SkiaPerfDestination destination = SkiaPerfDestination( + final destination = SkiaPerfDestination( SkiaPerfGcsAdaptor(testBucket!), testLock, ); diff --git a/packages/metrics_center/test/utility.dart b/packages/metrics_center/test/utility.dart index 78f52d935268..321b57625689 100644 --- a/packages/metrics_center/test/utility.dart +++ b/packages/metrics_center/test/utility.dart @@ -14,7 +14,7 @@ void expectSetMatch(Iterable actual, Iterable expected) { // May return null if the credentials file doesn't exist. Map? getTestGcpCredentialsJson() { - final File f = File('secret/test_gcp_credentials.json'); + final f = File('secret/test_gcp_credentials.json'); if (!f.existsSync()) { return null; } diff --git a/packages/multicast_dns/CHANGELOG.md b/packages/multicast_dns/CHANGELOG.md index a5055cd9e8b6..ab44bf6b730f 100644 --- a/packages/multicast_dns/CHANGELOG.md +++ b/packages/multicast_dns/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. ## 0.3.3 diff --git a/packages/multicast_dns/example/main.dart b/packages/multicast_dns/example/main.dart index 360d5a3273b3..bb441d7495d6 100644 --- a/packages/multicast_dns/example/main.dart +++ b/packages/multicast_dns/example/main.dart @@ -12,8 +12,8 @@ import 'package:multicast_dns/multicast_dns.dart'; Future main() async { // Parse the command line arguments. - const String name = '_dartobservatory._tcp.local'; - final MDnsClient client = MDnsClient(); + const name = '_dartobservatory._tcp.local'; + final client = MDnsClient(); // Start the client with default options. await client.start(); diff --git a/packages/multicast_dns/example/mdns_resolve.dart b/packages/multicast_dns/example/mdns_resolve.dart index 97ef0d8c88b9..ed4301476c54 100644 --- a/packages/multicast_dns/example/mdns_resolve.dart +++ b/packages/multicast_dns/example/mdns_resolve.dart @@ -21,7 +21,7 @@ For example: final String name = args[0]; - final MDnsClient client = MDnsClient(); + final client = MDnsClient(); await client.start(); await for (final IPAddressResourceRecord record in client.lookup( diff --git a/packages/multicast_dns/example/mdns_sd.dart b/packages/multicast_dns/example/mdns_sd.dart index 4c4d5fea7a84..1d2f36230075 100644 --- a/packages/multicast_dns/example/mdns_sd.dart +++ b/packages/multicast_dns/example/mdns_sd.dart @@ -21,7 +21,7 @@ For example: final bool verbose = args.contains('--verbose') || args.contains('-v'); final String name = args.last; - final MDnsClient client = MDnsClient(); + final client = MDnsClient(); await client.start(); await for (final PtrResourceRecord ptr in client.lookup( diff --git a/packages/multicast_dns/lib/multicast_dns.dart b/packages/multicast_dns/lib/multicast_dns.dart index 0a0c7d740628..3b5b2b5fc8e0 100644 --- a/packages/multicast_dns/lib/multicast_dns.dart +++ b/packages/multicast_dns/lib/multicast_dns.dart @@ -143,7 +143,7 @@ class MDnsClient { listenAddress.type, )).toList(); - for (final NetworkInterface interface in interfaces) { + for (final interface in interfaces) { final InternetAddress targetAddress = interface.addresses[0]; // Ensure that we're using this address/interface for multicast. @@ -217,14 +217,14 @@ class MDnsClient { throw StateError('mDNS client must be started before calling lookup.'); } // Look for entries in the cache. - final List cached = []; + final cached = []; _cache.lookup( query.fullyQualifiedName, query.resourceRecordType, cached, ); if (cached.isNotEmpty) { - final StreamController controller = StreamController(); + final controller = StreamController(); cached.forEach(controller.add); controller.close(); return controller.stream; diff --git a/packages/multicast_dns/lib/src/lookup_resolver.dart b/packages/multicast_dns/lib/src/lookup_resolver.dart index 531be38f2b1d..bca9c16cbcbd 100644 --- a/packages/multicast_dns/lib/src/lookup_resolver.dart +++ b/packages/multicast_dns/lib/src/lookup_resolver.dart @@ -40,9 +40,9 @@ class LookupResolver { String name, Duration timeout, ) { - final StreamController controller = StreamController(); - final PendingRequest request = PendingRequest(type, name, controller); - final Timer timer = Timer(timeout, () { + final controller = StreamController(); + final request = PendingRequest(type, name, controller); + final timer = Timer(timeout, () { request.unlink(); controller.close(); }); @@ -54,7 +54,7 @@ class LookupResolver { /// Parses [ResoureRecord]s received and delivers them to the appropriate /// listener(s) added via [addPendingRequest]. void handleResponse(List response) { - for (final ResourceRecord r in response) { + for (final r in response) { final int type = r.resourceRecordType; String name = r.name.toLowerCase(); if (name.endsWith('.')) { diff --git a/packages/multicast_dns/lib/src/native_protocol_client.dart b/packages/multicast_dns/lib/src/native_protocol_client.dart index 4c07df865dfe..89ea986d33c0 100644 --- a/packages/multicast_dns/lib/src/native_protocol_client.dart +++ b/packages/multicast_dns/lib/src/native_protocol_client.dart @@ -25,7 +25,7 @@ class ResourceRecordCache { /// The number of entries in the cache. int get entryCount { - int count = 0; + var count = 0; for (final SplayTreeMap> map in _cache.values) { for (final List records in map.values) { @@ -40,8 +40,8 @@ class ResourceRecordCache { // TODO(karlklose): include flush bit in the record and only flush if // necessary. // Clear the cache for all name/type combinations to be updated. - final Map> seenRecordTypes = >{}; - for (final ResourceRecord record in records) { + final seenRecordTypes = >{}; + for (final record in records) { // TODO(dnfield): Update this to use set literal syntax when we're able to bump the SDK constraint. seenRecordTypes[record.resourceRecordType] ??= Set(); // ignore: prefer_collection_literals diff --git a/packages/multicast_dns/lib/src/packet.dart b/packages/multicast_dns/lib/src/packet.dart index 60e1b07fe5e4..a914370594f6 100644 --- a/packages/multicast_dns/lib/src/packet.dart +++ b/packages/multicast_dns/lib/src/packet.dart @@ -56,14 +56,14 @@ List encodeMDnsQuery( // Calculate the size of the packet. int size = _kHeaderSize; - for (int i = 0; i < rawNameParts.length; i++) { + for (var i = 0; i < rawNameParts.length; i++) { size += 1 + rawNameParts[i].length; } size += 1; // End with empty part size += 4; // Trailer (QTYPE and QCLASS). - final Uint8List data = Uint8List(size); - final ByteData packetByteData = ByteData.view(data.buffer); + final data = Uint8List(size); + final packetByteData = ByteData.view(data.buffer); // Query identifier - just use 0. packetByteData.setUint16(_kIdOffset, 0); // Flags - 0 for query. @@ -77,7 +77,7 @@ List encodeMDnsQuery( // Number of resource records - 0 for query. packetByteData.setUint16(_kArcountOffset, 0); int offset = _kHeaderSize; - for (int i = 0; i < rawNameParts.length; i++) { + for (var i = 0; i < rawNameParts.length; i++) { data[offset++] = rawNameParts[i].length; data.setRange(offset, offset + rawNameParts[i].length, rawNameParts[i]); offset += rawNameParts[i].length; @@ -119,7 +119,7 @@ String readFQDN(List packet, [int offset = 0]) { final Uint8List data = packet is Uint8List ? packet : Uint8List.fromList(packet); - final ByteData byteData = ByteData.view(data.buffer); + final byteData = ByteData.view(data.buffer); return _readFQDN(data, byteData, offset, data.length).fqdn; } @@ -140,11 +140,11 @@ _FQDNReadResult _readFQDN( } } - final List parts = []; - final int prevOffset = offset; - final List offsetsToVisit = [offset]; - int upperLimitOffset = offset; - int highestOffsetRead = offset; + final parts = []; + final prevOffset = offset; + final offsetsToVisit = [offset]; + var upperLimitOffset = offset; + var highestOffsetRead = offset; while (offsetsToVisit.isNotEmpty) { offset = offsetsToVisit.removeLast(); @@ -175,11 +175,7 @@ _FQDNReadResult _readFQDN( offset++; if (partLength > 0) { checkLength(offset + partLength); - final Uint8List partBytes = Uint8List.view( - data.buffer, - offset, - partLength, - ); + final partBytes = Uint8List.view(data.buffer, offset, partLength); offset += partLength; // According to the RFC, this is supposed to be utf-8 encoded, but // we should continue decoding even if it isn't to avoid dropping the @@ -210,7 +206,7 @@ List? decodeMDnsResponse(List packet) { final Uint8List data = packet is Uint8List ? packet : Uint8List.fromList(packet); - final ByteData packetBytes = ByteData.view(data.buffer); + final packetBytes = ByteData.view(data.buffer); final int answerCount = packetBytes.getUint16(_kAncountOffset); final int authorityCount = packetBytes.getUint16(_kNscountOffset); @@ -261,7 +257,7 @@ List? decodeMDnsResponse(List packet) { switch (type) { case ResourceRecordType.addressIPv4: checkLength(offset + readDataLength); - final StringBuffer addr = StringBuffer(); + final addr = StringBuffer(); final int stop = offset + readDataLength; addr.write(packetBytes.getUint8(offset)); offset++; @@ -276,7 +272,7 @@ List? decodeMDnsResponse(List packet) { ); case ResourceRecordType.addressIPv6: checkLength(offset + readDataLength); - final StringBuffer addr = StringBuffer(); + final addr = StringBuffer(); final int stop = offset + readDataLength; addr.write(packetBytes.getUint16(offset).toRadixString(16)); offset += 2; @@ -329,8 +325,8 @@ List? decodeMDnsResponse(List packet) { // The first byte of the buffer is the length of the first string of // the TXT record. Further length-prefixed strings may follow. We // concatenate them with newlines. - final StringBuffer strings = StringBuffer(); - int index = 0; + final strings = StringBuffer(); + var index = 0; while (index < readDataLength) { final int txtLength = data[offset + index]; index++; @@ -356,10 +352,10 @@ List? decodeMDnsResponse(List packet) { // This list can't be fixed length right now because we might get // resource record types we don't support, and consumers expect this list // to not have null entries. - final List result = []; + final result = []; try { - for (int i = 0; i < questionCount; i++) { + for (var i = 0; i < questionCount; i++) { final _FQDNReadResult result = _readFQDN( data, packetBytes, @@ -370,7 +366,7 @@ List? decodeMDnsResponse(List packet) { checkLength(offset + 4); offset += 4; } - for (int i = 0; i < remainingCount; i++) { + for (var i = 0; i < remainingCount; i++) { final ResourceRecord? record = readResourceRecord(); if (record != null) { result.add(record); diff --git a/packages/multicast_dns/lib/src/resource_record.dart b/packages/multicast_dns/lib/src/resource_record.dart index bb2cc9c23d67..f16d9a163dcd 100644 --- a/packages/multicast_dns/lib/src/resource_record.dart +++ b/packages/multicast_dns/lib/src/resource_record.dart @@ -310,8 +310,8 @@ class SrvResourceRecord extends ResourceRecord { @override Uint8List encodeResponseRecord() { final List data = utf8.encode(target); - final Uint8List result = Uint8List(data.length + 7); - final ByteData resultData = ByteData.view(result.buffer); + final result = Uint8List(data.length + 7); + final resultData = ByteData.view(result.buffer); resultData.setUint16(0, priority); resultData.setUint16(2, weight); resultData.setUint16(4, port); diff --git a/packages/multicast_dns/pubspec.yaml b/packages/multicast_dns/pubspec.yaml index b8921c684344..ebd2ed2c79ae 100644 --- a/packages/multicast_dns/pubspec.yaml +++ b/packages/multicast_dns/pubspec.yaml @@ -5,7 +5,7 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.3.3 environment: - sdk: ^3.8.0 + sdk: ^3.9.0 dependencies: meta: ^1.3.0 diff --git a/packages/multicast_dns/test/client_test.dart b/packages/multicast_dns/test/client_test.dart index 79483e5ef717..89bb64783a50 100644 --- a/packages/multicast_dns/test/client_test.dart +++ b/packages/multicast_dns/test/client_test.dart @@ -12,8 +12,8 @@ import 'package:test/test.dart'; void main() { test('Can inject datagram socket factory and configure mdns port', () async { late int lastPort; - final FakeRawDatagramSocket datagramSocket = FakeRawDatagramSocket(); - final MDnsClient client = MDnsClient( + final datagramSocket = FakeRawDatagramSocket(); + final client = MDnsClient( rawDatagramSocketFactory: ( dynamic host, @@ -37,8 +37,8 @@ void main() { }); test('Closes IPv4 sockets', () async { - final FakeRawDatagramSocket datagramSocket = FakeRawDatagramSocket(); - final MDnsClient client = MDnsClient( + final datagramSocket = FakeRawDatagramSocket(); + final client = MDnsClient( rawDatagramSocketFactory: ( dynamic host, @@ -62,9 +62,9 @@ void main() { }); test('Closes IPv6 sockets', () async { - final FakeRawDatagramSocket datagramSocket = FakeRawDatagramSocket(); + final datagramSocket = FakeRawDatagramSocket(); datagramSocket.address = InternetAddress.anyIPv6; - final MDnsClient client = MDnsClient( + final client = MDnsClient( rawDatagramSocketFactory: ( dynamic host, @@ -88,9 +88,9 @@ void main() { }); test('start() is idempotent', () async { - final FakeRawDatagramSocket datagramSocket = FakeRawDatagramSocket(); + final datagramSocket = FakeRawDatagramSocket(); datagramSocket.address = InternetAddress.anyIPv4; - final MDnsClient client = MDnsClient( + final client = MDnsClient( rawDatagramSocketFactory: ( dynamic host, @@ -112,7 +112,7 @@ void main() { }); group('Bind a single socket to ANY IPv4 and more than one when IPv6', () { - final List> testCases = >[ + final testCases = >[ { 'name': 'IPv4', 'datagramSocketType': InternetAddress.anyIPv4, @@ -125,15 +125,15 @@ void main() { }, ]; - for (final Map testCase in testCases) { + for (final testCase in testCases) { test('Bind a single socket to ANY ${testCase["name"]}', () async { - final FakeRawDatagramSocket datagramSocket = FakeRawDatagramSocket(); + final datagramSocket = FakeRawDatagramSocket(); datagramSocket.address = testCase['datagramSocketType']! as InternetAddress; - final List selectedInterfacesForSendingPackets = []; - final MDnsClient client = MDnsClient( + final selectedInterfacesForSendingPackets = []; + final client = MDnsClient( rawDatagramSocketFactory: ( dynamic host, @@ -147,14 +147,14 @@ void main() { }, ); - const int numberOfFakeInterfaces = 10; + const numberOfFakeInterfaces = 10; Future> fakeNetworkInterfacesFactory( InternetAddressType type, ) async { - final List fakeInterfaces = []; + final fakeInterfaces = []; // Generate "fake" interfaces - for (int i = 0; i < numberOfFakeInterfaces; i++) { + for (var i = 0; i < numberOfFakeInterfaces; i++) { fakeInterfaces.add( FakeNetworkInterface('inetfake$i', [ InternetAddress("${testCase['interfacePrefix']! as String}$i"), @@ -166,7 +166,7 @@ void main() { return Future.value(fakeInterfaces); } - final InternetAddress listenAddress = + final listenAddress = testCase['datagramSocketType']! as InternetAddress; await client.start( @@ -191,9 +191,8 @@ void main() { }); test('Calls onError callback in case of socket error', () async { - final FakeRawDatagramSocketThatSendsError datagramSocket = - FakeRawDatagramSocketThatSendsError(); - final MDnsClient client = MDnsClient( + final datagramSocket = FakeRawDatagramSocketThatSendsError(); + final client = MDnsClient( rawDatagramSocketFactory: ( dynamic host, @@ -206,7 +205,7 @@ void main() { }, ); - final Completer onErrorCalledCompleter = Completer(); + final onErrorCalledCompleter = Completer(); await client.start( mDnsPort: 1234, interfacesFactory: (InternetAddressType type) async => diff --git a/packages/multicast_dns/test/decode_test.dart b/packages/multicast_dns/test/decode_test.dart index acadeed165db..b4712c881cc8 100644 --- a/packages/multicast_dns/test/decode_test.dart +++ b/packages/multicast_dns/test/decode_test.dart @@ -24,7 +24,7 @@ void testValidPackages() { List result = decodeMDnsResponse(package1)!; expect(result, isNotNull); expect(result.length, 1); - IPAddressResourceRecord ipResult = result[0] as IPAddressResourceRecord; + var ipResult = result[0] as IPAddressResourceRecord; expect(ipResult.name, 'raspberrypi.local'); expect(ipResult.address.address, '192.168.1.191'); @@ -193,8 +193,8 @@ void testValidPackages() { void testBadPackages() { test('Returns null for invalid packets', () { - for (final List p in >[package1, package2, package3]) { - for (int i = 0; i < p.length; i++) { + for (final p in >[package1, package2, package3]) { + for (var i = 0; i < p.length; i++) { expect(decodeMDnsResponse(p.sublist(0, i)), isNull); } } @@ -226,7 +226,7 @@ void testNonUtf8DomainName() { final List result = decodeMDnsResponse(nonUtf8Package)!; expect(result, isNotNull); expect(result[0] is TxtResourceRecord, isTrue); - final TxtResourceRecord txt = result[0] as TxtResourceRecord; + final txt = result[0] as TxtResourceRecord; expect(txt.name, contains('�')); }); } diff --git a/packages/multicast_dns/test/lookup_resolver_test.dart b/packages/multicast_dns/test/lookup_resolver_test.dart index dde83f9f8d8a..f67549b8bc09 100644 --- a/packages/multicast_dns/test/lookup_resolver_test.dart +++ b/packages/multicast_dns/test/lookup_resolver_test.dart @@ -22,8 +22,8 @@ ResourceRecord ip4Result(String name, InternetAddress address) { void testTimeout() { test('Resolver does not return with short timeout', () async { - const Duration shortTimeout = Duration(milliseconds: 1); - final LookupResolver resolver = LookupResolver(); + const shortTimeout = Duration(milliseconds: 1); + final resolver = LookupResolver(); final Stream result = resolver.addPendingRequest( ResourceRecordType.addressIPv4, 'xxx', @@ -36,8 +36,8 @@ void testTimeout() { // One pending request and one response. void testResult() { test('One pending request and one response', () async { - const Duration noTimeout = Duration(days: 1); - final LookupResolver resolver = LookupResolver(); + const noTimeout = Duration(days: 1); + final resolver = LookupResolver(); final Stream futureResult = resolver.addPendingRequest( ResourceRecordType.addressIPv4, 'xxx.local', @@ -48,8 +48,7 @@ void testResult() { InternetAddress('1.2.3.4'), ); resolver.handleResponse([response]); - final IPAddressResourceRecord result = - await futureResult.first as IPAddressResourceRecord; + final result = await futureResult.first as IPAddressResourceRecord; expect('1.2.3.4', result.address.address); resolver.clearPendingRequests(); }); @@ -57,8 +56,8 @@ void testResult() { void testResult2() { test('Two requests', () async { - const Duration noTimeout = Duration(days: 1); - final LookupResolver resolver = LookupResolver(); + const noTimeout = Duration(days: 1); + final resolver = LookupResolver(); final Stream futureResult1 = resolver.addPendingRequest( ResourceRecordType.addressIPv4, 'xxx.local', @@ -78,10 +77,8 @@ void testResult2() { InternetAddress('2.3.4.5'), ); resolver.handleResponse([response2, response1]); - final IPAddressResourceRecord result1 = - await futureResult1.first as IPAddressResourceRecord; - final IPAddressResourceRecord result2 = - await futureResult2.first as IPAddressResourceRecord; + final result1 = await futureResult1.first as IPAddressResourceRecord; + final result2 = await futureResult2.first as IPAddressResourceRecord; expect('1.2.3.4', result1.address.address); expect('2.3.4.5', result2.address.address); resolver.clearPendingRequests(); @@ -90,8 +87,8 @@ void testResult2() { void testResult3() { test('Multiple requests', () async { - const Duration noTimeout = Duration(days: 1); - final LookupResolver resolver = LookupResolver(); + const noTimeout = Duration(days: 1); + final resolver = LookupResolver(); final ResourceRecord response0 = ip4Result( 'zzz.local', InternetAddress('2.3.4.5'), @@ -121,10 +118,8 @@ void testResult3() { resolver.handleResponse([response0]); resolver.handleResponse([response2, response1]); resolver.handleResponse([response0]); - final IPAddressResourceRecord result1 = - await futureResult1.first as IPAddressResourceRecord; - final IPAddressResourceRecord result2 = - await futureResult2.first as IPAddressResourceRecord; + final result1 = await futureResult1.first as IPAddressResourceRecord; + final result2 = await futureResult2.first as IPAddressResourceRecord; expect('1.2.3.4', result1.address.address); expect('2.3.4.5', result2.address.address); resolver.clearPendingRequests(); diff --git a/packages/multicast_dns/test/resource_record_cache_test.dart b/packages/multicast_dns/test/resource_record_cache_test.dart index 703211eea493..9ecb88d1eabb 100644 --- a/packages/multicast_dns/test/resource_record_cache_test.dart +++ b/packages/multicast_dns/test/resource_record_cache_test.dart @@ -20,11 +20,11 @@ void main() { void testOverwrite() { test('Cache can overwrite entries', () { - final InternetAddress ip1 = InternetAddress('192.168.1.1'); - final InternetAddress ip2 = InternetAddress('192.168.1.2'); + final ip1 = InternetAddress('192.168.1.1'); + final ip2 = InternetAddress('192.168.1.2'); final int valid = DateTime.now().millisecondsSinceEpoch + 86400 * 1000; - final ResourceRecordCache cache = ResourceRecordCache(); + final cache = ResourceRecordCache(); // Add two different records. cache.updateRecords([ @@ -58,11 +58,11 @@ void testOverwrite() { void testTimeout() { test('Cache can evict records after timeout', () { - final InternetAddress ip1 = InternetAddress('192.168.1.1'); + final ip1 = InternetAddress('192.168.1.1'); final int valid = DateTime.now().millisecondsSinceEpoch + 86400 * 1000; final int notValid = DateTime.now().millisecondsSinceEpoch - 1; - final ResourceRecordCache cache = ResourceRecordCache(); + final cache = ResourceRecordCache(); cache.updateRecords([ IPAddressResourceRecord('hest', valid, address: ip1), @@ -73,7 +73,7 @@ void testTimeout() { IPAddressResourceRecord('fisk', notValid, address: ip1), ]); - List results = []; + var results = []; cache.lookup('hest', ResourceRecordType.addressIPv4, results); expect(results.isEmpty, isFalse); diff --git a/packages/multicast_dns/tool/packet_gen.dart b/packages/multicast_dns/tool/packet_gen.dart index de4e5b635bd8..d3df26c9fad1 100644 --- a/packages/multicast_dns/tool/packet_gen.dart +++ b/packages/multicast_dns/tool/packet_gen.dart @@ -9,8 +9,8 @@ import 'dart:io'; void formatHexStream(String hexStream) { - String s = ''; - for (int i = 0; i < hexStream.length / 2; i++) { + var s = ''; + for (var i = 0; i < hexStream.length / 2; i++) { if (s.isNotEmpty) { s += ', '; } @@ -30,8 +30,8 @@ void formatHexStream(String hexStream) { // Support code for generating the hex-lists in test/decode_test.dart. void hexDumpList(List package) { - String s = ''; - for (int i = 0; i < package.length; i++) { + var s = ''; + for (var i = 0; i < package.length; i++) { if (s.isNotEmpty) { s += ', '; } @@ -54,8 +54,8 @@ void hexDumpList(List package) { void dumpDatagram(Datagram datagram) { String toHex(List ints) { - final StringBuffer buffer = StringBuffer(); - for (int i = 0; i < ints.length; i++) { + final buffer = StringBuffer(); + for (var i = 0; i < ints.length; i++) { buffer.write(ints[i].toRadixString(16).padLeft(2, '0')); if ((i + 1) % 10 == 0) { buffer.writeln(); diff --git a/packages/path_provider/path_provider/CHANGELOG.md b/packages/path_provider/path_provider/CHANGELOG.md index 0d2390c0f16c..794cb7bb98c0 100644 --- a/packages/path_provider/path_provider/CHANGELOG.md +++ b/packages/path_provider/path_provider/CHANGELOG.md @@ -1,7 +1,10 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. -* Updates README to indicate that Andoid SDK <21 is no longer supported. +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. +* Updates README to reflect currently supported OS versions for the latest + versions of the endorsed platform implementations. + * Applications built with older versions of Flutter will continue to + use compatible versions of the platform implementations. ## 2.1.5 diff --git a/packages/path_provider/path_provider/README.md b/packages/path_provider/path_provider/README.md index 8390d5d99689..c9f39b35151f 100644 --- a/packages/path_provider/path_provider/README.md +++ b/packages/path_provider/path_provider/README.md @@ -9,7 +9,7 @@ Not all methods are supported on all platforms. | | Android | iOS | Linux | macOS | Windows | |-------------|---------|-------|-------|--------|-------------| -| **Support** | SDK 21+ | 12.0+ | Any | 10.14+ | Windows 10+ | +| **Support** | SDK 24+ | 13.0+ | Any | 10.15+ | Windows 10+ | ## Example diff --git a/packages/path_provider/path_provider/example/android/app/gradle/wrapper/gradle-wrapper.properties b/packages/path_provider/path_provider/example/android/app/gradle/wrapper/gradle-wrapper.properties index 0c68fbc1dadd..8dedf4fef55c 100644 --- a/packages/path_provider/path_provider/example/android/app/gradle/wrapper/gradle-wrapper.properties +++ b/packages/path_provider/path_provider/example/android/app/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-all.zip +networkTimeout=10000 zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists - diff --git a/packages/path_provider/path_provider/example/android/settings.gradle b/packages/path_provider/path_provider/example/android/settings.gradle index 96fce46479f8..b542cca3f52e 100644 --- a/packages/path_provider/path_provider/example/android/settings.gradle +++ b/packages/path_provider/path_provider/example/android/settings.gradle @@ -19,8 +19,8 @@ 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.11.0" apply false - id "org.jetbrains.kotlin.android" version "2.2.0" apply false + id "com.android.application" version "8.11.1" apply false + id "org.jetbrains.kotlin.android" version "2.2.20" apply false id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1" } diff --git a/packages/path_provider/path_provider/example/integration_test/path_provider_test.dart b/packages/path_provider/path_provider/example/integration_test/path_provider_test.dart index 41606be831da..69647b68dce6 100644 --- a/packages/path_provider/path_provider/example/integration_test/path_provider_test.dart +++ b/packages/path_provider/path_provider/example/integration_test/path_provider_test.dart @@ -71,7 +71,7 @@ void main() { } }); - final List allDirs = [ + final allDirs = [ null, StorageDirectory.music, StorageDirectory.podcasts, @@ -82,7 +82,7 @@ void main() { StorageDirectory.movies, ]; - for (final StorageDirectory? type in allDirs) { + for (final type in allDirs) { testWidgets('getExternalStorageDirectories (type: $type)', ( WidgetTester tester, ) async { @@ -117,7 +117,7 @@ void _verifySampleFile(Directory? directory, String name) { if (directory == null) { return; } - final File file = File('${directory.path}/$name'); + final file = File('${directory.path}/$name'); if (file.existsSync()) { file.deleteSync(); diff --git a/packages/path_provider/path_provider/example/ios/Flutter/AppFrameworkInfo.plist b/packages/path_provider/path_provider/example/ios/Flutter/AppFrameworkInfo.plist index 7c5696400627..391a902b2beb 100644 --- a/packages/path_provider/path_provider/example/ios/Flutter/AppFrameworkInfo.plist +++ b/packages/path_provider/path_provider/example/ios/Flutter/AppFrameworkInfo.plist @@ -20,7 +20,5 @@ ???? CFBundleVersion 1.0 - MinimumOSVersion - 12.0 diff --git a/packages/path_provider/path_provider/example/ios/Flutter/Debug.xcconfig b/packages/path_provider/path_provider/example/ios/Flutter/Debug.xcconfig index ec97fc6f3021..592ceee85b89 100644 --- a/packages/path_provider/path_provider/example/ios/Flutter/Debug.xcconfig +++ b/packages/path_provider/path_provider/example/ios/Flutter/Debug.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" diff --git a/packages/path_provider/path_provider/example/ios/Flutter/Release.xcconfig b/packages/path_provider/path_provider/example/ios/Flutter/Release.xcconfig index c4855bfe2000..592ceee85b89 100644 --- a/packages/path_provider/path_provider/example/ios/Flutter/Release.xcconfig +++ b/packages/path_provider/path_provider/example/ios/Flutter/Release.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" diff --git a/packages/path_provider/path_provider/example/ios/Podfile b/packages/path_provider/path_provider/example/ios/Podfile deleted file mode 100644 index 01d4aa611bb9..000000000000 --- a/packages/path_provider/path_provider/example/ios/Podfile +++ /dev/null @@ -1,40 +0,0 @@ -# Uncomment this line to define a global platform for your project -# platform :ios, '12.0' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_ios_podfile_setup - -target 'Runner' do - use_frameworks! - - flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_ios_build_settings(target) - end -end diff --git a/packages/path_provider/path_provider/example/ios/Runner.xcodeproj/project.pbxproj b/packages/path_provider/path_provider/example/ios/Runner.xcodeproj/project.pbxproj index 9eb874c6b403..c8adcc5d0bd6 100644 --- a/packages/path_provider/path_provider/example/ios/Runner.xcodeproj/project.pbxproj +++ b/packages/path_provider/path_provider/example/ios/Runner.xcodeproj/project.pbxproj @@ -8,7 +8,6 @@ /* Begin PBXBuildFile section */ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; - 2845184EEBEC52AD12645832 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 84D692C93D5ECEF65168BA36 /* Pods_Runner.framework */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; @@ -34,11 +33,10 @@ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; - 4D8A276405BF24CBEA3E388B /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; - 84D692C93D5ECEF65168BA36 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 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; }; @@ -46,8 +44,6 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - B5B0C67825A38CB73A4D9199 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; - B9B73C13AA4BD5419AD293F4 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -56,35 +52,16 @@ buildActionMask = 2147483647; files = ( 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, - 2845184EEBEC52AD12645832 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 668ACDABF0807F1341F739B9 /* Frameworks */ = { - isa = PBXGroup; - children = ( - 84D692C93D5ECEF65168BA36 /* Pods_Runner.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; - 6EF92B34008B02D2326BC11D /* Pods */ = { - isa = PBXGroup; - children = ( - B5B0C67825A38CB73A4D9199 /* Pods-Runner.debug.xcconfig */, - 4D8A276405BF24CBEA3E388B /* Pods-Runner.release.xcconfig */, - B9B73C13AA4BD5419AD293F4 /* Pods-Runner.profile.xcconfig */, - ); - name = Pods; - path = Pods; - sourceTree = ""; - }; 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, 9740EEB21CF90195004384FC /* Debug.xcconfig */, 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, @@ -99,8 +76,6 @@ 9740EEB11CF90186004384FC /* Flutter */, 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, - 6EF92B34008B02D2326BC11D /* Pods */, - 668ACDABF0807F1341F739B9 /* Frameworks */, ); sourceTree = ""; }; @@ -134,7 +109,6 @@ isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - AA83EFBF6960B64E1E1E6EEA /* [CP] Check Pods Manifest.lock */, 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, @@ -237,28 +211,6 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; }; - AA83EFBF6960B64E1E1E6EEA /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -336,7 +288,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -415,7 +367,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -466,7 +418,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; diff --git a/packages/path_provider/path_provider/example/lib/main.dart b/packages/path_provider/path_provider/example/lib/main.dart index e60a40e944c0..a3aeb6cc6575 100644 --- a/packages/path_provider/path_provider/example/lib/main.dart +++ b/packages/path_provider/path_provider/example/lib/main.dart @@ -55,7 +55,7 @@ class _MyHomePageState extends State { BuildContext context, AsyncSnapshot snapshot, ) { - Text text = const Text(''); + var text = const Text(''); if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasError) { text = Text('Error: ${snapshot.error}'); @@ -72,7 +72,7 @@ class _MyHomePageState extends State { BuildContext context, AsyncSnapshot?> snapshot, ) { - Text text = const Text(''); + var text = const Text(''); if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasError) { text = Text('Error: ${snapshot.error}'); diff --git a/packages/path_provider/path_provider/example/macos/Flutter/Flutter-Debug.xcconfig b/packages/path_provider/path_provider/example/macos/Flutter/Flutter-Debug.xcconfig index 785633d3a86b..c2efd0b608ba 100644 --- a/packages/path_provider/path_provider/example/macos/Flutter/Flutter-Debug.xcconfig +++ b/packages/path_provider/path_provider/example/macos/Flutter/Flutter-Debug.xcconfig @@ -1,2 +1 @@ -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" diff --git a/packages/path_provider/path_provider/example/macos/Flutter/Flutter-Release.xcconfig b/packages/path_provider/path_provider/example/macos/Flutter/Flutter-Release.xcconfig index 5fba960c3af2..c2efd0b608ba 100644 --- a/packages/path_provider/path_provider/example/macos/Flutter/Flutter-Release.xcconfig +++ b/packages/path_provider/path_provider/example/macos/Flutter/Flutter-Release.xcconfig @@ -1,2 +1 @@ -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" diff --git a/packages/path_provider/path_provider/example/macos/Podfile b/packages/path_provider/path_provider/example/macos/Podfile deleted file mode 100644 index ae77cc1d4269..000000000000 --- a/packages/path_provider/path_provider/example/macos/Podfile +++ /dev/null @@ -1,39 +0,0 @@ -platform :osx, '10.14' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\"" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_macos_podfile_setup - -target 'Runner' do - use_frameworks! - - flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__)) -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_macos_build_settings(target) - end -end diff --git a/packages/path_provider/path_provider/example/macos/Runner.xcodeproj/project.pbxproj b/packages/path_provider/path_provider/example/macos/Runner.xcodeproj/project.pbxproj index 6758fe7160aa..6e7dcd34b70c 100644 --- a/packages/path_provider/path_provider/example/macos/Runner.xcodeproj/project.pbxproj +++ b/packages/path_provider/path_provider/example/macos/Runner.xcodeproj/project.pbxproj @@ -21,7 +21,6 @@ /* End PBXAggregateTarget section */ /* Begin PBXBuildFile section */ - 23F6FAA3AF82DFCF2B7DD79A /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1523F64D34B952AB303BFFA8 /* Pods_Runner.framework */; }; 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; @@ -54,8 +53,6 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 0A1A53CF00FD04D6ED0A8E4A /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; - 1523F64D34B952AB303BFFA8 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; 33CC10ED2044A3C60003C045 /* path_provider_example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = path_provider_example.app; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -70,10 +67,9 @@ 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; - 46139048DB9F59D473B61B5E /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; - F4586DA69948E3A954A2FC9C /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -82,24 +78,12 @@ buildActionMask = 2147483647; files = ( 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, - 23F6FAA3AF82DFCF2B7DD79A /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 30697CBF35C100C7DD4B4699 /* Pods */ = { - isa = PBXGroup; - children = ( - 46139048DB9F59D473B61B5E /* Pods-Runner.debug.xcconfig */, - F4586DA69948E3A954A2FC9C /* Pods-Runner.release.xcconfig */, - 0A1A53CF00FD04D6ED0A8E4A /* Pods-Runner.profile.xcconfig */, - ); - name = Pods; - path = Pods; - sourceTree = ""; - }; 33BA886A226E78AF003329D5 /* Configs */ = { isa = PBXGroup; children = ( @@ -117,8 +101,6 @@ 33FAB671232836740065AC1E /* Runner */, 33CEB47122A05771004F2AC0 /* Flutter */, 33CC10EE2044A3C60003C045 /* Products */, - D73912EC22F37F3D000D13A0 /* Frameworks */, - 30697CBF35C100C7DD4B4699 /* Pods */, ); sourceTree = ""; }; @@ -144,6 +126,7 @@ 33CEB47122A05771004F2AC0 /* Flutter */ = { isa = PBXGroup; children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, @@ -165,14 +148,6 @@ path = Runner; sourceTree = ""; }; - D73912EC22F37F3D000D13A0 /* Frameworks */ = { - isa = PBXGroup; - children = ( - 1523F64D34B952AB303BFFA8 /* Pods_Runner.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -180,7 +155,6 @@ isa = PBXNativeTarget; buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - 82C3ED26F2C350499338A54B /* [CP] Check Pods Manifest.lock */, 33CC10E92044A3C60003C045 /* Sources */, 33CC10EA2044A3C60003C045 /* Frameworks */, 33CC10EB2044A3C60003C045 /* Resources */, @@ -299,28 +273,6 @@ shellPath = /bin/sh; shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh\ntouch Flutter/ephemeral/tripwire\n"; }; - 82C3ED26F2C350499338A54B /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -395,7 +347,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; + MACOSX_DEPLOYMENT_TARGET = 10.15; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; @@ -478,7 +430,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; + MACOSX_DEPLOYMENT_TARGET = 10.15; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = macosx; @@ -525,7 +477,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; + MACOSX_DEPLOYMENT_TARGET = 10.15; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; diff --git a/packages/path_provider/path_provider/example/pubspec.yaml b/packages/path_provider/path_provider/example/pubspec.yaml index 25663b182d02..20fe32e15065 100644 --- a/packages/path_provider/path_provider/example/pubspec.yaml +++ b/packages/path_provider/path_provider/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the path_provider plugin. publish_to: none environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" dependencies: flutter: diff --git a/packages/path_provider/path_provider/lib/path_provider.dart b/packages/path_provider/path_provider/lib/path_provider.dart index 9ccad357ae5a..d855c260889e 100644 --- a/packages/path_provider/path_provider/lib/path_provider.dart +++ b/packages/path_provider/path_provider/lib/path_provider.dart @@ -30,7 +30,7 @@ class MissingPlatformDirectoryException implements Exception { @override String toString() { - final String detailsAddition = details == null ? '' : ': $details'; + final detailsAddition = details == null ? '' : ': $details'; return 'MissingPlatformDirectoryException($message)$detailsAddition'; } } diff --git a/packages/path_provider/path_provider/pubspec.yaml b/packages/path_provider/path_provider/pubspec.yaml index e90dc9f826ed..64c830244573 100644 --- a/packages/path_provider/path_provider/pubspec.yaml +++ b/packages/path_provider/path_provider/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.1.5 environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" flutter: plugin: diff --git a/packages/path_provider/path_provider_android/CHANGELOG.md b/packages/path_provider/path_provider_android/CHANGELOG.md index 76f560327b59..106b35fa0676 100644 --- a/packages/path_provider/path_provider_android/CHANGELOG.md +++ b/packages/path_provider/path_provider_android/CHANGELOG.md @@ -1,3 +1,7 @@ +## 2.2.23 + +* Updates build files from Groovy to Kotlin. + ## 2.2.22 * Bumps com.android.tools.build:gradle from 8.12.1 to 8.13.1. diff --git a/packages/path_provider/path_provider_android/android/build.gradle b/packages/path_provider/path_provider_android/android/build.gradle deleted file mode 100644 index ecbcabc613aa..000000000000 --- a/packages/path_provider/path_provider_android/android/build.gradle +++ /dev/null @@ -1,59 +0,0 @@ -group = 'io.flutter.plugins.pathprovider' -version = '1.0-SNAPSHOT' - -buildscript { - repositories { - google() - mavenCentral() - } - - dependencies { - classpath 'com.android.tools.build:gradle:8.13.1' - } -} - -rootProject.allprojects { - repositories { - google() - mavenCentral() - } -} - -apply plugin: 'com.android.library' - -android { - namespace = "io.flutter.plugins.pathprovider" - compileSdk = flutter.compileSdkVersion - - defaultConfig { - minSdkVersion 21 - testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - } - lintOptions { - checkAllWarnings = true - warningsAsErrors = true - disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency', 'NewerVersionAvailable' - } - compileOptions { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 - } - - - testOptions { - unitTests.includeAndroidResources = true - unitTests.returnDefaultValues = true - unitTests.all { - testLogging { - events "passed", "skipped", "failed", "standardOut", "standardError" - outputs.upToDateWhen {false} - showStandardStreams = true - } - } - } -} - -dependencies { - implementation("androidx.annotation:annotation:1.9.1") - testImplementation("junit:junit:4.13.2") -} diff --git a/packages/path_provider/path_provider_android/android/build.gradle.kts b/packages/path_provider/path_provider_android/android/build.gradle.kts new file mode 100644 index 000000000000..3114e6c6385e --- /dev/null +++ b/packages/path_provider/path_provider_android/android/build.gradle.kts @@ -0,0 +1,64 @@ +group = "io.flutter.plugins.pathprovider" +version = "1.0-SNAPSHOT" + +buildscript { + repositories { + google() + mavenCentral() + } + + dependencies { + classpath("com.android.tools.build:gradle:8.13.1") + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +plugins { + id("com.android.library") +} + +android { + namespace = "io.flutter.plugins.pathprovider" + compileSdk = flutter.compileSdkVersion + + defaultConfig { + minSdk = 24 + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + lint { + checkAllWarnings = true + warningsAsErrors = true + disable.addAll(setOf("AndroidGradlePluginVersion", "InvalidPackage", "GradleDependency", "NewerVersionAvailable")) + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + testOptions { + unitTests { + isIncludeAndroidResources = true + isReturnDefaultValues = true + all { + it.outputs.upToDateWhen { false } + it.testLogging { + events("passed", "skipped", "failed", "standardOut", "standardError") + showStandardStreams = true + } + } + } + } +} + +dependencies { + implementation("androidx.annotation:annotation:1.9.1") + testImplementation("junit:junit:4.13.2") +} diff --git a/packages/path_provider/path_provider_android/android/settings.gradle b/packages/path_provider/path_provider_android/android/settings.gradle deleted file mode 100644 index 359a57ff9540..000000000000 --- a/packages/path_provider/path_provider_android/android/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'path_provider_android' diff --git a/packages/path_provider/path_provider_android/android/settings.gradle.kts b/packages/path_provider/path_provider_android/android/settings.gradle.kts new file mode 100644 index 000000000000..4fc5bb16d8aa --- /dev/null +++ b/packages/path_provider/path_provider_android/android/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "path_provider_android" diff --git a/packages/path_provider/path_provider_android/example/android/app/gradle/wrapper/gradle-wrapper.properties b/packages/path_provider/path_provider_android/example/android/app/gradle/wrapper/gradle-wrapper.properties index 0c68fbc1dadd..8dedf4fef55c 100644 --- a/packages/path_provider/path_provider_android/example/android/app/gradle/wrapper/gradle-wrapper.properties +++ b/packages/path_provider/path_provider_android/example/android/app/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.0-all.zip +networkTimeout=10000 zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists - 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 96fce46479f8..b542cca3f52e 100644 --- a/packages/path_provider/path_provider_android/example/android/settings.gradle +++ b/packages/path_provider/path_provider_android/example/android/settings.gradle @@ -19,8 +19,8 @@ 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.11.0" apply false - id "org.jetbrains.kotlin.android" version "2.2.0" apply false + id "com.android.application" version "8.11.1" apply false + id "org.jetbrains.kotlin.android" version "2.2.20" apply false id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1" } diff --git a/packages/path_provider/path_provider_android/example/integration_test/path_provider_test.dart b/packages/path_provider/path_provider_android/example/integration_test/path_provider_test.dart index af788344facb..ab6b1b76eaf7 100644 --- a/packages/path_provider/path_provider_android/example/integration_test/path_provider_test.dart +++ b/packages/path_provider/path_provider_android/example/integration_test/path_provider_test.dart @@ -57,7 +57,7 @@ void main() { } }); - final List allDirs = [ + final allDirs = [ null, StorageDirectory.music, StorageDirectory.podcasts, @@ -68,7 +68,7 @@ void main() { StorageDirectory.movies, ]; - for (final StorageDirectory? type in allDirs) { + for (final type in allDirs) { testWidgets('getExternalStorageDirectories (type: $type)', ( WidgetTester tester, ) async { @@ -93,8 +93,8 @@ void _verifySampleFile(String? directoryPath, String name) { if (directoryPath == null) { return; } - final Directory directory = Directory(directoryPath); - final File file = File('${directory.path}${Platform.pathSeparator}$name'); + final directory = Directory(directoryPath); + final file = File('${directory.path}${Platform.pathSeparator}$name'); if (file.existsSync()) { file.deleteSync(); diff --git a/packages/path_provider/path_provider_android/example/lib/main.dart b/packages/path_provider/path_provider_android/example/lib/main.dart index 546d3f125f2e..1bec8806abbc 100644 --- a/packages/path_provider/path_provider_android/example/lib/main.dart +++ b/packages/path_provider/path_provider_android/example/lib/main.dart @@ -53,7 +53,7 @@ class _MyHomePageState extends State { BuildContext context, AsyncSnapshot snapshot, ) { - Text text = const Text(''); + var text = const Text(''); if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasError) { text = Text('Error: ${snapshot.error}'); @@ -70,7 +70,7 @@ class _MyHomePageState extends State { BuildContext context, AsyncSnapshot?> snapshot, ) { - Text text = const Text(''); + var text = const Text(''); if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasError) { text = Text('Error: ${snapshot.error}'); diff --git a/packages/path_provider/path_provider_android/pubspec.yaml b/packages/path_provider/path_provider_android/pubspec.yaml index 021a3bf16d66..a5a6380aa24b 100644 --- a/packages/path_provider/path_provider_android/pubspec.yaml +++ b/packages/path_provider/path_provider_android/pubspec.yaml @@ -2,7 +2,7 @@ name: path_provider_android description: Android implementation of the path_provider plugin. repository: https://github.com/flutter/packages/tree/main/packages/path_provider/path_provider_android issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+path_provider%22 -version: 2.2.22 +version: 2.2.23 environment: sdk: ^3.9.0 diff --git a/packages/path_provider/path_provider_foundation/CHANGELOG.md b/packages/path_provider/path_provider_foundation/CHANGELOG.md index 1c0ffee40bf6..b07a38497137 100644 --- a/packages/path_provider/path_provider_foundation/CHANGELOG.md +++ b/packages/path_provider/path_provider_foundation/CHANGELOG.md @@ -1,5 +1,16 @@ +## 2.6.0 + +* Re-release: replaces Flutter-plugin-based implementation with direct + FFI calls to Foundation. +* Updates minimum supported SDK version to Flutter 3.38.4/Dart 3.10. + +## 2.5.1 + +* Reverts to plugin-based implementation while FFI issues are investigated. + ## 2.5.0 +* **Retracted** due to production build issues. * Replaces Flutter-plugin-based implementation with direct FFI calls to Foundation. diff --git a/packages/path_provider/path_provider_foundation/example/integration_test/path_provider_test.dart b/packages/path_provider/path_provider_foundation/example/integration_test/path_provider_test.dart index 2bd88a2c98f0..9ad8b748b972 100644 --- a/packages/path_provider/path_provider_foundation/example/integration_test/path_provider_test.dart +++ b/packages/path_provider/path_provider_foundation/example/integration_test/path_provider_test.dart @@ -76,7 +76,7 @@ void main() { testWidgets('getContainerDirectory', (WidgetTester tester) async { if (Platform.isIOS) { - final PathProviderFoundation provider = PathProviderFoundation(); + final provider = PathProviderFoundation(); final String? result = await provider.getContainerPath( appGroupIdentifier: 'group.flutter.appGroupTest', ); @@ -90,11 +90,12 @@ void main() { // NSString, etc.) that aren't available in an actual unit test. For these // tests, the platform is stubbed out. group('unit', () { - final ValueVariant platformVariants = - ValueVariant({ - FakePlatformProvider(isIOS: true), - FakePlatformProvider(isMacOS: true), - }); + final platformVariants = ValueVariant( + { + FakePlatformProvider(isIOS: true), + FakePlatformProvider(isMacOS: true), + }, + ); // These tests use the actual filesystem, since an injectable filesystem // would add a runtime dependency to the package, so everything is contained @@ -110,8 +111,8 @@ void main() { }); testWidgets('getTemporaryPath iOS', (_) async { - final MockFoundationFFI mockFfiLib = MockFoundationFFI(); - final PathProviderFoundation pathProvider = PathProviderFoundation( + final mockFfiLib = MockFoundationFFI(); + final pathProvider = PathProviderFoundation( ffiLib: mockFfiLib, platform: FakePlatformProvider(isIOS: true), ); @@ -131,8 +132,8 @@ void main() { }); testWidgets('getTemporaryPath macOS', (_) async { - final MockFoundationFFI mockFfiLib = MockFoundationFFI(); - final PathProviderFoundation pathProvider = PathProviderFoundation( + final mockFfiLib = MockFoundationFFI(); + final pathProvider = PathProviderFoundation( ffiLib: mockFfiLib, platform: FakePlatformProvider(isMacOS: true), ); @@ -153,8 +154,8 @@ void main() { }); testWidgets('getApplicationSupportPath iOS', (_) async { - final MockFoundationFFI mockFfiLib = MockFoundationFFI(); - final PathProviderFoundation pathProvider = PathProviderFoundation( + final mockFfiLib = MockFoundationFFI(); + final pathProvider = PathProviderFoundation( ffiLib: mockFfiLib, platform: FakePlatformProvider(isIOS: true), ); @@ -179,8 +180,8 @@ void main() { }); testWidgets('getApplicationSupportPath macOS', (_) async { - final MockFoundationFFI mockFfiLib = MockFoundationFFI(); - final PathProviderFoundation pathProvider = PathProviderFoundation( + final mockFfiLib = MockFoundationFFI(); + final pathProvider = PathProviderFoundation( ffiLib: mockFfiLib, platform: FakePlatformProvider(isMacOS: true), ); @@ -211,8 +212,8 @@ void main() { testWidgets( 'getApplicationSupportPath creates the directory if necessary', (_) async { - final MockFoundationFFI mockFfiLib = MockFoundationFFI(); - final PathProviderFoundation pathProvider = PathProviderFoundation( + final mockFfiLib = MockFoundationFFI(); + final pathProvider = PathProviderFoundation( ffiLib: mockFfiLib, platform: platformVariants.currentValue, ); @@ -239,8 +240,8 @@ void main() { ); testWidgets('getLibraryPath', (_) async { - final MockFoundationFFI mockFfiLib = MockFoundationFFI(); - final PathProviderFoundation pathProvider = PathProviderFoundation( + final mockFfiLib = MockFoundationFFI(); + final pathProvider = PathProviderFoundation( ffiLib: mockFfiLib, platform: platformVariants.currentValue, ); @@ -260,8 +261,8 @@ void main() { }, variant: platformVariants); testWidgets('getApplicationDocumentsPath', (_) async { - final MockFoundationFFI mockFfiLib = MockFoundationFFI(); - final PathProviderFoundation pathProvider = PathProviderFoundation( + final mockFfiLib = MockFoundationFFI(); + final pathProvider = PathProviderFoundation( ffiLib: mockFfiLib, platform: platformVariants.currentValue, ); @@ -286,8 +287,8 @@ void main() { }, variant: platformVariants); testWidgets('getApplicationCachePath iOS', (_) async { - final MockFoundationFFI mockFfiLib = MockFoundationFFI(); - final PathProviderFoundation pathProvider = PathProviderFoundation( + final mockFfiLib = MockFoundationFFI(); + final pathProvider = PathProviderFoundation( ffiLib: mockFfiLib, platform: FakePlatformProvider(isIOS: true), ); @@ -312,8 +313,8 @@ void main() { }); testWidgets('getApplicationCachePath macOS', (_) async { - final MockFoundationFFI mockFfiLib = MockFoundationFFI(); - final PathProviderFoundation pathProvider = PathProviderFoundation( + final mockFfiLib = MockFoundationFFI(); + final pathProvider = PathProviderFoundation( ffiLib: mockFfiLib, platform: FakePlatformProvider(isMacOS: true), ); @@ -344,8 +345,8 @@ void main() { testWidgets( 'getApplicationCachePath creates the directory if necessary', (_) async { - final MockFoundationFFI mockFfiLib = MockFoundationFFI(); - final PathProviderFoundation pathProvider = PathProviderFoundation( + final mockFfiLib = MockFoundationFFI(); + final pathProvider = PathProviderFoundation( ffiLib: mockFfiLib, platform: platformVariants.currentValue, ); @@ -372,8 +373,8 @@ void main() { ); testWidgets('getDownloadsPath', (_) async { - final MockFoundationFFI mockFfiLib = MockFoundationFFI(); - final PathProviderFoundation pathProvider = PathProviderFoundation( + final mockFfiLib = MockFoundationFFI(); + final pathProvider = PathProviderFoundation( ffiLib: mockFfiLib, platform: platformVariants.currentValue, ); @@ -396,14 +397,14 @@ void main() { final String containerPath = p.join(testRoot.path, 'container', 'path'); final NSURL containerUrl = NSURL.fileURLWithPath(NSString(containerPath)); - final MockFoundationFFI mockFfiLib = MockFoundationFFI(); - final PathProviderFoundation pathProvider = PathProviderFoundation( + final mockFfiLib = MockFoundationFFI(); + final pathProvider = PathProviderFoundation( ffiLib: mockFfiLib, containerURLForSecurityApplicationGroupIdentifier: (_) => containerUrl, platform: FakePlatformProvider(isIOS: true), ); - const String appGroupIdentifier = 'group.example.test'; + const appGroupIdentifier = 'group.example.test'; final String? result = await pathProvider.getContainerPath( appGroupIdentifier: appGroupIdentifier, ); @@ -426,8 +427,8 @@ void _verifySampleFile(String? directoryPath, String name) { if (directoryPath == null) { return; } - final Directory directory = Directory(directoryPath); - final File file = File('${directory.path}${Platform.pathSeparator}$name'); + final directory = Directory(directoryPath); + final file = File('${directory.path}${Platform.pathSeparator}$name'); if (file.existsSync()) { file.deleteSync(); diff --git a/packages/path_provider/path_provider_foundation/example/ios/Flutter/AppFrameworkInfo.plist b/packages/path_provider/path_provider_foundation/example/ios/Flutter/AppFrameworkInfo.plist index 1dc6cf7652ba..391a902b2beb 100644 --- a/packages/path_provider/path_provider_foundation/example/ios/Flutter/AppFrameworkInfo.plist +++ b/packages/path_provider/path_provider_foundation/example/ios/Flutter/AppFrameworkInfo.plist @@ -20,7 +20,5 @@ ???? CFBundleVersion 1.0 - MinimumOSVersion - 13.0 diff --git a/packages/path_provider/path_provider_foundation/example/ios/Flutter/Debug.xcconfig b/packages/path_provider/path_provider_foundation/example/ios/Flutter/Debug.xcconfig index ec97fc6f3021..592ceee85b89 100644 --- a/packages/path_provider/path_provider_foundation/example/ios/Flutter/Debug.xcconfig +++ b/packages/path_provider/path_provider_foundation/example/ios/Flutter/Debug.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" diff --git a/packages/path_provider/path_provider_foundation/example/ios/Flutter/Release.xcconfig b/packages/path_provider/path_provider_foundation/example/ios/Flutter/Release.xcconfig index c4855bfe2000..592ceee85b89 100644 --- a/packages/path_provider/path_provider_foundation/example/ios/Flutter/Release.xcconfig +++ b/packages/path_provider/path_provider_foundation/example/ios/Flutter/Release.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" diff --git a/packages/path_provider/path_provider_foundation/example/ios/Podfile b/packages/path_provider/path_provider_foundation/example/ios/Podfile deleted file mode 100644 index a4e8dc81f973..000000000000 --- a/packages/path_provider/path_provider_foundation/example/ios/Podfile +++ /dev/null @@ -1,44 +0,0 @@ -# Uncomment this line to define a global platform for your project -# platform :ios, '13.0' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_ios_podfile_setup - -target 'Runner' do - use_frameworks! - - flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) - - target 'RunnerTests' do - inherit! :search_paths - end -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_ios_build_settings(target) - end -end diff --git a/packages/path_provider/path_provider_foundation/example/ios/Runner.xcodeproj/project.pbxproj b/packages/path_provider/path_provider_foundation/example/ios/Runner.xcodeproj/project.pbxproj index ea6743595e0c..0c70fafc2d34 100644 --- a/packages/path_provider/path_provider_foundation/example/ios/Runner.xcodeproj/project.pbxproj +++ b/packages/path_provider/path_provider_foundation/example/ios/Runner.xcodeproj/project.pbxproj @@ -10,13 +10,11 @@ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; 33258D7929818305006BAA98 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33258D7729818302006BAA98 /* RunnerTests.swift */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; - 569E86265D93B926F433B2DF /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 479D5DD53D431F6BBABA2E43 /* Pods_Runner.framework */; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; - D18DAAE2A3406D4789C8DAB2 /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 988A82A3033B36B9EAF2782B /* Pods_RunnerTests.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -45,18 +43,13 @@ /* Begin PBXFileReference section */ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; - 1E28C831B7D8EA9408BFB69A /* 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 = ""; }; 33258D7729818302006BAA98 /* RunnerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = RunnerTests.swift; path = ../../darwin/RunnerTests/RunnerTests.swift; sourceTree = ""; }; 3380327429784D96002D32AE /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; - 479D5DD53D431F6BBABA2E43 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 5DB8EF5A2759054360D79B8D /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; - 86F7986E9DC17432CC8AE464 /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; - 91DA83C3D33EB641BAEA3087 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -64,10 +57,7 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 988A82A3033B36B9EAF2782B /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 9AEFA2CD2991B4C300C2ED4A /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = ""; }; - B0CB6DC5569DDEB858FBEB22 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; - C1E50EBAA845915BAF5591C9 /* 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 = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -75,7 +65,6 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - D18DAAE2A3406D4789C8DAB2 /* Pods_RunnerTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -84,7 +73,6 @@ buildActionMask = 2147483647; files = ( 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, - 569E86265D93B926F433B2DF /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -119,7 +107,6 @@ 33258D76298182CC006BAA98 /* RunnerTests */, 97C146EF1CF9000F007C117D /* Products */, E1C876D20454FC3A1ED7F7E5 /* Pods */, - C72F144CE69E83C4574EB334 /* Frameworks */, ); sourceTree = ""; }; @@ -148,24 +135,9 @@ path = Runner; sourceTree = ""; }; - C72F144CE69E83C4574EB334 /* Frameworks */ = { - isa = PBXGroup; - children = ( - 479D5DD53D431F6BBABA2E43 /* Pods_Runner.framework */, - 988A82A3033B36B9EAF2782B /* Pods_RunnerTests.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; E1C876D20454FC3A1ED7F7E5 /* Pods */ = { isa = PBXGroup; children = ( - 5DB8EF5A2759054360D79B8D /* Pods-Runner.debug.xcconfig */, - B0CB6DC5569DDEB858FBEB22 /* Pods-Runner.release.xcconfig */, - 91DA83C3D33EB641BAEA3087 /* Pods-Runner.profile.xcconfig */, - 1E28C831B7D8EA9408BFB69A /* Pods-RunnerTests.debug.xcconfig */, - C1E50EBAA845915BAF5591C9 /* Pods-RunnerTests.release.xcconfig */, - 86F7986E9DC17432CC8AE464 /* Pods-RunnerTests.profile.xcconfig */, ); path = Pods; sourceTree = ""; @@ -177,7 +149,6 @@ isa = PBXNativeTarget; buildConfigurationList = 3380327D29784D96002D32AE /* Build configuration list for PBXNativeTarget "RunnerTests" */; buildPhases = ( - 9144B1C9B36C0B00C1DF8FBB /* [CP] Check Pods Manifest.lock */, 3380327029784D96002D32AE /* Sources */, 3380327129784D96002D32AE /* Frameworks */, 3380327229784D96002D32AE /* Resources */, @@ -196,14 +167,12 @@ isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - 45F307B61DA47FC553C87CA6 /* [CP] Check Pods Manifest.lock */, 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, 97C146EC1CF9000F007C117D /* Resources */, 9705A1C41CF9048500538489 /* Embed Frameworks */, 3B06AD1E1E4923F5004D2608 /* Thin Binary */, - D4AF0CAAE697EF439AFEC08C /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -297,50 +266,6 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; }; - 45F307B61DA47FC553C87CA6 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 9144B1C9B36C0B00C1DF8FBB /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; 9740EEB61CF901F6004384FC /* Run Script */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; @@ -356,23 +281,6 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; }; - D4AF0CAAE697EF439AFEC08C /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", - ); - name = "[CP] Embed Pods Frameworks"; - outputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -497,7 +405,6 @@ }; 3380327A29784D96002D32AE /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 1E28C831B7D8EA9408BFB69A /* Pods-RunnerTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; @@ -505,14 +412,13 @@ MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 6.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; }; name = Debug; }; 3380327B29784D96002D32AE /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = C1E50EBAA845915BAF5591C9 /* Pods-RunnerTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; @@ -520,14 +426,13 @@ MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 6.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; }; name = Release; }; 3380327C29784D96002D32AE /* Profile */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 86F7986E9DC17432CC8AE464 /* Pods-RunnerTests.profile.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; @@ -535,7 +440,7 @@ MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 6.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; }; name = Profile; diff --git a/packages/path_provider/path_provider_foundation/example/lib/main.dart b/packages/path_provider/path_provider_foundation/example/lib/main.dart index 884f68ec7f91..ca2af824df43 100644 --- a/packages/path_provider/path_provider_foundation/example/lib/main.dart +++ b/packages/path_provider/path_provider_foundation/example/lib/main.dart @@ -45,7 +45,7 @@ class _MyAppState extends State { String? containerDirectory; String? cacheDirectory; final PathProviderPlatform provider = PathProviderPlatform.instance; - final PathProviderFoundation providerFoundation = PathProviderFoundation(); + final providerFoundation = PathProviderFoundation(); try { tempDirectory = await provider.getTemporaryPath(); diff --git a/packages/path_provider/path_provider_foundation/example/macos/Flutter/Flutter-Debug.xcconfig b/packages/path_provider/path_provider_foundation/example/macos/Flutter/Flutter-Debug.xcconfig index 785633d3a86b..c2efd0b608ba 100644 --- a/packages/path_provider/path_provider_foundation/example/macos/Flutter/Flutter-Debug.xcconfig +++ b/packages/path_provider/path_provider_foundation/example/macos/Flutter/Flutter-Debug.xcconfig @@ -1,2 +1 @@ -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" diff --git a/packages/path_provider/path_provider_foundation/example/macos/Flutter/Flutter-Release.xcconfig b/packages/path_provider/path_provider_foundation/example/macos/Flutter/Flutter-Release.xcconfig index 5fba960c3af2..c2efd0b608ba 100644 --- a/packages/path_provider/path_provider_foundation/example/macos/Flutter/Flutter-Release.xcconfig +++ b/packages/path_provider/path_provider_foundation/example/macos/Flutter/Flutter-Release.xcconfig @@ -1,2 +1 @@ -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" diff --git a/packages/path_provider/path_provider_foundation/example/macos/Podfile b/packages/path_provider/path_provider_foundation/example/macos/Podfile deleted file mode 100644 index b687011ee229..000000000000 --- a/packages/path_provider/path_provider_foundation/example/macos/Podfile +++ /dev/null @@ -1,43 +0,0 @@ -platform :osx, '10.15' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\"" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_macos_podfile_setup - -target 'Runner' do - use_frameworks! - - flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__)) - - target 'RunnerTests' do - inherit! :search_paths - end -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_macos_build_settings(target) - end -end diff --git a/packages/path_provider/path_provider_foundation/example/macos/Runner.xcodeproj/project.pbxproj b/packages/path_provider/path_provider_foundation/example/macos/Runner.xcodeproj/project.pbxproj index ba309f37ca90..dcb49a46668e 100644 --- a/packages/path_provider/path_provider_foundation/example/macos/Runner.xcodeproj/project.pbxproj +++ b/packages/path_provider/path_provider_foundation/example/macos/Runner.xcodeproj/project.pbxproj @@ -21,7 +21,6 @@ /* End PBXAggregateTarget section */ /* Begin PBXBuildFile section */ - 23F6FAA3AF82DFCF2B7DD79A /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1523F64D34B952AB303BFFA8 /* Pods_Runner.framework */; }; 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; @@ -29,7 +28,6 @@ 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; 33EBD3AA26728EA70013E557 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33EBD3A926728EA70013E557 /* RunnerTests.swift */; }; 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; - FEE1C654F5DF2F210CC17B17 /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BA0C143378C83246316BE4F7 /* Pods_RunnerTests.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -63,11 +61,6 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 0A1A53CF00FD04D6ED0A8E4A /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; - 0B41979101786837FC1ABC29 /* 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 = ""; }; - 0B43E5DCF2F998ABCD395373 /* 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 = ""; }; - 1523F64D34B952AB303BFFA8 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 1C62AF358280E9A8FA10B127 /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; 33CC10ED2044A3C60003C045 /* path_provider_example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = path_provider_example.app; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -85,12 +78,9 @@ 33EBD3A726728EA70013E557 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 33EBD3A926728EA70013E557 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ../../../darwin/RunnerTests/RunnerTests.swift; sourceTree = ""; }; 33EBD3AB26728EA70013E557 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 46139048DB9F59D473B61B5E /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; - BA0C143378C83246316BE4F7 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - F4586DA69948E3A954A2FC9C /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -99,7 +89,6 @@ buildActionMask = 2147483647; files = ( 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, - 23F6FAA3AF82DFCF2B7DD79A /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -107,7 +96,6 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - FEE1C654F5DF2F210CC17B17 /* Pods_RunnerTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -117,12 +105,6 @@ 30697CBF35C100C7DD4B4699 /* Pods */ = { isa = PBXGroup; children = ( - 46139048DB9F59D473B61B5E /* Pods-Runner.debug.xcconfig */, - F4586DA69948E3A954A2FC9C /* Pods-Runner.release.xcconfig */, - 0A1A53CF00FD04D6ED0A8E4A /* Pods-Runner.profile.xcconfig */, - 0B43E5DCF2F998ABCD395373 /* Pods-RunnerTests.debug.xcconfig */, - 0B41979101786837FC1ABC29 /* Pods-RunnerTests.release.xcconfig */, - 1C62AF358280E9A8FA10B127 /* Pods-RunnerTests.profile.xcconfig */, ); path = Pods; sourceTree = ""; @@ -145,7 +127,6 @@ 33CEB47122A05771004F2AC0 /* Flutter */, 33EBD3A826728EA70013E557 /* RunnerTests */, 33CC10EE2044A3C60003C045 /* Products */, - D73912EC22F37F3D000D13A0 /* Frameworks */, 30697CBF35C100C7DD4B4699 /* Pods */, ); sourceTree = ""; @@ -204,15 +185,6 @@ path = Runner; sourceTree = ""; }; - D73912EC22F37F3D000D13A0 /* Frameworks */ = { - isa = PBXGroup; - children = ( - 1523F64D34B952AB303BFFA8 /* Pods_Runner.framework */, - BA0C143378C83246316BE4F7 /* Pods_RunnerTests.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -220,13 +192,11 @@ isa = PBXNativeTarget; buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - 82C3ED26F2C350499338A54B /* [CP] Check Pods Manifest.lock */, 33CC10E92044A3C60003C045 /* Sources */, 33CC10EA2044A3C60003C045 /* Frameworks */, 33CC10EB2044A3C60003C045 /* Resources */, 33CC110E2044A8840003C045 /* Bundle Framework */, 3399D490228B24CF009A79C7 /* ShellScript */, - 1266F7AD8AAB78C0041678F8 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -245,7 +215,6 @@ isa = PBXNativeTarget; buildConfigurationList = 33EBD3B126728EA70013E557 /* Build configuration list for PBXNativeTarget "RunnerTests" */; buildPhases = ( - 74960BD2BEA7516F537D0F92 /* [CP] Check Pods Manifest.lock */, 33EBD3A326728EA70013E557 /* Sources */, 33EBD3A426728EA70013E557 /* Frameworks */, 33EBD3A526728EA70013E557 /* Resources */, @@ -333,24 +302,6 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 1266F7AD8AAB78C0041678F8 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh", - "${BUILT_PRODUCTS_DIR}/objective_c/objective_c.framework", - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/objective_c.framework", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; 3399D490228B24CF009A79C7 /* ShellScript */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; @@ -389,50 +340,6 @@ shellPath = /bin/sh; shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh\ntouch Flutter/ephemeral/tripwire\n"; }; - 74960BD2BEA7516F537D0F92 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 82C3ED26F2C350499338A54B /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -723,7 +630,6 @@ }; 33EBD3AE26728EA70013E557 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 0B43E5DCF2F998ABCD395373 /* Pods-RunnerTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; COMBINE_HIDPI_IMAGES = YES; @@ -735,14 +641,13 @@ ); PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 6.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/path_provider_example.app/Contents/MacOS/path_provider_example"; }; name = Debug; }; 33EBD3AF26728EA70013E557 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 0B41979101786837FC1ABC29 /* Pods-RunnerTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; COMBINE_HIDPI_IMAGES = YES; @@ -754,14 +659,13 @@ ); PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 6.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/path_provider_example.app/Contents/MacOS/path_provider_example"; }; name = Release; }; 33EBD3B026728EA70013E557 /* Profile */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 1C62AF358280E9A8FA10B127 /* Pods-RunnerTests.profile.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; COMBINE_HIDPI_IMAGES = YES; @@ -773,7 +677,7 @@ ); PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 6.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/path_provider_example.app/Contents/MacOS/path_provider_example"; }; name = Profile; diff --git a/packages/path_provider/path_provider_foundation/example/pubspec.yaml b/packages/path_provider/path_provider_foundation/example/pubspec.yaml index 41355762b20c..7f188b977469 100644 --- a/packages/path_provider/path_provider_foundation/example/pubspec.yaml +++ b/packages/path_provider/path_provider_foundation/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the path_provider plugin. publish_to: none environment: - sdk: ^3.9.0 - flutter: ">=3.35.0" + sdk: ^3.10.3 + flutter: ">=3.38.4" dependencies: flutter: @@ -25,7 +25,7 @@ dev_dependencies: integration_test: sdk: flutter mockito: ^5.5.0 - objective_c: ^9.0.0 + objective_c: ^9.2.1 path: ^1.8.0 flutter: diff --git a/packages/path_provider/path_provider_foundation/pubspec.yaml b/packages/path_provider/path_provider_foundation/pubspec.yaml index a7daee5e8983..ce37651e25b6 100644 --- a/packages/path_provider/path_provider_foundation/pubspec.yaml +++ b/packages/path_provider/path_provider_foundation/pubspec.yaml @@ -2,11 +2,11 @@ name: path_provider_foundation description: iOS and macOS implementation of the path_provider plugin repository: https://github.com/flutter/packages/tree/main/packages/path_provider/path_provider_foundation issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+path_provider%22 -version: 2.5.0 +version: 2.6.0 environment: - sdk: ^3.9.0 - flutter: ">=3.35.0" + sdk: ^3.10.3 + flutter: ">=3.38.4" flutter: plugin: @@ -21,7 +21,7 @@ dependencies: ffi: ^2.1.4 flutter: sdk: flutter - objective_c: ^9.1.0 + objective_c: ^9.2.1 path_provider_platform_interface: ^2.1.0 dev_dependencies: diff --git a/packages/path_provider/path_provider_foundation/test/path_provider_foundation_test.dart b/packages/path_provider/path_provider_foundation/test/path_provider_foundation_test.dart index 459444bb53ad..506e135768da 100644 --- a/packages/path_provider/path_provider_foundation/test/path_provider_foundation_test.dart +++ b/packages/path_provider/path_provider_foundation/test/path_provider_foundation_test.dart @@ -30,16 +30,12 @@ void main() { }); test('getExternalCachePaths throws', () async { - final PathProviderFoundation pathProvider = PathProviderFoundation( - ffiLib: FakeFoundationFFI(), - ); + final pathProvider = PathProviderFoundation(ffiLib: FakeFoundationFFI()); expect(pathProvider.getExternalCachePaths(), throwsA(isUnsupportedError)); }); test('getExternalStoragePath throws', () async { - final PathProviderFoundation pathProvider = PathProviderFoundation( - ffiLib: FakeFoundationFFI(), - ); + final pathProvider = PathProviderFoundation(ffiLib: FakeFoundationFFI()); expect( pathProvider.getExternalStoragePath(), throwsA(isUnsupportedError), @@ -47,9 +43,7 @@ void main() { }); test('getExternalStoragePaths throws', () async { - final PathProviderFoundation pathProvider = PathProviderFoundation( - ffiLib: FakeFoundationFFI(), - ); + final pathProvider = PathProviderFoundation(ffiLib: FakeFoundationFFI()); expect( pathProvider.getExternalStoragePaths(), throwsA(isUnsupportedError), @@ -57,7 +51,7 @@ void main() { }); test('getContainerPath throws on macOS', () async { - final PathProviderFoundation pathProvider = PathProviderFoundation( + final pathProvider = PathProviderFoundation( platform: FakePlatformProvider(isMacOS: true), ffiLib: FakeFoundationFFI(), ); diff --git a/packages/path_provider/path_provider_foundation/tool/ffigen.dart b/packages/path_provider/path_provider_foundation/tool/ffigen.dart index 214cba31e6f3..e07f848581e8 100644 --- a/packages/path_provider/path_provider_foundation/tool/ffigen.dart +++ b/packages/path_provider/path_provider_foundation/tool/ffigen.dart @@ -33,7 +33,7 @@ void main() { }, includeMember: (Declaration declaration, String member) { final String interfaceName = declaration.originalName; - final String signature = member; + final signature = member; return switch (interfaceName) { 'NSFileManager' => { 'containerURLForSecurityApplicationGroupIdentifier:', diff --git a/packages/path_provider/path_provider_linux/CHANGELOG.md b/packages/path_provider/path_provider_linux/CHANGELOG.md index 4fa3cabfe72b..c20a465819e2 100644 --- a/packages/path_provider/path_provider_linux/CHANGELOG.md +++ b/packages/path_provider/path_provider_linux/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. ## 2.2.1 diff --git a/packages/path_provider/path_provider_linux/example/integration_test/path_provider_test.dart b/packages/path_provider/path_provider_linux/example/integration_test/path_provider_test.dart index 8ab4e8374bb9..2c916682b460 100644 --- a/packages/path_provider/path_provider_linux/example/integration_test/path_provider_test.dart +++ b/packages/path_provider/path_provider_linux/example/integration_test/path_provider_test.dart @@ -11,7 +11,7 @@ void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('getTemporaryDirectory', (WidgetTester tester) async { - final PathProviderLinux provider = PathProviderLinux(); + final provider = PathProviderLinux(); final String? result = await provider.getTemporaryPath(); _verifySampleFile(result, 'temporaryDirectory'); }); @@ -20,25 +20,25 @@ void main() { if (!Platform.isLinux) { return; } - final PathProviderLinux provider = PathProviderLinux(); + final provider = PathProviderLinux(); final String? result = await provider.getDownloadsPath(); _verifySampleFile(result, 'downloadDirectory'); }); testWidgets('getApplicationDocumentsDirectory', (WidgetTester tester) async { - final PathProviderLinux provider = PathProviderLinux(); + final provider = PathProviderLinux(); final String? result = await provider.getApplicationDocumentsPath(); _verifySampleFile(result, 'applicationDocuments'); }); testWidgets('getApplicationSupportDirectory', (WidgetTester tester) async { - final PathProviderLinux provider = PathProviderLinux(); + final provider = PathProviderLinux(); final String? result = await provider.getApplicationSupportPath(); _verifySampleFile(result, 'applicationSupport'); }); testWidgets('getApplicationCacheDirectory', (WidgetTester tester) async { - final PathProviderLinux provider = PathProviderLinux(); + final provider = PathProviderLinux(); final String? result = await provider.getApplicationCachePath(); _verifySampleFile(result, 'applicationCache'); }); @@ -51,8 +51,8 @@ void _verifySampleFile(String? directoryPath, String name) { if (directoryPath == null) { return; } - final Directory directory = Directory(directoryPath); - final File file = File('${directory.path}${Platform.pathSeparator}$name'); + final directory = Directory(directoryPath); + final file = File('${directory.path}${Platform.pathSeparator}$name'); if (file.existsSync()) { file.deleteSync(); diff --git a/packages/path_provider/path_provider_linux/example/pubspec.yaml b/packages/path_provider/path_provider_linux/example/pubspec.yaml index 10b611c7ad0c..128b76d1f50e 100644 --- a/packages/path_provider/path_provider_linux/example/pubspec.yaml +++ b/packages/path_provider/path_provider_linux/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the path_provider_linux plugin. publish_to: "none" environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" dependencies: flutter: diff --git a/packages/path_provider/path_provider_linux/lib/src/path_provider_linux.dart b/packages/path_provider/path_provider_linux/lib/src/path_provider_linux.dart index 64874471249e..20c4226cdac7 100644 --- a/packages/path_provider/path_provider_linux/lib/src/path_provider_linux.dart +++ b/packages/path_provider/path_provider_linux/lib/src/path_provider_linux.dart @@ -47,16 +47,14 @@ class PathProviderLinux extends PathProviderPlatform { @override Future getApplicationSupportPath() async { - final Directory directory = Directory( - path.join(xdg.dataHome.path, await _getId()), - ); + final directory = Directory(path.join(xdg.dataHome.path, await _getId())); if (directory.existsSync()) { return directory.path; } // This plugin originally used the executable name as a directory. // Use that if it exists for backwards compatibility. - final Directory legacyDirectory = Directory( + final legacyDirectory = Directory( path.join(xdg.dataHome.path, await _getExecutableName()), ); if (legacyDirectory.existsSync()) { @@ -75,9 +73,7 @@ class PathProviderLinux extends PathProviderPlatform { @override Future getApplicationCachePath() async { - final Directory directory = Directory( - path.join(xdg.cacheHome.path, await _getId()), - ); + final directory = Directory(path.join(xdg.cacheHome.path, await _getId())); if (!directory.existsSync()) { await directory.create(recursive: true); } diff --git a/packages/path_provider/path_provider_linux/pubspec.yaml b/packages/path_provider/path_provider_linux/pubspec.yaml index e49e63ef593f..f932ca25f002 100644 --- a/packages/path_provider/path_provider_linux/pubspec.yaml +++ b/packages/path_provider/path_provider_linux/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.2.1 environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" flutter: plugin: diff --git a/packages/path_provider/path_provider_linux/test/get_application_id_test.dart b/packages/path_provider/path_provider_linux/test/get_application_id_test.dart index 1730d897d78a..4e6afb33441b 100644 --- a/packages/path_provider/path_provider_linux/test/get_application_id_test.dart +++ b/packages/path_provider/path_provider_linux/test/get_application_id_test.dart @@ -53,7 +53,7 @@ void main() { test('returns value if g_application_get_application_id returns a value', () { fakeGio.libraryIsPresent = true; fakeGio.application = 1; - const String id = 'foo'; + const id = 'foo'; final Pointer idPtr = id.toNativeUtf8(); fakeGio.applicationId = idPtr; expect(getApplicationId(), id); diff --git a/packages/path_provider/path_provider_platform_interface/CHANGELOG.md b/packages/path_provider/path_provider_platform_interface/CHANGELOG.md index 1aa80031a123..06f0815e025e 100644 --- a/packages/path_provider/path_provider_platform_interface/CHANGELOG.md +++ b/packages/path_provider/path_provider_platform_interface/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. ## 2.1.2 diff --git a/packages/path_provider/path_provider_platform_interface/pubspec.yaml b/packages/path_provider/path_provider_platform_interface/pubspec.yaml index 3543f63f570d..5e732d931860 100644 --- a/packages/path_provider/path_provider_platform_interface/pubspec.yaml +++ b/packages/path_provider/path_provider_platform_interface/pubspec.yaml @@ -7,8 +7,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.1.2 environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" dependencies: flutter: diff --git a/packages/path_provider/path_provider_platform_interface/test/method_channel_path_provider_test.dart b/packages/path_provider/path_provider_platform_interface/test/method_channel_path_provider_test.dart index b404c977fece..77e199495979 100644 --- a/packages/path_provider/path_provider_platform_interface/test/method_channel_path_provider_test.dart +++ b/packages/path_provider/path_provider_platform_interface/test/method_channel_path_provider_test.dart @@ -10,18 +10,18 @@ import 'package:platform/platform.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); - const String kTemporaryPath = 'temporaryPath'; - const String kApplicationSupportPath = 'applicationSupportPath'; - const String kLibraryPath = 'libraryPath'; - const String kApplicationDocumentsPath = 'applicationDocumentsPath'; - const String kApplicationCachePath = 'applicationCachePath'; - const String kExternalCachePaths = 'externalCachePaths'; - const String kExternalStoragePaths = 'externalStoragePaths'; - const String kDownloadsPath = 'downloadsPath'; + const kTemporaryPath = 'temporaryPath'; + const kApplicationSupportPath = 'applicationSupportPath'; + const kLibraryPath = 'libraryPath'; + const kApplicationDocumentsPath = 'applicationDocumentsPath'; + const kApplicationCachePath = 'applicationCachePath'; + const kExternalCachePaths = 'externalCachePaths'; + const kExternalStoragePaths = 'externalStoragePaths'; + const kDownloadsPath = 'downloadsPath'; group('$MethodChannelPathProvider', () { late MethodChannelPathProvider methodChannelPathProvider; - final List log = []; + final log = []; setUp(() async { methodChannelPathProvider = MethodChannelPathProvider(); @@ -155,10 +155,7 @@ void main() { } }); - for (final StorageDirectory? type in [ - null, - ...StorageDirectory.values, - ]) { + for (final type in [null, ...StorageDirectory.values]) { test('getExternalStoragePaths (type: $type) android succeeds', () async { final List? result = await methodChannelPathProvider .getExternalStoragePaths(type: type); diff --git a/packages/path_provider/path_provider_platform_interface/test/path_provider_platform_interface_test.dart b/packages/path_provider/path_provider_platform_interface/test/path_provider_platform_interface_test.dart index 18eeadf34ba0..f38d94ee94b5 100644 --- a/packages/path_provider/path_provider_platform_interface/test/path_provider_platform_interface_test.dart +++ b/packages/path_provider/path_provider_platform_interface/test/path_provider_platform_interface_test.dart @@ -15,8 +15,7 @@ void main() { }); test('getApplicationCachePath throws unimplemented error', () { - final ExtendsPathProviderPlatform pathProviderPlatform = - ExtendsPathProviderPlatform(); + final pathProviderPlatform = ExtendsPathProviderPlatform(); expect( () => pathProviderPlatform.getApplicationCachePath(), diff --git a/packages/path_provider/path_provider_windows/CHANGELOG.md b/packages/path_provider/path_provider_windows/CHANGELOG.md index bdaf657695a7..7106687483c5 100644 --- a/packages/path_provider/path_provider_windows/CHANGELOG.md +++ b/packages/path_provider/path_provider_windows/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. ## 2.3.0 diff --git a/packages/path_provider/path_provider_windows/example/integration_test/path_provider_test.dart b/packages/path_provider/path_provider_windows/example/integration_test/path_provider_test.dart index 913e79cb7428..214fc901499a 100644 --- a/packages/path_provider/path_provider_windows/example/integration_test/path_provider_test.dart +++ b/packages/path_provider/path_provider_windows/example/integration_test/path_provider_test.dart @@ -11,31 +11,31 @@ void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('getTemporaryDirectory', (WidgetTester tester) async { - final PathProviderWindows provider = PathProviderWindows(); + final provider = PathProviderWindows(); final String? result = await provider.getTemporaryPath(); _verifySampleFile(result, 'temporaryDirectory'); }); testWidgets('getApplicationDocumentsDirectory', (WidgetTester tester) async { - final PathProviderWindows provider = PathProviderWindows(); + final provider = PathProviderWindows(); final String? result = await provider.getApplicationDocumentsPath(); _verifySampleFile(result, 'applicationDocuments'); }); testWidgets('getApplicationSupportDirectory', (WidgetTester tester) async { - final PathProviderWindows provider = PathProviderWindows(); + final provider = PathProviderWindows(); final String? result = await provider.getApplicationSupportPath(); _verifySampleFile(result, 'applicationSupport'); }); testWidgets('getApplicationCacheDirectory', (WidgetTester tester) async { - final PathProviderWindows provider = PathProviderWindows(); + final provider = PathProviderWindows(); final String? result = await provider.getApplicationCachePath(); _verifySampleFile(result, 'applicationCache'); }); testWidgets('getDownloadsDirectory', (WidgetTester tester) async { - final PathProviderWindows provider = PathProviderWindows(); + final provider = PathProviderWindows(); final String? result = await provider.getDownloadsPath(); _verifySampleFile(result, 'downloads'); }); @@ -48,8 +48,8 @@ void _verifySampleFile(String? directoryPath, String name) { if (directoryPath == null) { return; } - final Directory directory = Directory(directoryPath); - final File file = File('${directory.path}${Platform.pathSeparator}$name'); + final directory = Directory(directoryPath); + final file = File('${directory.path}${Platform.pathSeparator}$name'); if (file.existsSync()) { file.deleteSync(); diff --git a/packages/path_provider/path_provider_windows/example/lib/main.dart b/packages/path_provider/path_provider_windows/example/lib/main.dart index 4dc03bf414ed..465492c1ece8 100644 --- a/packages/path_provider/path_provider_windows/example/lib/main.dart +++ b/packages/path_provider/path_provider_windows/example/lib/main.dart @@ -39,7 +39,7 @@ class _MyAppState extends State { String? appSupportDirectory; String? documentsDirectory; String? cacheDirectory; - final PathProviderWindows provider = PathProviderWindows(); + final provider = PathProviderWindows(); try { tempDirectory = await provider.getTemporaryPath(); diff --git a/packages/path_provider/path_provider_windows/example/pubspec.yaml b/packages/path_provider/path_provider_windows/example/pubspec.yaml index 3f584221d8cd..59c315085486 100644 --- a/packages/path_provider/path_provider_windows/example/pubspec.yaml +++ b/packages/path_provider/path_provider_windows/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the path_provider plugin. publish_to: none environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" dependencies: flutter: diff --git a/packages/path_provider/path_provider_windows/lib/src/guid.dart b/packages/path_provider/path_provider_windows/lib/src/guid.dart index 07bf17714eb3..c240b8098061 100644 --- a/packages/path_provider/path_provider_windows/lib/src/guid.dart +++ b/packages/path_provider/path_provider_windows/lib/src/guid.dart @@ -34,8 +34,8 @@ base class GUID extends Struct { if (hexOnly.length != 32) { throw ArgumentError.value(guid, 'guid', 'Invalid GUID string'); } - final ByteData bytes = ByteData(16); - for (int i = 0; i < 16; ++i) { + final bytes = ByteData(16); + for (var i = 0; i < 16; ++i) { bytes.setUint8( i, int.parse(hexOnly.substring(i * 2, i * 2 + 2), radix: 16), diff --git a/packages/path_provider/path_provider_windows/lib/src/path_provider_windows_real.dart b/packages/path_provider/path_provider_windows/lib/src/path_provider_windows_real.dart index 98df30bdf31e..e82bafc6332d 100644 --- a/packages/path_provider/path_provider_windows/lib/src/path_provider_windows_real.dart +++ b/packages/path_provider/path_provider_windows/lib/src/path_provider_windows_real.dart @@ -104,7 +104,7 @@ class PathProviderWindows extends PathProviderPlatform { } // Ensure that the directory exists, since GetTempPath doesn't. - final Directory directory = Directory(path); + final directory = Directory(path); if (!directory.existsSync()) { await directory.create(recursive: true); } @@ -255,7 +255,7 @@ class PathProviderWindows extends PathProviderPlatform { .trimRight() // Ensure that it does not end with a '.'. .replaceAll(RegExp(r'[.]+$'), ''); - const int kMaxComponentLength = 255; + const kMaxComponentLength = 255; if (sanitized.length > kMaxComponentLength) { sanitized = sanitized.substring(0, kMaxComponentLength); } @@ -267,7 +267,7 @@ class PathProviderWindows extends PathProviderPlatform { if (baseDir == null) { return null; } - final Directory directory = Directory( + final directory = Directory( path.join(baseDir, _getApplicationSpecificSubdirectory()), ); // Ensure that the directory exists if possible, since it will on other diff --git a/packages/path_provider/path_provider_windows/pubspec.yaml b/packages/path_provider/path_provider_windows/pubspec.yaml index 7c9579d04347..8a221e100e60 100644 --- a/packages/path_provider/path_provider_windows/pubspec.yaml +++ b/packages/path_provider/path_provider_windows/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.3.0 environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" flutter: plugin: diff --git a/packages/path_provider/path_provider_windows/test/guid_test.dart b/packages/path_provider/path_provider_windows/test/guid_test.dart index 9c7cbd41f6e8..dbb64d407ca6 100644 --- a/packages/path_provider/path_provider_windows/test/guid_test.dart +++ b/packages/path_provider/path_provider_windows/test/guid_test.dart @@ -13,7 +13,7 @@ void main() { test('has correct byte representation', () async { final Pointer guid = calloc() ..ref.parse('{00112233-4455-6677-8899-aabbccddeeff}'); - final ByteData data = ByteData(16) + final data = ByteData(16) ..setInt32(0, guid.ref.data1, Endian.little) ..setInt16(4, guid.ref.data2, Endian.little) ..setInt16(6, guid.ref.data3, Endian.little) diff --git a/packages/path_provider/path_provider_windows/test/path_provider_windows_test.dart b/packages/path_provider/path_provider_windows/test/path_provider_windows_test.dart index ed79b00d661c..5ef6c87299a6 100644 --- a/packages/path_provider/path_provider_windows/test/path_provider_windows_test.dart +++ b/packages/path_provider/path_provider_windows/test/path_provider_windows_test.dart @@ -45,12 +45,12 @@ void main() { }); test('getTemporaryPath', () async { - final PathProviderWindows pathProvider = PathProviderWindows(); + final pathProvider = PathProviderWindows(); expect(await pathProvider.getTemporaryPath(), contains(r'C:\')); }, skip: !Platform.isWindows); test('getApplicationSupportPath with no version info', () async { - final PathProviderWindows pathProvider = PathProviderWindows(); + final pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier( {}, ); @@ -64,7 +64,7 @@ void main() { test( 'getApplicationSupportPath with full version info in CP1252', () async { - final PathProviderWindows pathProvider = PathProviderWindows(); + final pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier({ 'CompanyName': 'A Company', 'ProductName': 'Amazing App', @@ -82,7 +82,7 @@ void main() { test( 'getApplicationSupportPath with full version info in Unicode', () async { - final PathProviderWindows pathProvider = PathProviderWindows(); + final pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier({ 'CompanyName': 'A Company', 'ProductName': 'Amazing App', @@ -100,7 +100,7 @@ void main() { test( 'getApplicationSupportPath with full version info in Unsupported Encoding', () async { - final PathProviderWindows pathProvider = PathProviderWindows(); + final pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier( { 'CompanyName': 'A Company', @@ -119,7 +119,7 @@ void main() { ); test('getApplicationSupportPath with missing company', () async { - final PathProviderWindows pathProvider = PathProviderWindows(); + final pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier({ 'ProductName': 'Amazing App', }); @@ -132,7 +132,7 @@ void main() { }, skip: !Platform.isWindows); test('getApplicationSupportPath with problematic values', () async { - final PathProviderWindows pathProvider = PathProviderWindows(); + final pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier({ 'CompanyName': r'A Company: Name.', 'ProductName': r'A"/Terrible\|App?*Name', @@ -153,7 +153,7 @@ void main() { test( 'getApplicationSupportPath with a completely invalid company', () async { - final PathProviderWindows pathProvider = PathProviderWindows(); + final pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier({ 'CompanyName': r'..', 'ProductName': r'Amazing App', @@ -169,7 +169,7 @@ void main() { ); test('getApplicationSupportPath with very long app name', () async { - final PathProviderWindows pathProvider = PathProviderWindows(); + final pathProvider = PathProviderWindows(); final String truncatedName = 'A' * 255; pathProvider.versionInfoQuerier = FakeVersionInfoQuerier({ 'CompanyName': 'A Company', @@ -182,14 +182,14 @@ void main() { }, skip: !Platform.isWindows); test('getApplicationDocumentsPath', () async { - final PathProviderWindows pathProvider = PathProviderWindows(); + final pathProvider = PathProviderWindows(); final String? path = await pathProvider.getApplicationDocumentsPath(); expect(path, contains(r'C:\')); expect(path, contains(r'Documents')); }, skip: !Platform.isWindows); test('getApplicationCachePath', () async { - final PathProviderWindows pathProvider = PathProviderWindows(); + final pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier({ 'CompanyName': 'A Company', 'ProductName': 'Amazing App', @@ -203,7 +203,7 @@ void main() { }, skip: !Platform.isWindows); test('getDownloadsPath', () async { - final PathProviderWindows pathProvider = PathProviderWindows(); + final pathProvider = PathProviderWindows(); final String? path = await pathProvider.getDownloadsPath(); expect(path, contains(r'C:\')); expect(path, contains(r'Downloads')); diff --git a/packages/pigeon/CHANGELOG.md b/packages/pigeon/CHANGELOG.md index b06060a495ec..d14e07c1b4b4 100644 --- a/packages/pigeon/CHANGELOG.md +++ b/packages/pigeon/CHANGELOG.md @@ -1,3 +1,70 @@ +## 26.3.1 + +* Fixes dartdoc comments that accidentally used HTML. + +## 26.3.0 + +* Optimizes and improves data class equality and hashing. +* Changes hashing and equality methods to behave consistently across platforms. +* Adds equality methods to previously unsupported languages. + +## 26.2.3 + +* Produces a helpful error message when a method return type is missing or an + unsupported type, such as a function type or record type. + +## 26.2.2 + +* [dart] Ignores all lint rules in generated code. +* [dart] In generated code, imports the meta package for annotations, instead of + the Flutter foundation library. +* [dart] In generated code, no longer imports Uint8List. +* Bumps minimum version of the args package to 2.5.0. + +## 26.2.1 + +* [dart] Improves nullability-handling in generated code. + +## 26.2.0 + +* [kotlin] Adds option to add javax.annotation.Generated annotation. + +## 26.1.10 + +* Dramatically reduces the number of File write operations sent to the operating + system during code-generation. This improves performance of IDEs and the Dart + analysis server. + +## 26.1.9 + +* [dart] Reduces much duplication in reply-handling code. + +## 26.1.8 + +* Makes some internal class constructors constant. + +## 26.1.7 + +* [objc] Updates to use module imports. + +## 26.1.6 + +* Bumps kotlin_version to 2.3.0. + +## 26.1.5 + +* [kotlin] Fixes a "bridge method" warning when implementing an event stream handler. + +## 26.1.4 + +* [swift][kotlin] Fixes crash that occurs when an object that is removed from the instance manager + calls to Dart. + +## 26.1.3 + +* [dart] Fixes error from constructor parameter sharing name with attached field for a ProxyApi. +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. + ## 26.1.2 * [kotlin] Fixes compilation error with unbounded type parameter for InstanceManager. diff --git a/packages/pigeon/CONTRIBUTING.md b/packages/pigeon/CONTRIBUTING.md index 698a36769de4..41ead7842651 100644 --- a/packages/pigeon/CONTRIBUTING.md +++ b/packages/pigeon/CONTRIBUTING.md @@ -6,16 +6,6 @@ Pigeon is a code generation tool that adds type safety to Flutter’s Platform Channels. This document serves as an overview of how it functions to help people who would like to contribute to the project. -## State Diagram - -Pigeon generates a temporary file in its _LaunchIsolate_, the isolate that is -spawned to run `main()`, then launches another isolate, _PigeonIsolate_, that -uses `dart:mirrors` to parse the generated file, creating an -[AST](https://en.wikipedia.org/wiki/Abstract_syntax_tree), then running code -generators with that AST. - -![State Diagram](./doc/pigeon_state.png) - ## Source Index * [ast.dart](./lib/src/ast.dart) - The data structure for representing the Abstract Syntax Tree. @@ -37,7 +27,7 @@ generators with that AST. ## Testing Overview -Pigeon has 3 types of tests, you'll find them all in +Pigeon has 3 types of tests; you'll find them all in [test.dart](./tool/test.dart). * Unit tests - These are the fastest tests that are just typical unit tests, @@ -73,11 +63,3 @@ void main(List args, SendPort sendPort) async { ``` This is how `dart:mirrors` gets access to the supplied Pigeon file. - -## Imminent Plans - -* Migrate to Dart Analyzer for AST generation ([issue - 78818](https://github.com/flutter/flutter/issues/78818)) - We might have - reached the limitations of using dart:mirrors for parsing the Dart files. - That package has been deprecated and it doesn't support null-safe annotations. - We should migrate to using the Dart Analyzer as the front-end parser. diff --git a/packages/pigeon/diff_tool.sh b/packages/pigeon/diff_tool.sh index 398105c8dccd..815a160dd286 100755 --- a/packages/pigeon/diff_tool.sh +++ b/packages/pigeon/diff_tool.sh @@ -21,7 +21,7 @@ gitTool="git -c advice.detachedHead=false" generate_everything() { local inputPath=$1 local outputDir=$2 - pub run pigeon \ + dart run pigeon \ --input "$inputPath" \ --dart_out "$outputDir/dart.dart" \ --java_out "$outputDir/java.dart" \ diff --git a/packages/pigeon/doc/pigeon_state.png b/packages/pigeon/doc/pigeon_state.png deleted file mode 100644 index 79539ad44a8a..000000000000 Binary files a/packages/pigeon/doc/pigeon_state.png and /dev/null differ diff --git a/packages/pigeon/doc/pigeon_state.puml b/packages/pigeon/doc/pigeon_state.puml deleted file mode 100644 index 4027ac4ad8be..000000000000 --- a/packages/pigeon/doc/pigeon_state.puml +++ /dev/null @@ -1,60 +0,0 @@ -@startuml - -[*] -> LaunchIsolate - -state LaunchIsolate { - [*] --> ParseCommandLineArguments - ParseCommandLineArguments --> WriteTemporarySourceCode - WriteTemporarySourceCode --> SpawnPigeonIsolate - SpawnPigeonIsolate --> WaitForPigeonIsolate - WaitForPigeonIsolate --> [*] -} - -LaunchIsolate -> [*] - -state PigeonIsolate { - [*] --> ParseCommandLineArguments2 - ParseCommandLineArguments2 --> PrintUsage - PrintUsage --> [*] - ParseCommandLineArguments2 --> ExecuteConfigurePigeon - ExecuteConfigurePigeon --> GenerateAST - GenerateAST --> RunGenerators - RunGenerators --> PrintErrors - PrintErrors --> ReturnStatusCode - ReturnStatusCode --> [*] - - state GenerateAST { - [*] --> CollectAnnotatedClasses - CollectAnnotatedClasses --> CollectAnnotatedClassesDependencies - CollectAnnotatedClassesDependencies --> BuildAST - BuildAST --> [*] - } - - state RunGenerators { - state DartTestGeneratorFork <> - state DartTestGeneratorJoin <> - [*] --> DartTestGeneratorFork - DartTestGeneratorFork --> DartTestGeneratorJoin - DartTestGeneratorFork --> DartTestGenerator - DartTestGenerator --> DartTestGeneratorJoin - DartTestGeneratorJoin --> [*] - || - state DartGeneratorFork <> - state DartGeneratorJoin <> - [*] --> DartGeneratorFork - DartGeneratorFork --> DartGeneratorJoin - DartGeneratorFork --> DartGenerator - DartGenerator --> DartGeneratorJoin - DartGeneratorJoin --> [*] - || - state JavaGeneratorFork <> - state JavaGeneratorJoin <> - [*] --> JavaGeneratorFork - JavaGeneratorFork --> JavaGeneratorJoin - JavaGeneratorFork --> JavaGenerator - JavaGenerator --> JavaGeneratorJoin - JavaGeneratorJoin --> [*] - } -} - -@enduml \ No newline at end of file diff --git a/packages/pigeon/example/README.md b/packages/pigeon/example/README.md index b3e895b26c66..1ce5a202cb7b 100644 --- a/packages/pigeon/example/README.md +++ b/packages/pigeon/example/README.md @@ -103,7 +103,7 @@ Future add(int a, int b) async { /// Sends message through host api using `MessageData` class /// and api `sendMessage` method. Future sendMessage(String messageText) { - final MessageData message = MessageData( + final message = MessageData( code: Code.one, data: {'header': 'this is a header'}, description: 'uri text', diff --git a/packages/pigeon/example/app/android/app/src/main/java/io/flutter/plugins/Messages.java b/packages/pigeon/example/app/android/app/src/main/java/io/flutter/plugins/Messages.java index 799d468cfb1e..751c1f5dc3b0 100644 --- a/packages/pigeon/example/app/android/app/src/main/java/io/flutter/plugins/Messages.java +++ b/packages/pigeon/example/app/android/app/src/main/java/io/flutter/plugins/Messages.java @@ -19,14 +19,171 @@ import java.lang.annotation.Target; import java.nio.ByteBuffer; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.Objects; /** Generated class from Pigeon. */ @SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression", "serial"}) public class Messages { + static boolean pigeonDoubleEquals(double a, double b) { + // Normalize -0.0 to 0.0 and handle NaN equality. + return (a == 0.0 ? 0.0 : a) == (b == 0.0 ? 0.0 : b) || (Double.isNaN(a) && Double.isNaN(b)); + } + + static boolean pigeonFloatEquals(float a, float b) { + // Normalize -0.0 to 0.0 and handle NaN equality. + return (a == 0.0f ? 0.0f : a) == (b == 0.0f ? 0.0f : b) || (Float.isNaN(a) && Float.isNaN(b)); + } + + static int pigeonDoubleHashCode(double d) { + // Normalize -0.0 to 0.0 and handle NaN to ensure consistent hash codes. + if (d == 0.0) { + d = 0.0; + } + long bits = Double.doubleToLongBits(d); + return (int) (bits ^ (bits >>> 32)); + } + + static int pigeonFloatHashCode(float f) { + // Normalize -0.0 to 0.0 and handle NaN to ensure consistent hash codes. + if (f == 0.0f) { + f = 0.0f; + } + return Float.floatToIntBits(f); + } + + static boolean pigeonDeepEquals(Object a, Object b) { + if (a == b) { + return true; + } + if (a == null || b == null) { + return false; + } + if (a instanceof byte[] && b instanceof byte[]) { + return Arrays.equals((byte[]) a, (byte[]) b); + } + if (a instanceof int[] && b instanceof int[]) { + return Arrays.equals((int[]) a, (int[]) b); + } + if (a instanceof long[] && b instanceof long[]) { + return Arrays.equals((long[]) a, (long[]) b); + } + if (a instanceof double[] && b instanceof double[]) { + double[] da = (double[]) a; + double[] db = (double[]) b; + if (da.length != db.length) { + return false; + } + for (int i = 0; i < da.length; i++) { + if (!pigeonDoubleEquals(da[i], db[i])) { + return false; + } + } + return true; + } + if (a instanceof List && b instanceof List) { + List listA = (List) a; + List listB = (List) b; + if (listA.size() != listB.size()) { + return false; + } + for (int i = 0; i < listA.size(); i++) { + if (!pigeonDeepEquals(listA.get(i), listB.get(i))) { + return false; + } + } + return true; + } + if (a instanceof Map && b instanceof Map) { + Map mapA = (Map) a; + Map mapB = (Map) b; + if (mapA.size() != mapB.size()) { + return false; + } + for (Map.Entry entryA : mapA.entrySet()) { + Object keyA = entryA.getKey(); + Object valueA = entryA.getValue(); + boolean found = false; + for (Map.Entry entryB : mapB.entrySet()) { + Object keyB = entryB.getKey(); + if (pigeonDeepEquals(keyA, keyB)) { + Object valueB = entryB.getValue(); + if (pigeonDeepEquals(valueA, valueB)) { + found = true; + break; + } else { + return false; + } + } + } + if (!found) { + return false; + } + } + return true; + } + if (a instanceof Double && b instanceof Double) { + return pigeonDoubleEquals((double) a, (double) b); + } + if (a instanceof Float && b instanceof Float) { + return pigeonFloatEquals((float) a, (float) b); + } + return a.equals(b); + } + + static int pigeonDeepHashCode(Object value) { + if (value == null) { + return 0; + } + if (value instanceof byte[]) { + return Arrays.hashCode((byte[]) value); + } + if (value instanceof int[]) { + return Arrays.hashCode((int[]) value); + } + if (value instanceof long[]) { + return Arrays.hashCode((long[]) value); + } + if (value instanceof double[]) { + double[] da = (double[]) value; + int result = 1; + for (double d : da) { + result = 31 * result + pigeonDoubleHashCode(d); + } + return result; + } + if (value instanceof List) { + int result = 1; + for (Object item : (List) value) { + result = 31 * result + pigeonDeepHashCode(item); + } + return result; + } + if (value instanceof Map) { + int result = 0; + for (Map.Entry entry : ((Map) value).entrySet()) { + result += + ((pigeonDeepHashCode(entry.getKey()) * 31) ^ pigeonDeepHashCode(entry.getValue())); + } + return result; + } + if (value instanceof Object[]) { + int result = 1; + for (Object item : (Object[]) value) { + result = 31 * result + pigeonDeepHashCode(item); + } + return result; + } + if (value instanceof Double) { + return pigeonDoubleHashCode((double) value); + } + if (value instanceof Float) { + return pigeonFloatHashCode((float) value); + } + return value.hashCode(); + } /** Error class for passing custom error details to Flutter via a thrown PlatformException. */ public static class FlutterError extends RuntimeException { @@ -142,15 +299,16 @@ public boolean equals(Object o) { return false; } MessageData that = (MessageData) o; - return Objects.equals(name, that.name) - && Objects.equals(description, that.description) - && code.equals(that.code) - && data.equals(that.data); + return pigeonDeepEquals(name, that.name) + && pigeonDeepEquals(description, that.description) + && pigeonDeepEquals(code, that.code) + && pigeonDeepEquals(data, that.data); } @Override public int hashCode() { - return Objects.hash(name, description, code, data); + Object[] fields = new Object[] {getClass(), name, description, code, data}; + return pigeonDeepHashCode(fields); } public static final class Builder { diff --git a/packages/pigeon/example/app/android/app/src/main/kotlin/dev/flutter/pigeon_example_app/EventChannelMessages.g.kt b/packages/pigeon/example/app/android/app/src/main/kotlin/dev/flutter/pigeon_example_app/EventChannelMessages.g.kt index d7ec9b6255cb..9029c9425018 100644 --- a/packages/pigeon/example/app/android/app/src/main/kotlin/dev/flutter/pigeon_example_app/EventChannelMessages.g.kt +++ b/packages/pigeon/example/app/android/app/src/main/kotlin/dev/flutter/pigeon_example_app/EventChannelMessages.g.kt @@ -13,7 +13,36 @@ import java.io.ByteArrayOutputStream import java.nio.ByteBuffer private object EventChannelMessagesPigeonUtils { + fun doubleEquals(a: Double, b: Double): Boolean { + // Normalize -0.0 to 0.0 and handle NaN equality. + return (if (a == 0.0) 0.0 else a) == (if (b == 0.0) 0.0 else b) || (a.isNaN() && b.isNaN()) + } + + fun floatEquals(a: Float, b: Float): Boolean { + // Normalize -0.0 to 0.0 and handle NaN equality. + return (if (a == 0.0f) 0.0f else a) == (if (b == 0.0f) 0.0f else b) || (a.isNaN() && b.isNaN()) + } + + fun doubleHash(d: Double): Int { + // Normalize -0.0 to 0.0 and handle NaN to ensure consistent hash codes. + val normalized = if (d == 0.0) 0.0 else d + val bits = java.lang.Double.doubleToLongBits(normalized) + return (bits xor (bits ushr 32)).toInt() + } + + fun floatHash(f: Float): Int { + // Normalize -0.0 to 0.0 and handle NaN to ensure consistent hash codes. + val normalized = if (f == 0.0f) 0.0f else f + return java.lang.Float.floatToIntBits(normalized) + } + fun deepEquals(a: Any?, b: Any?): Boolean { + if (a === b) { + return true + } + if (a == null || b == null) { + return false + } if (a is ByteArray && b is ByteArray) { return a.contentEquals(b) } @@ -24,20 +53,109 @@ private object EventChannelMessagesPigeonUtils { return a.contentEquals(b) } if (a is DoubleArray && b is DoubleArray) { - return a.contentEquals(b) + if (a.size != b.size) return false + for (i in a.indices) { + if (!doubleEquals(a[i], b[i])) return false + } + return true + } + if (a is FloatArray && b is FloatArray) { + if (a.size != b.size) return false + for (i in a.indices) { + if (!floatEquals(a[i], b[i])) return false + } + return true } if (a is Array<*> && b is Array<*>) { - return a.size == b.size && a.indices.all { deepEquals(a[it], b[it]) } + if (a.size != b.size) return false + for (i in a.indices) { + if (!deepEquals(a[i], b[i])) return false + } + return true } if (a is List<*> && b is List<*>) { - return a.size == b.size && a.indices.all { deepEquals(a[it], b[it]) } + if (a.size != b.size) return false + val iterA = a.iterator() + val iterB = b.iterator() + while (iterA.hasNext() && iterB.hasNext()) { + if (!deepEquals(iterA.next(), iterB.next())) return false + } + return true } if (a is Map<*, *> && b is Map<*, *>) { - return a.size == b.size && - a.all { (b as Map).contains(it.key) && deepEquals(it.value, b[it.key]) } + if (a.size != b.size) return false + for (entry in a) { + val key = entry.key + var found = false + for (bEntry in b) { + if (deepEquals(key, bEntry.key)) { + if (deepEquals(entry.value, bEntry.value)) { + found = true + break + } else { + return false + } + } + } + if (!found) return false + } + return true + } + if (a is Double && b is Double) { + return doubleEquals(a, b) + } + if (a is Float && b is Float) { + return floatEquals(a, b) } return a == b } + + fun deepHash(value: Any?): Int { + return when (value) { + null -> 0 + is ByteArray -> value.contentHashCode() + is IntArray -> value.contentHashCode() + is LongArray -> value.contentHashCode() + is DoubleArray -> { + var result = 1 + for (item in value) { + result = 31 * result + doubleHash(item) + } + result + } + is FloatArray -> { + var result = 1 + for (item in value) { + result = 31 * result + floatHash(item) + } + result + } + is Array<*> -> { + var result = 1 + for (item in value) { + result = 31 * result + deepHash(item) + } + result + } + is List<*> -> { + var result = 1 + for (item in value) { + result = 31 * result + deepHash(item) + } + result + } + is Map<*, *> -> { + var result = 0 + for (entry in value) { + result += ((deepHash(entry.key) * 31) xor deepHash(entry.value)) + } + result + } + is Double -> doubleHash(value) + is Float -> floatHash(value) + else -> value.hashCode() + } + } } /** @@ -61,16 +179,21 @@ data class IntEvent(val data: Long) : PlatformEvent() { } override fun equals(other: Any?): Boolean { - if (other !is IntEvent) { + if (other == null || other.javaClass != javaClass) { return false } if (this === other) { return true } - return EventChannelMessagesPigeonUtils.deepEquals(toList(), other.toList()) + val other = other as IntEvent + return EventChannelMessagesPigeonUtils.deepEquals(this.data, other.data) } - override fun hashCode(): Int = toList().hashCode() + override fun hashCode(): Int { + var result = javaClass.hashCode() + result = 31 * result + EventChannelMessagesPigeonUtils.deepHash(this.data) + return result + } } /** Generated class from Pigeon that represents data sent in messages. */ @@ -89,16 +212,21 @@ data class StringEvent(val data: String) : PlatformEvent() { } override fun equals(other: Any?): Boolean { - if (other !is StringEvent) { + if (other == null || other.javaClass != javaClass) { return false } if (this === other) { return true } - return EventChannelMessagesPigeonUtils.deepEquals(toList(), other.toList()) + val other = other as StringEvent + return EventChannelMessagesPigeonUtils.deepEquals(this.data, other.data) } - override fun hashCode(): Int = toList().hashCode() + override fun hashCode(): Int { + var result = javaClass.hashCode() + result = 31 * result + EventChannelMessagesPigeonUtils.deepHash(this.data) + return result + } } private open class EventChannelMessagesPigeonCodec : StandardMessageCodec() { @@ -186,4 +314,8 @@ abstract class StreamEventsStreamHandler : .setStreamHandler(internalStreamHandler) } } + // Implement methods from EventChannelMessagesPigeonEventChannelWrapper + override fun onListen(p0: Any?, sink: PigeonEventSink) {} + + override fun onCancel(p0: Any?) {} } diff --git a/packages/pigeon/example/app/android/app/src/main/kotlin/dev/flutter/pigeon_example_app/Messages.g.kt b/packages/pigeon/example/app/android/app/src/main/kotlin/dev/flutter/pigeon_example_app/Messages.g.kt index 87f4ef1acf12..f82200d46f0d 100644 --- a/packages/pigeon/example/app/android/app/src/main/kotlin/dev/flutter/pigeon_example_app/Messages.g.kt +++ b/packages/pigeon/example/app/android/app/src/main/kotlin/dev/flutter/pigeon_example_app/Messages.g.kt @@ -35,7 +35,36 @@ private object MessagesPigeonUtils { } } + fun doubleEquals(a: Double, b: Double): Boolean { + // Normalize -0.0 to 0.0 and handle NaN equality. + return (if (a == 0.0) 0.0 else a) == (if (b == 0.0) 0.0 else b) || (a.isNaN() && b.isNaN()) + } + + fun floatEquals(a: Float, b: Float): Boolean { + // Normalize -0.0 to 0.0 and handle NaN equality. + return (if (a == 0.0f) 0.0f else a) == (if (b == 0.0f) 0.0f else b) || (a.isNaN() && b.isNaN()) + } + + fun doubleHash(d: Double): Int { + // Normalize -0.0 to 0.0 and handle NaN to ensure consistent hash codes. + val normalized = if (d == 0.0) 0.0 else d + val bits = java.lang.Double.doubleToLongBits(normalized) + return (bits xor (bits ushr 32)).toInt() + } + + fun floatHash(f: Float): Int { + // Normalize -0.0 to 0.0 and handle NaN to ensure consistent hash codes. + val normalized = if (f == 0.0f) 0.0f else f + return java.lang.Float.floatToIntBits(normalized) + } + fun deepEquals(a: Any?, b: Any?): Boolean { + if (a === b) { + return true + } + if (a == null || b == null) { + return false + } if (a is ByteArray && b is ByteArray) { return a.contentEquals(b) } @@ -46,20 +75,109 @@ private object MessagesPigeonUtils { return a.contentEquals(b) } if (a is DoubleArray && b is DoubleArray) { - return a.contentEquals(b) + if (a.size != b.size) return false + for (i in a.indices) { + if (!doubleEquals(a[i], b[i])) return false + } + return true + } + if (a is FloatArray && b is FloatArray) { + if (a.size != b.size) return false + for (i in a.indices) { + if (!floatEquals(a[i], b[i])) return false + } + return true } if (a is Array<*> && b is Array<*>) { - return a.size == b.size && a.indices.all { deepEquals(a[it], b[it]) } + if (a.size != b.size) return false + for (i in a.indices) { + if (!deepEquals(a[i], b[i])) return false + } + return true } if (a is List<*> && b is List<*>) { - return a.size == b.size && a.indices.all { deepEquals(a[it], b[it]) } + if (a.size != b.size) return false + val iterA = a.iterator() + val iterB = b.iterator() + while (iterA.hasNext() && iterB.hasNext()) { + if (!deepEquals(iterA.next(), iterB.next())) return false + } + return true } if (a is Map<*, *> && b is Map<*, *>) { - return a.size == b.size && - a.all { (b as Map).contains(it.key) && deepEquals(it.value, b[it.key]) } + if (a.size != b.size) return false + for (entry in a) { + val key = entry.key + var found = false + for (bEntry in b) { + if (deepEquals(key, bEntry.key)) { + if (deepEquals(entry.value, bEntry.value)) { + found = true + break + } else { + return false + } + } + } + if (!found) return false + } + return true + } + if (a is Double && b is Double) { + return doubleEquals(a, b) + } + if (a is Float && b is Float) { + return floatEquals(a, b) } return a == b } + + fun deepHash(value: Any?): Int { + return when (value) { + null -> 0 + is ByteArray -> value.contentHashCode() + is IntArray -> value.contentHashCode() + is LongArray -> value.contentHashCode() + is DoubleArray -> { + var result = 1 + for (item in value) { + result = 31 * result + doubleHash(item) + } + result + } + is FloatArray -> { + var result = 1 + for (item in value) { + result = 31 * result + floatHash(item) + } + result + } + is Array<*> -> { + var result = 1 + for (item in value) { + result = 31 * result + deepHash(item) + } + result + } + is List<*> -> { + var result = 1 + for (item in value) { + result = 31 * result + deepHash(item) + } + result + } + is Map<*, *> -> { + var result = 0 + for (entry in value) { + result += ((deepHash(entry.key) * 31) xor deepHash(entry.value)) + } + result + } + is Double -> doubleHash(value) + is Float -> floatHash(value) + else -> value.hashCode() + } + } } /** @@ -113,16 +231,27 @@ data class MessageData( } override fun equals(other: Any?): Boolean { - if (other !is MessageData) { + if (other == null || other.javaClass != javaClass) { return false } if (this === other) { return true } - return MessagesPigeonUtils.deepEquals(toList(), other.toList()) + val other = other as MessageData + return MessagesPigeonUtils.deepEquals(this.name, other.name) && + MessagesPigeonUtils.deepEquals(this.description, other.description) && + MessagesPigeonUtils.deepEquals(this.code, other.code) && + MessagesPigeonUtils.deepEquals(this.data, other.data) } - override fun hashCode(): Int = toList().hashCode() + override fun hashCode(): Int { + var result = javaClass.hashCode() + result = 31 * result + MessagesPigeonUtils.deepHash(this.name) + result = 31 * result + MessagesPigeonUtils.deepHash(this.description) + result = 31 * result + MessagesPigeonUtils.deepHash(this.code) + result = 31 * result + MessagesPigeonUtils.deepHash(this.data) + return result + } } private open class MessagesPigeonCodec : StandardMessageCodec() { diff --git a/packages/pigeon/example/app/android/settings.gradle b/packages/pigeon/example/app/android/settings.gradle index 5320b13f9838..b9ca9c0ead08 100644 --- a/packages/pigeon/example/app/android/settings.gradle +++ b/packages/pigeon/example/app/android/settings.gradle @@ -18,10 +18,10 @@ 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.11.0" apply false - id "org.jetbrains.kotlin.android" version "2.2.0" apply false - id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1" + id "dev.flutter.flutter-plugin-loader" version "1.0.0" + id "com.android.application" version "8.11.1" apply false + id "org.jetbrains.kotlin.android" version "2.2.20" apply false + id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1" } diff --git a/packages/pigeon/example/app/ios/Flutter/AppFrameworkInfo.plist b/packages/pigeon/example/app/ios/Flutter/AppFrameworkInfo.plist index 7c5696400627..391a902b2beb 100644 --- a/packages/pigeon/example/app/ios/Flutter/AppFrameworkInfo.plist +++ b/packages/pigeon/example/app/ios/Flutter/AppFrameworkInfo.plist @@ -20,7 +20,5 @@ ???? CFBundleVersion 1.0 - MinimumOSVersion - 12.0 diff --git a/packages/pigeon/example/app/ios/Flutter/Debug.xcconfig b/packages/pigeon/example/app/ios/Flutter/Debug.xcconfig index ec97fc6f3021..592ceee85b89 100644 --- a/packages/pigeon/example/app/ios/Flutter/Debug.xcconfig +++ b/packages/pigeon/example/app/ios/Flutter/Debug.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" diff --git a/packages/pigeon/example/app/ios/Flutter/Release.xcconfig b/packages/pigeon/example/app/ios/Flutter/Release.xcconfig index c4855bfe2000..592ceee85b89 100644 --- a/packages/pigeon/example/app/ios/Flutter/Release.xcconfig +++ b/packages/pigeon/example/app/ios/Flutter/Release.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" diff --git a/packages/pigeon/example/app/ios/Podfile b/packages/pigeon/example/app/ios/Podfile deleted file mode 100644 index 01d4aa611bb9..000000000000 --- a/packages/pigeon/example/app/ios/Podfile +++ /dev/null @@ -1,40 +0,0 @@ -# Uncomment this line to define a global platform for your project -# platform :ios, '12.0' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_ios_podfile_setup - -target 'Runner' do - use_frameworks! - - flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_ios_build_settings(target) - end -end diff --git a/packages/pigeon/example/app/ios/Runner.xcodeproj/project.pbxproj b/packages/pigeon/example/app/ios/Runner.xcodeproj/project.pbxproj index 121307f17ef8..d35dbca6ab24 100644 --- a/packages/pigeon/example/app/ios/Runner.xcodeproj/project.pbxproj +++ b/packages/pigeon/example/app/ios/Runner.xcodeproj/project.pbxproj @@ -3,14 +3,13 @@ archiveVersion = 1; classes = { }; - objectVersion = 60; + objectVersion = 54; objects = { /* Begin PBXBuildFile section */ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; 3368472729F02D040090029A /* Messages.g.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3368472629F02D040090029A /* Messages.g.swift */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; - 3EE8794C275F32088AD591EB /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A650BDD6F68BD8FFBF3F1780 /* Pods_Runner.framework */; }; 474BFAAB2D01312700CB80BA /* EventChannelMessages.g.swift in Sources */ = {isa = PBXBuildFile; fileRef = 474BFAAA2D01312700CB80BA /* EventChannelMessages.g.swift */; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; @@ -35,12 +34,12 @@ /* Begin PBXFileReference section */ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; - 27CAC22A75533A4A7E343992 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; 3368472629F02D040090029A /* Messages.g.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Messages.g.swift; sourceTree = ""; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; 474BFAAA2D01312700CB80BA /* EventChannelMessages.g.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EventChannelMessages.g.swift; sourceTree = ""; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; @@ -49,9 +48,6 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - A650BDD6F68BD8FFBF3F1780 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - AE98FBE14AEFBBA591D3392B /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; - C9FCCD56B6FEFE59650B7D41 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -60,27 +56,15 @@ buildActionMask = 2147483647; files = ( 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, - 3EE8794C275F32088AD591EB /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 2DE1FB11A4049DEDD8609D3D /* Frameworks */ = { - isa = PBXGroup; - children = ( - A650BDD6F68BD8FFBF3F1780 /* Pods_Runner.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; 5AC2660E9756DE131CECB642 /* Pods */ = { isa = PBXGroup; children = ( - AE98FBE14AEFBBA591D3392B /* Pods-Runner.debug.xcconfig */, - 27CAC22A75533A4A7E343992 /* Pods-Runner.release.xcconfig */, - C9FCCD56B6FEFE59650B7D41 /* Pods-Runner.profile.xcconfig */, ); path = Pods; sourceTree = ""; @@ -88,6 +72,7 @@ 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, 9740EEB21CF90195004384FC /* Debug.xcconfig */, 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, @@ -103,7 +88,6 @@ 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, 5AC2660E9756DE131CECB642 /* Pods */, - 2DE1FB11A4049DEDD8609D3D /* Frameworks */, ); sourceTree = ""; }; @@ -139,7 +123,6 @@ isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - 11874A3E3724772837B0A747 /* [CP] Check Pods Manifest.lock */, 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, @@ -184,7 +167,7 @@ ); mainGroup = 97C146E51CF9000F007C117D; packageReferences = ( - 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */, ); productRefGroup = 97C146EF1CF9000F007C117D /* Products */; projectDirPath = ""; @@ -210,28 +193,6 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 11874A3E3724772837B0A747 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; @@ -340,7 +301,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -417,7 +378,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -466,7 +427,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -546,7 +507,7 @@ /* End XCConfigurationList section */ /* Begin XCLocalSwiftPackageReference section */ - 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = { + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */ = { isa = XCLocalSwiftPackageReference; relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; }; diff --git a/packages/pigeon/example/app/ios/Runner/EventChannelMessages.g.swift b/packages/pigeon/example/app/ios/Runner/EventChannelMessages.g.swift index 027453c3951e..70cab0a27bec 100644 --- a/packages/pigeon/example/app/ios/Runner/EventChannelMessages.g.swift +++ b/packages/pigeon/example/app/ios/Runner/EventChannelMessages.g.swift @@ -23,6 +23,19 @@ private func nilOrValue(_ value: Any?) -> T? { return value as! T? } +private func doubleEqualsEventChannelMessages(_ lhs: Double, _ rhs: Double) -> Bool { + return (lhs.isNaN && rhs.isNaN) || lhs == rhs +} + +private func doubleHashEventChannelMessages(_ value: Double, _ hasher: inout Hasher) { + if value.isNaN { + hasher.combine(0x7FF8_0000_0000_0000) + } else { + // Normalize -0.0 to 0.0 + hasher.combine(value == 0 ? 0 : value) + } +} + func deepEqualsEventChannelMessages(_ lhs: Any?, _ rhs: Any?) -> Bool { let cleanLhs = nilOrValue(lhs) as Any? let cleanRhs = nilOrValue(rhs) as Any? @@ -33,56 +46,90 @@ func deepEqualsEventChannelMessages(_ lhs: Any?, _ rhs: Any?) -> Bool { case (nil, _), (_, nil): return false - case is (Void, Void): + case (let lhs as AnyObject, let rhs as AnyObject) where lhs === rhs: return true - case let (cleanLhsHashable, cleanRhsHashable) as (AnyHashable, AnyHashable): - return cleanLhsHashable == cleanRhsHashable + case is (Void, Void): + return true - case let (cleanLhsArray, cleanRhsArray) as ([Any?], [Any?]): - guard cleanLhsArray.count == cleanRhsArray.count else { return false } - for (index, element) in cleanLhsArray.enumerated() { - if !deepEqualsEventChannelMessages(element, cleanRhsArray[index]) { + case (let lhsArray, let rhsArray) as ([Any?], [Any?]): + guard lhsArray.count == rhsArray.count else { return false } + for (index, element) in lhsArray.enumerated() { + if !deepEqualsEventChannelMessages(element, rhsArray[index]) { return false } } return true - case let (cleanLhsDictionary, cleanRhsDictionary) as ([AnyHashable: Any?], [AnyHashable: Any?]): - guard cleanLhsDictionary.count == cleanRhsDictionary.count else { return false } - for (key, cleanLhsValue) in cleanLhsDictionary { - guard cleanRhsDictionary.index(forKey: key) != nil else { return false } - if !deepEqualsEventChannelMessages(cleanLhsValue, cleanRhsDictionary[key]!) { + case (let lhsArray, let rhsArray) as ([Double], [Double]): + guard lhsArray.count == rhsArray.count else { return false } + for (index, element) in lhsArray.enumerated() { + if !doubleEqualsEventChannelMessages(element, rhsArray[index]) { return false } } return true + case (let lhsDictionary, let rhsDictionary) as ([AnyHashable: Any?], [AnyHashable: Any?]): + guard lhsDictionary.count == rhsDictionary.count else { return false } + for (lhsKey, lhsValue) in lhsDictionary { + var found = false + for (rhsKey, rhsValue) in rhsDictionary { + if deepEqualsEventChannelMessages(lhsKey, rhsKey) { + if deepEqualsEventChannelMessages(lhsValue, rhsValue) { + found = true + break + } else { + return false + } + } + } + if !found { return false } + } + return true + + case (let lhs as Double, let rhs as Double): + return doubleEqualsEventChannelMessages(lhs, rhs) + + case (let lhsHashable, let rhsHashable) as (AnyHashable, AnyHashable): + return lhsHashable == rhsHashable + default: - // Any other type shouldn't be able to be used with pigeon. File an issue if you find this to be untrue. return false } } func deepHashEventChannelMessages(value: Any?, hasher: inout Hasher) { - if let valueList = value as? [AnyHashable] { - for item in valueList { deepHashEventChannelMessages(value: item, hasher: &hasher) } - return - } - - if let valueDict = value as? [AnyHashable: AnyHashable] { - for key in valueDict.keys { - hasher.combine(key) - deepHashEventChannelMessages(value: valueDict[key]!, hasher: &hasher) + let cleanValue = nilOrValue(value) as Any? + if let cleanValue = cleanValue { + if let doubleValue = cleanValue as? Double { + doubleHashEventChannelMessages(doubleValue, &hasher) + } else if let valueList = cleanValue as? [Any?] { + for item in valueList { + deepHashEventChannelMessages(value: item, hasher: &hasher) + } + } else if let valueList = cleanValue as? [Double] { + for item in valueList { + doubleHashEventChannelMessages(item, &hasher) + } + } else if let valueDict = cleanValue as? [AnyHashable: Any?] { + var result = 0 + for (key, value) in valueDict { + var entryKeyHasher = Hasher() + deepHashEventChannelMessages(value: key, hasher: &entryKeyHasher) + var entryValueHasher = Hasher() + deepHashEventChannelMessages(value: value, hasher: &entryValueHasher) + result = result &+ ((entryKeyHasher.finalize() &* 31) ^ entryValueHasher.finalize()) + } + hasher.combine(result) + } else if let hashableValue = cleanValue as? AnyHashable { + hasher.combine(hashableValue) + } else { + hasher.combine(String(describing: cleanValue)) } - return + } else { + hasher.combine(0) } - - if let hashableValue = value as? AnyHashable { - hasher.combine(hashableValue.hashValue) - } - - return hasher.combine(String(describing: value)) } /// Generated class from Pigeon that represents data sent in messages. @@ -109,10 +156,15 @@ struct IntEvent: PlatformEvent { ] } static func == (lhs: IntEvent, rhs: IntEvent) -> Bool { - return deepEqualsEventChannelMessages(lhs.toList(), rhs.toList()) + if Swift.type(of: lhs) != Swift.type(of: rhs) { + return false + } + return deepEqualsEventChannelMessages(lhs.data, rhs.data) } + func hash(into hasher: inout Hasher) { - deepHashEventChannelMessages(value: toList(), hasher: &hasher) + hasher.combine("IntEvent") + deepHashEventChannelMessages(value: data, hasher: &hasher) } } @@ -134,10 +186,15 @@ struct StringEvent: PlatformEvent { ] } static func == (lhs: StringEvent, rhs: StringEvent) -> Bool { - return deepEqualsEventChannelMessages(lhs.toList(), rhs.toList()) + if Swift.type(of: lhs) != Swift.type(of: rhs) { + return false + } + return deepEqualsEventChannelMessages(lhs.data, rhs.data) } + func hash(into hasher: inout Hasher) { - deepHashEventChannelMessages(value: toList(), hasher: &hasher) + hasher.combine("StringEvent") + deepHashEventChannelMessages(value: data, hasher: &hasher) } } diff --git a/packages/pigeon/example/app/ios/Runner/Messages.g.swift b/packages/pigeon/example/app/ios/Runner/Messages.g.swift index 46c3e23598ef..f8b12f846c22 100644 --- a/packages/pigeon/example/app/ios/Runner/Messages.g.swift +++ b/packages/pigeon/example/app/ios/Runner/Messages.g.swift @@ -53,7 +53,7 @@ private func wrapError(_ error: Any) -> [Any?] { } return [ "\(error)", - "\(type(of: error))", + "\(Swift.type(of: error))", "Stacktrace: \(Thread.callStackSymbols)", ] } @@ -73,6 +73,19 @@ private func nilOrValue(_ value: Any?) -> T? { return value as! T? } +private func doubleEqualsMessages(_ lhs: Double, _ rhs: Double) -> Bool { + return (lhs.isNaN && rhs.isNaN) || lhs == rhs +} + +private func doubleHashMessages(_ value: Double, _ hasher: inout Hasher) { + if value.isNaN { + hasher.combine(0x7FF8_0000_0000_0000) + } else { + // Normalize -0.0 to 0.0 + hasher.combine(value == 0 ? 0 : value) + } +} + func deepEqualsMessages(_ lhs: Any?, _ rhs: Any?) -> Bool { let cleanLhs = nilOrValue(lhs) as Any? let cleanRhs = nilOrValue(rhs) as Any? @@ -83,56 +96,90 @@ func deepEqualsMessages(_ lhs: Any?, _ rhs: Any?) -> Bool { case (nil, _), (_, nil): return false - case is (Void, Void): + case (let lhs as AnyObject, let rhs as AnyObject) where lhs === rhs: return true - case let (cleanLhsHashable, cleanRhsHashable) as (AnyHashable, AnyHashable): - return cleanLhsHashable == cleanRhsHashable + case is (Void, Void): + return true - case let (cleanLhsArray, cleanRhsArray) as ([Any?], [Any?]): - guard cleanLhsArray.count == cleanRhsArray.count else { return false } - for (index, element) in cleanLhsArray.enumerated() { - if !deepEqualsMessages(element, cleanRhsArray[index]) { + case (let lhsArray, let rhsArray) as ([Any?], [Any?]): + guard lhsArray.count == rhsArray.count else { return false } + for (index, element) in lhsArray.enumerated() { + if !deepEqualsMessages(element, rhsArray[index]) { return false } } return true - case let (cleanLhsDictionary, cleanRhsDictionary) as ([AnyHashable: Any?], [AnyHashable: Any?]): - guard cleanLhsDictionary.count == cleanRhsDictionary.count else { return false } - for (key, cleanLhsValue) in cleanLhsDictionary { - guard cleanRhsDictionary.index(forKey: key) != nil else { return false } - if !deepEqualsMessages(cleanLhsValue, cleanRhsDictionary[key]!) { + case (let lhsArray, let rhsArray) as ([Double], [Double]): + guard lhsArray.count == rhsArray.count else { return false } + for (index, element) in lhsArray.enumerated() { + if !doubleEqualsMessages(element, rhsArray[index]) { return false } } return true + case (let lhsDictionary, let rhsDictionary) as ([AnyHashable: Any?], [AnyHashable: Any?]): + guard lhsDictionary.count == rhsDictionary.count else { return false } + for (lhsKey, lhsValue) in lhsDictionary { + var found = false + for (rhsKey, rhsValue) in rhsDictionary { + if deepEqualsMessages(lhsKey, rhsKey) { + if deepEqualsMessages(lhsValue, rhsValue) { + found = true + break + } else { + return false + } + } + } + if !found { return false } + } + return true + + case (let lhs as Double, let rhs as Double): + return doubleEqualsMessages(lhs, rhs) + + case (let lhsHashable, let rhsHashable) as (AnyHashable, AnyHashable): + return lhsHashable == rhsHashable + default: - // Any other type shouldn't be able to be used with pigeon. File an issue if you find this to be untrue. return false } } func deepHashMessages(value: Any?, hasher: inout Hasher) { - if let valueList = value as? [AnyHashable] { - for item in valueList { deepHashMessages(value: item, hasher: &hasher) } - return - } - - if let valueDict = value as? [AnyHashable: AnyHashable] { - for key in valueDict.keys { - hasher.combine(key) - deepHashMessages(value: valueDict[key]!, hasher: &hasher) + let cleanValue = nilOrValue(value) as Any? + if let cleanValue = cleanValue { + if let doubleValue = cleanValue as? Double { + doubleHashMessages(doubleValue, &hasher) + } else if let valueList = cleanValue as? [Any?] { + for item in valueList { + deepHashMessages(value: item, hasher: &hasher) + } + } else if let valueList = cleanValue as? [Double] { + for item in valueList { + doubleHashMessages(item, &hasher) + } + } else if let valueDict = cleanValue as? [AnyHashable: Any?] { + var result = 0 + for (key, value) in valueDict { + var entryKeyHasher = Hasher() + deepHashMessages(value: key, hasher: &entryKeyHasher) + var entryValueHasher = Hasher() + deepHashMessages(value: value, hasher: &entryValueHasher) + result = result &+ ((entryKeyHasher.finalize() &* 31) ^ entryValueHasher.finalize()) + } + hasher.combine(result) + } else if let hashableValue = cleanValue as? AnyHashable { + hasher.combine(hashableValue) + } else { + hasher.combine(String(describing: cleanValue)) } - return - } - - if let hashableValue = value as? AnyHashable { - hasher.combine(hashableValue.hashValue) + } else { + hasher.combine(0) } - - return hasher.combine(String(describing: value)) } enum Code: Int { @@ -170,10 +217,20 @@ struct MessageData: Hashable { ] } static func == (lhs: MessageData, rhs: MessageData) -> Bool { - return deepEqualsMessages(lhs.toList(), rhs.toList()) + if Swift.type(of: lhs) != Swift.type(of: rhs) { + return false + } + return deepEqualsMessages(lhs.name, rhs.name) + && deepEqualsMessages(lhs.description, rhs.description) + && deepEqualsMessages(lhs.code, rhs.code) && deepEqualsMessages(lhs.data, rhs.data) } + func hash(into hasher: inout Hasher) { - deepHashMessages(value: toList(), hasher: &hasher) + hasher.combine("MessageData") + deepHashMessages(value: name, hasher: &hasher) + deepHashMessages(value: description, hasher: &hasher) + deepHashMessages(value: code, hasher: &hasher) + deepHashMessages(value: data, hasher: &hasher) } } diff --git a/packages/pigeon/example/app/lib/main.dart b/packages/pigeon/example/app/lib/main.dart index fe1dfe9bf9d6..eeb193aa1f6a 100644 --- a/packages/pigeon/example/app/lib/main.dart +++ b/packages/pigeon/example/app/lib/main.dart @@ -74,7 +74,7 @@ class _MyHomePageState extends State { /// Sends message through host api using `MessageData` class /// and api `sendMessage` method. Future sendMessage(String messageText) { - final MessageData message = MessageData( + final message = MessageData( code: Code.one, data: {'header': 'this is a header'}, description: 'uri text', diff --git a/packages/pigeon/example/app/lib/src/event_channel_messages.g.dart b/packages/pigeon/example/app/lib/src/event_channel_messages.g.dart index 36df9a2ce33d..0a31f7b13d7c 100644 --- a/packages/pigeon/example/app/lib/src/event_channel_messages.g.dart +++ b/packages/pigeon/example/app/lib/src/event_channel_messages.g.dart @@ -3,15 +3,25 @@ // found in the LICENSE file. // Autogenerated from Pigeon, 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 +// ignore_for_file: unused_import, unused_shown_name +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, omit_obvious_local_variable_types, unnecessary_import, no_leading_underscores_for_local_identifiers import 'dart:async'; -import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; +import 'dart:typed_data' show Float64List, Int32List, Int64List; -import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; +import 'package:meta/meta.dart' show immutable, protected, visibleForTesting; bool _deepEquals(Object? a, Object? b) { + if (identical(a, b)) { + return true; + } + if (a is double && b is double) { + if (a.isNaN && b.isNaN) { + return true; + } + return a == b; + } if (a is List && b is List) { return a.length == b.length && a.indexed.every( @@ -19,16 +29,52 @@ bool _deepEquals(Object? a, Object? b) { ); } if (a is Map && b is Map) { - return a.length == b.length && - a.entries.every( - (MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key]), - ); + if (a.length != b.length) { + return false; + } + for (final MapEntry entryA in a.entries) { + bool found = false; + for (final MapEntry entryB in b.entries) { + if (_deepEquals(entryA.key, entryB.key)) { + if (_deepEquals(entryA.value, entryB.value)) { + found = true; + break; + } else { + return false; + } + } + } + if (!found) { + return false; + } + } + return true; } return a == b; } +int _deepHash(Object? value) { + if (value is List) { + return Object.hashAll(value.map(_deepHash)); + } + if (value is Map) { + int result = 0; + for (final MapEntry entry in value.entries) { + result += (_deepHash(entry.key) * 31) ^ _deepHash(entry.value); + } + return result; + } + if (value is double && value.isNaN) { + // Normalize NaN to a consistent hash. + return 0x7FF8000000000000.hashCode; + } + if (value is double && value == 0.0) { + // Normalize -0.0 to 0.0 so they have the same hash code. + return 0.0.hashCode; + } + return value.hashCode; +} + sealed class PlatformEvent {} class IntEvent extends PlatformEvent { @@ -58,12 +104,12 @@ class IntEvent extends PlatformEvent { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(data, other.data); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } class StringEvent extends PlatformEvent { @@ -93,12 +139,12 @@ class StringEvent extends PlatformEvent { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(data, other.data); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } class _PigeonCodec extends StandardMessageCodec { diff --git a/packages/pigeon/example/app/lib/src/messages.g.dart b/packages/pigeon/example/app/lib/src/messages.g.dart index a1707968cf71..9efe3e125b07 100644 --- a/packages/pigeon/example/app/lib/src/messages.g.dart +++ b/packages/pigeon/example/app/lib/src/messages.g.dart @@ -3,19 +3,38 @@ // found in the LICENSE file. // Autogenerated from Pigeon, 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 +// ignore_for_file: unused_import, unused_shown_name +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, omit_obvious_local_variable_types, unnecessary_import, no_leading_underscores_for_local_identifiers import 'dart:async'; -import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; +import 'dart:typed_data' show Float64List, Int32List, Int64List; -import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; +import 'package:meta/meta.dart' show immutable, protected, visibleForTesting; -PlatformException _createConnectionError(String channelName) { - return PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel: "$channelName".', - ); +Object? _extractReplyValueOrThrow( + List? replyList, + String channelName, { + required bool isNullValid, +}) { + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel: "$channelName".', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (!isNullValid && (replyList.isNotEmpty && replyList[0] == null)) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } + return replyList.firstOrNull; } List wrapResponse({ @@ -33,6 +52,15 @@ List wrapResponse({ } bool _deepEquals(Object? a, Object? b) { + if (identical(a, b)) { + return true; + } + if (a is double && b is double) { + if (a.isNaN && b.isNaN) { + return true; + } + return a == b; + } if (a is List && b is List) { return a.length == b.length && a.indexed.every( @@ -40,16 +68,52 @@ bool _deepEquals(Object? a, Object? b) { ); } if (a is Map && b is Map) { - return a.length == b.length && - a.entries.every( - (MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key]), - ); + if (a.length != b.length) { + return false; + } + for (final MapEntry entryA in a.entries) { + bool found = false; + for (final MapEntry entryB in b.entries) { + if (_deepEquals(entryA.key, entryB.key)) { + if (_deepEquals(entryA.value, entryB.value)) { + found = true; + break; + } else { + return false; + } + } + } + if (!found) { + return false; + } + } + return true; } return a == b; } +int _deepHash(Object? value) { + if (value is List) { + return Object.hashAll(value.map(_deepHash)); + } + if (value is Map) { + int result = 0; + for (final MapEntry entry in value.entries) { + result += (_deepHash(entry.key) * 31) ^ _deepHash(entry.value); + } + return result; + } + if (value is double && value.isNaN) { + // Normalize NaN to a consistent hash. + return 0x7FF8000000000000.hashCode; + } + if (value is double && value == 0.0) { + // Normalize -0.0 to 0.0 so they have the same hash code. + return 0.0.hashCode; + } + return value.hashCode; +} + enum Code { one, two } class MessageData { @@ -82,7 +146,7 @@ class MessageData { name: result[0] as String?, description: result[1] as String?, code: result[2]! as Code, - data: (result[3] as Map?)!.cast(), + data: (result[3]! as Map).cast(), ); } @@ -95,12 +159,15 @@ class MessageData { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(name, other.name) && + _deepEquals(description, other.description) && + _deepEquals(code, other.code) && + _deepEquals(data, other.data); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } class _PigeonCodec extends StandardMessageCodec { @@ -125,7 +192,7 @@ class _PigeonCodec extends StandardMessageCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 129: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : Code.values[value]; case 130: return MessageData.decode(readValue(buffer)!); @@ -153,97 +220,64 @@ class ExampleHostApi { final String pigeonVar_messageChannelSuffix; Future getHostLanguage() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.getHostLanguage$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as String; } Future add(int a, int b) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.add$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [a, b], ); - 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 int?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as int; } Future sendMessage(MessageData message) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.sendMessage$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [message], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as bool; } } @@ -261,8 +295,7 @@ abstract class MessageFlutterApi { ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_example_package.MessageFlutterApi.flutterMethod$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -271,12 +304,8 @@ abstract class MessageFlutterApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_example_package.MessageFlutterApi.flutterMethod was null.', - ); - final List args = (message as List?)!; - final String? arg_aString = (args[0] as String?); + final List args = message! as List; + final String? arg_aString = args[0] as String?; try { final String output = api.flutterMethod(arg_aString); return wrapResponse(result: output); diff --git a/packages/pigeon/example/app/linux/messages.g.cc b/packages/pigeon/example/app/linux/messages.g.cc index 5dc179e4203a..f1b0e818d11f 100644 --- a/packages/pigeon/example/app/linux/messages.g.cc +++ b/packages/pigeon/example/app/linux/messages.g.cc @@ -6,6 +6,197 @@ #include "messages.g.h" +#include + +#include +static guint G_GNUC_UNUSED flpigeon_hash_double(double v) { + if (std::isnan(v)) { + return static_cast(0x7FF80000); + } + if (v == 0.0) { + v = 0.0; + } + union { + double d; + uint64_t u; + } u; + u.d = v; + return static_cast(u.u ^ (u.u >> 32)); +} +static gboolean G_GNUC_UNUSED flpigeon_equals_double(double a, double b) { + return (a == b) || (std::isnan(a) && std::isnan(b)); +} +static gboolean G_GNUC_UNUSED flpigeon_deep_equals(FlValue* a, FlValue* b) { + if (a == b) { + return TRUE; + } + if (a == nullptr || b == nullptr) { + return FALSE; + } + if (fl_value_get_type(a) != fl_value_get_type(b)) { + return FALSE; + } + switch (fl_value_get_type(a)) { + case FL_VALUE_TYPE_NULL: + return TRUE; + case FL_VALUE_TYPE_BOOL: + return fl_value_get_bool(a) == fl_value_get_bool(b); + case FL_VALUE_TYPE_INT: + return fl_value_get_int(a) == fl_value_get_int(b); + case FL_VALUE_TYPE_FLOAT: { + return flpigeon_equals_double(fl_value_get_float(a), + fl_value_get_float(b)); + } + case FL_VALUE_TYPE_STRING: + return g_strcmp0(fl_value_get_string(a), fl_value_get_string(b)) == 0; + case FL_VALUE_TYPE_UINT8_LIST: + return fl_value_get_length(a) == fl_value_get_length(b) && + memcmp(fl_value_get_uint8_list(a), fl_value_get_uint8_list(b), + fl_value_get_length(a)) == 0; + case FL_VALUE_TYPE_INT32_LIST: + return fl_value_get_length(a) == fl_value_get_length(b) && + memcmp(fl_value_get_int32_list(a), fl_value_get_int32_list(b), + fl_value_get_length(a) * sizeof(int32_t)) == 0; + case FL_VALUE_TYPE_INT64_LIST: + return fl_value_get_length(a) == fl_value_get_length(b) && + memcmp(fl_value_get_int64_list(a), fl_value_get_int64_list(b), + fl_value_get_length(a) * sizeof(int64_t)) == 0; + case FL_VALUE_TYPE_FLOAT_LIST: { + size_t len = fl_value_get_length(a); + if (len != fl_value_get_length(b)) { + return FALSE; + } + const double* a_data = fl_value_get_float_list(a); + const double* b_data = fl_value_get_float_list(b); + for (size_t i = 0; i < len; i++) { + if (!flpigeon_equals_double(a_data[i], b_data[i])) { + return FALSE; + } + } + return TRUE; + } + case FL_VALUE_TYPE_LIST: { + size_t len = fl_value_get_length(a); + if (len != fl_value_get_length(b)) { + return FALSE; + } + for (size_t i = 0; i < len; i++) { + if (!flpigeon_deep_equals(fl_value_get_list_value(a, i), + fl_value_get_list_value(b, i))) { + return FALSE; + } + } + return TRUE; + } + case FL_VALUE_TYPE_MAP: { + size_t len = fl_value_get_length(a); + if (len != fl_value_get_length(b)) { + return FALSE; + } + for (size_t i = 0; i < len; i++) { + FlValue* key = fl_value_get_map_key(a, i); + FlValue* val = fl_value_get_map_value(a, i); + gboolean found = FALSE; + for (size_t j = 0; j < len; j++) { + FlValue* b_key = fl_value_get_map_key(b, j); + if (flpigeon_deep_equals(key, b_key)) { + FlValue* b_val = fl_value_get_map_value(b, j); + if (flpigeon_deep_equals(val, b_val)) { + found = TRUE; + break; + } else { + return FALSE; + } + } + } + if (!found) { + return FALSE; + } + } + return TRUE; + } + default: + return FALSE; + } + return FALSE; +} +static guint G_GNUC_UNUSED flpigeon_deep_hash(FlValue* value) { + if (value == nullptr) { + return 0; + } + switch (fl_value_get_type(value)) { + case FL_VALUE_TYPE_NULL: + return 0; + case FL_VALUE_TYPE_BOOL: + return fl_value_get_bool(value) ? 1231 : 1237; + case FL_VALUE_TYPE_INT: { + int64_t v = fl_value_get_int(value); + return static_cast(v ^ (v >> 32)); + } + case FL_VALUE_TYPE_FLOAT: + return flpigeon_hash_double(fl_value_get_float(value)); + case FL_VALUE_TYPE_STRING: + return g_str_hash(fl_value_get_string(value)); + case FL_VALUE_TYPE_UINT8_LIST: { + guint result = 1; + size_t len = fl_value_get_length(value); + const uint8_t* data = fl_value_get_uint8_list(value); + for (size_t i = 0; i < len; i++) { + result = result * 31 + data[i]; + } + return result; + } + case FL_VALUE_TYPE_INT32_LIST: { + guint result = 1; + size_t len = fl_value_get_length(value); + const int32_t* data = fl_value_get_int32_list(value); + for (size_t i = 0; i < len; i++) { + result = result * 31 + static_cast(data[i]); + } + return result; + } + case FL_VALUE_TYPE_INT64_LIST: { + guint result = 1; + size_t len = fl_value_get_length(value); + const int64_t* data = fl_value_get_int64_list(value); + for (size_t i = 0; i < len; i++) { + result = result * 31 + static_cast(data[i] ^ (data[i] >> 32)); + } + return result; + } + case FL_VALUE_TYPE_FLOAT_LIST: { + guint result = 1; + size_t len = fl_value_get_length(value); + const double* data = fl_value_get_float_list(value); + for (size_t i = 0; i < len; i++) { + result = result * 31 + flpigeon_hash_double(data[i]); + } + return result; + } + case FL_VALUE_TYPE_LIST: { + guint result = 1; + size_t len = fl_value_get_length(value); + for (size_t i = 0; i < len; i++) { + result = + result * 31 + flpigeon_deep_hash(fl_value_get_list_value(value, i)); + } + return result; + } + case FL_VALUE_TYPE_MAP: { + guint result = 0; + size_t len = fl_value_get_length(value); + for (size_t i = 0; i < len; i++) { + result += ((flpigeon_deep_hash(fl_value_get_map_key(value, i)) * 31) ^ + flpigeon_deep_hash(fl_value_get_map_value(value, i))); + } + return result; + } + default: + return static_cast(fl_value_get_type(value)); + } + return 0; +} + struct _PigeonExamplePackageMessageData { GObject parent_instance; @@ -119,6 +310,41 @@ pigeon_example_package_message_data_new_from_list(FlValue* values) { return pigeon_example_package_message_data_new(name, description, code, data); } +gboolean pigeon_example_package_message_data_equals( + PigeonExamplePackageMessageData* a, PigeonExamplePackageMessageData* b) { + if (a == b) { + return TRUE; + } + if (a == nullptr || b == nullptr) { + return FALSE; + } + if (g_strcmp0(a->name, b->name) != 0) { + return FALSE; + } + if (g_strcmp0(a->description, b->description) != 0) { + return FALSE; + } + if (a->code != b->code) { + return FALSE; + } + if (!flpigeon_deep_equals(a->data, b->data)) { + return FALSE; + } + return TRUE; +} + +guint pigeon_example_package_message_data_hash( + PigeonExamplePackageMessageData* self) { + g_return_val_if_fail(PIGEON_EXAMPLE_PACKAGE_IS_MESSAGE_DATA(self), 0); + guint result = 0; + result = result * 31 + (self->name != nullptr ? g_str_hash(self->name) : 0); + result = result * 31 + + (self->description != nullptr ? g_str_hash(self->description) : 0); + result = result * 31 + static_cast(self->code); + result = result * 31 + flpigeon_deep_hash(self->data); + return result; +} + struct _PigeonExamplePackageMessageCodec { FlStandardMessageCodec parent_instance; }; diff --git a/packages/pigeon/example/app/linux/messages.g.h b/packages/pigeon/example/app/linux/messages.g.h index 6fb44cc93516..c03ecb20a01d 100644 --- a/packages/pigeon/example/app/linux/messages.g.h +++ b/packages/pigeon/example/app/linux/messages.g.h @@ -90,6 +90,29 @@ PigeonExamplePackageCode pigeon_example_package_message_data_get_code( FlValue* pigeon_example_package_message_data_get_data( PigeonExamplePackageMessageData* object); +/** + * pigeon_example_package_message_data_equals: + * @a: a #PigeonExamplePackageMessageData. + * @b: another #PigeonExamplePackageMessageData. + * + * Checks if two #PigeonExamplePackageMessageData objects are equal. + * + * Returns: TRUE if @a and @b are equal. + */ +gboolean pigeon_example_package_message_data_equals( + PigeonExamplePackageMessageData* a, PigeonExamplePackageMessageData* b); + +/** + * pigeon_example_package_message_data_hash: + * @object: a #PigeonExamplePackageMessageData. + * + * Calculates a hash code for a #PigeonExamplePackageMessageData object. + * + * Returns: the hash code. + */ +guint pigeon_example_package_message_data_hash( + PigeonExamplePackageMessageData* object); + G_DECLARE_FINAL_TYPE(PigeonExamplePackageMessageCodec, pigeon_example_package_message_codec, PIGEON_EXAMPLE_PACKAGE, MESSAGE_CODEC, diff --git a/packages/pigeon/example/app/macos/Flutter/Flutter-Debug.xcconfig b/packages/pigeon/example/app/macos/Flutter/Flutter-Debug.xcconfig index 4b81f9b2d200..c2efd0b608ba 100644 --- a/packages/pigeon/example/app/macos/Flutter/Flutter-Debug.xcconfig +++ b/packages/pigeon/example/app/macos/Flutter/Flutter-Debug.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" diff --git a/packages/pigeon/example/app/macos/Flutter/Flutter-Release.xcconfig b/packages/pigeon/example/app/macos/Flutter/Flutter-Release.xcconfig index 5caa9d1579e4..c2efd0b608ba 100644 --- a/packages/pigeon/example/app/macos/Flutter/Flutter-Release.xcconfig +++ b/packages/pigeon/example/app/macos/Flutter/Flutter-Release.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" diff --git a/packages/pigeon/example/app/macos/Podfile b/packages/pigeon/example/app/macos/Podfile deleted file mode 100644 index ae77cc1d4269..000000000000 --- a/packages/pigeon/example/app/macos/Podfile +++ /dev/null @@ -1,39 +0,0 @@ -platform :osx, '10.14' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\"" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_macos_podfile_setup - -target 'Runner' do - use_frameworks! - - flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__)) -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_macos_build_settings(target) - end -end diff --git a/packages/pigeon/example/app/macos/Runner.xcodeproj/project.pbxproj b/packages/pigeon/example/app/macos/Runner.xcodeproj/project.pbxproj index ac0c3358e4c3..c175252ead73 100644 --- a/packages/pigeon/example/app/macos/Runner.xcodeproj/project.pbxproj +++ b/packages/pigeon/example/app/macos/Runner.xcodeproj/project.pbxproj @@ -27,7 +27,6 @@ 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; - FE4D972A28C4B251F843526C /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 32CC79C72C76529428DDC41C /* Pods_Runner.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -54,7 +53,6 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 32CC79C72C76529428DDC41C /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; 3368472429F02AAC0090029A /* Messages.g.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = Messages.g.swift; path = ../../ios/Runner/Messages.g.swift; sourceTree = ""; }; @@ -70,11 +68,8 @@ 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; - 4891FB202295F11C6F60A6FC /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; - A31DF385E5E70E8894046AC3 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; - F4D94E001BD74D8D03893EC5 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -82,7 +77,6 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - FE4D972A28C4B251F843526C /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -106,8 +100,6 @@ 33FAB671232836740065AC1E /* Runner */, 33CEB47122A05771004F2AC0 /* Flutter */, 33CC10EE2044A3C60003C045 /* Products */, - D73912EC22F37F3D000D13A0 /* Frameworks */, - B56E624D6807F2D1E8C4EA7C /* Pods */, ); sourceTree = ""; }; @@ -155,25 +147,6 @@ path = Runner; sourceTree = ""; }; - B56E624D6807F2D1E8C4EA7C /* Pods */ = { - isa = PBXGroup; - children = ( - A31DF385E5E70E8894046AC3 /* Pods-Runner.debug.xcconfig */, - F4D94E001BD74D8D03893EC5 /* Pods-Runner.release.xcconfig */, - 4891FB202295F11C6F60A6FC /* Pods-Runner.profile.xcconfig */, - ); - name = Pods; - path = Pods; - sourceTree = ""; - }; - D73912EC22F37F3D000D13A0 /* Frameworks */ = { - isa = PBXGroup; - children = ( - 32CC79C72C76529428DDC41C /* Pods_Runner.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -181,7 +154,6 @@ isa = PBXNativeTarget; buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - 4901B19C7FAADB635D77080B /* [CP] Check Pods Manifest.lock */, 33CC10E92044A3C60003C045 /* Sources */, 33CC10EA2044A3C60003C045 /* Frameworks */, 33CC10EB2044A3C60003C045 /* Resources */, @@ -294,28 +266,6 @@ shellPath = /bin/sh; shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; }; - 4901B19C7FAADB635D77080B /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -391,7 +341,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; + MACOSX_DEPLOYMENT_TARGET = 10.15; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; @@ -470,7 +420,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; + MACOSX_DEPLOYMENT_TARGET = 10.15; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = macosx; @@ -517,7 +467,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; + MACOSX_DEPLOYMENT_TARGET = 10.15; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; diff --git a/packages/pigeon/example/app/macos/Runner/messages.g.h b/packages/pigeon/example/app/macos/Runner/messages.g.h index de6b076dfb3c..c44b9361e8b9 100644 --- a/packages/pigeon/example/app/macos/Runner/messages.g.h +++ b/packages/pigeon/example/app/macos/Runner/messages.g.h @@ -4,7 +4,7 @@ // Autogenerated from Pigeon, do not edit directly. // See also: https://pub.dev/packages/pigeon -#import +@import Foundation; @protocol FlutterBinaryMessenger; @protocol FlutterMessageCodec; diff --git a/packages/pigeon/example/app/macos/Runner/messages.g.m b/packages/pigeon/example/app/macos/Runner/messages.g.m index 661dc4e54499..ed7655039d25 100644 --- a/packages/pigeon/example/app/macos/Runner/messages.g.m +++ b/packages/pigeon/example/app/macos/Runner/messages.g.m @@ -7,14 +7,101 @@ #import "messages.g.h" #if TARGET_OS_OSX -#import +@import FlutterMacOS; #else -#import +@import Flutter; #endif -#if !__has_feature(objc_arc) -#error File requires ARC to be enabled. -#endif +static BOOL __attribute__((unused)) FLTPigeonDeepEquals(id _Nullable a, id _Nullable b) { + if (a == b) { + return YES; + } + if (a == nil) { + return b == [NSNull null]; + } + if (b == nil) { + return a == [NSNull null]; + } + if ([a isKindOfClass:[NSNumber class]] && [b isKindOfClass:[NSNumber class]]) { + return + [a isEqual:b] || (isnan([(NSNumber *)a doubleValue]) && isnan([(NSNumber *)b doubleValue])); + } + if ([a isKindOfClass:[NSArray class]] && [b isKindOfClass:[NSArray class]]) { + NSArray *arrayA = (NSArray *)a; + NSArray *arrayB = (NSArray *)b; + if (arrayA.count != arrayB.count) { + return NO; + } + for (NSUInteger i = 0; i < arrayA.count; i++) { + if (!FLTPigeonDeepEquals(arrayA[i], arrayB[i])) { + return NO; + } + } + return YES; + } + if ([a isKindOfClass:[NSDictionary class]] && [b isKindOfClass:[NSDictionary class]]) { + NSDictionary *dictA = (NSDictionary *)a; + NSDictionary *dictB = (NSDictionary *)b; + if (dictA.count != dictB.count) { + return NO; + } + for (id keyA in dictA) { + id valueA = dictA[keyA]; + BOOL found = NO; + for (id keyB in dictB) { + if (FLTPigeonDeepEquals(keyA, keyB)) { + id valueB = dictB[keyB]; + if (FLTPigeonDeepEquals(valueA, valueB)) { + found = YES; + break; + } else { + return NO; + } + } + } + if (!found) { + return NO; + } + } + return YES; + } + return [a isEqual:b]; +} + +static NSUInteger __attribute__((unused)) FLTPigeonDeepHash(id _Nullable value) { + if (value == nil || value == (id)[NSNull null]) { + return 0; + } + if ([value isKindOfClass:[NSNumber class]]) { + NSNumber *n = (NSNumber *)value; + double d = n.doubleValue; + if (isnan(d)) { + // Normalize NaN to a consistent hash. + return (NSUInteger)0x7FF8000000000000; + } + if (d == 0.0) { + // Normalize -0.0 to 0.0 so they have the same hash code. + d = 0.0; + } + return @(d).hash; + } + if ([value isKindOfClass:[NSArray class]]) { + NSUInteger result = 1; + for (id item in (NSArray *)value) { + result = result * 31 + FLTPigeonDeepHash(item); + } + return result; + } + if ([value isKindOfClass:[NSDictionary class]]) { + NSUInteger result = 0; + NSDictionary *dict = (NSDictionary *)value; + for (id key in dict) { + result += ((FLTPigeonDeepHash(key) * 31) ^ FLTPigeonDeepHash(dict[key])); + } + return result; + } + return [value hash]; +} static NSArray *wrapResult(id result, FlutterError *error) { if (error) { @@ -87,6 +174,27 @@ + (nullable PGNMessageData *)nullableFromList:(NSArray *)list { self.data ?: [NSNull null], ]; } +- (BOOL)isEqual:(id)object { + if (self == object) { + return YES; + } + if (![object isKindOfClass:[self class]]) { + return NO; + } + PGNMessageData *other = (PGNMessageData *)object; + return FLTPigeonDeepEquals(self.name, other.name) && + FLTPigeonDeepEquals(self.description, other.description) && self.code == other.code && + FLTPigeonDeepEquals(self.data, other.data); +} + +- (NSUInteger)hash { + NSUInteger result = [self class].hash; + result = result * 31 + FLTPigeonDeepHash(self.name); + result = result * 31 + FLTPigeonDeepHash(self.description); + result = result * 31 + @(self.code).hash; + result = result * 31 + FLTPigeonDeepHash(self.data); + return result; +} @end @interface PGNMessagesPigeonCodecReader : FlutterStandardReader diff --git a/packages/pigeon/example/app/pigeons/event_channel_messages.dart b/packages/pigeon/example/app/pigeons/event_channel_messages.dart index 388b327155b2..c786e8204f9a 100644 --- a/packages/pigeon/example/app/pigeons/event_channel_messages.dart +++ b/packages/pigeon/example/app/pigeons/event_channel_messages.dart @@ -7,7 +7,7 @@ import 'package:pigeon/pigeon.dart'; @ConfigurePigeon( PigeonOptions( dartOut: 'lib/src/event_channel_messages.g.dart', - dartOptions: DartOptions(), + dartOptions: DartOptions(ignoreLints: false), cppOptions: CppOptions(namespace: 'pigeon_example'), kotlinOut: 'android/app/src/main/kotlin/dev/flutter/pigeon_example_app/EventChannelMessages.g.kt', diff --git a/packages/pigeon/example/app/windows/runner/messages.g.cpp b/packages/pigeon/example/app/windows/runner/messages.g.cpp index 755efbc8570b..11453da4e053 100644 --- a/packages/pigeon/example/app/windows/runner/messages.g.cpp +++ b/packages/pigeon/example/app/windows/runner/messages.g.cpp @@ -13,16 +13,18 @@ #include #include +#include +#include #include #include #include namespace pigeon_example { -using flutter::BasicMessageChannel; -using flutter::CustomEncodableValue; -using flutter::EncodableList; -using flutter::EncodableMap; -using flutter::EncodableValue; +using ::flutter::BasicMessageChannel; +using ::flutter::CustomEncodableValue; +using ::flutter::EncodableList; +using ::flutter::EncodableMap; +using ::flutter::EncodableValue; FlutterError CreateConnectionError(const std::string channel_name) { return FlutterError( @@ -31,6 +33,212 @@ FlutterError CreateConnectionError(const std::string channel_name) { EncodableValue("")); } +namespace { +template +bool PigeonInternalDeepEquals(const T& a, const T& b); + +bool PigeonInternalDeepEquals(const double& a, const double& b); + +template +bool PigeonInternalDeepEquals(const std::vector& a, const std::vector& b); + +template +bool PigeonInternalDeepEquals(const std::map& a, const std::map& b); + +template +bool PigeonInternalDeepEquals(const std::optional& a, + const std::optional& b); + +template +bool PigeonInternalDeepEquals(const std::unique_ptr& a, + const std::unique_ptr& b); + +bool PigeonInternalDeepEquals(const ::flutter::EncodableValue& a, + const ::flutter::EncodableValue& b); + +template +bool PigeonInternalDeepEquals(const T& a, const T& b) { + return a == b; +} + +template +bool PigeonInternalDeepEquals(const std::vector& a, + const std::vector& b) { + if (a.size() != b.size()) { + return false; + } + for (size_t i = 0; i < a.size(); ++i) { + if (!PigeonInternalDeepEquals(a[i], b[i])) { + return false; + } + } + return true; +} + +template +bool PigeonInternalDeepEquals(const std::map& a, + const std::map& b) { + if (a.size() != b.size()) { + return false; + } + for (const auto& kv : a) { + bool found = false; + for (const auto& b_kv : b) { + if (PigeonInternalDeepEquals(kv.first, b_kv.first)) { + if (PigeonInternalDeepEquals(kv.second, b_kv.second)) { + found = true; + break; + } else { + return false; + } + } + } + if (!found) { + return false; + } + } + return true; +} + +bool PigeonInternalDeepEquals(const double& a, const double& b) { + // Normalize -0.0 to 0.0 and handle NaN equality. + return (a == b) || (std::isnan(a) && std::isnan(b)); +} + +template +bool PigeonInternalDeepEquals(const std::optional& a, + const std::optional& b) { + if (!a && !b) { + return true; + } + if (!a || !b) { + return false; + } + return PigeonInternalDeepEquals(*a, *b); +} + +template +bool PigeonInternalDeepEquals(const std::unique_ptr& a, + const std::unique_ptr& b) { + if (a.get() == b.get()) { + return true; + } + if (!a || !b) { + return false; + } + return PigeonInternalDeepEquals(*a, *b); +} + +bool PigeonInternalDeepEquals(const ::flutter::EncodableValue& a, + const ::flutter::EncodableValue& b) { + if (a.index() != b.index()) { + return false; + } + if (const double* da = std::get_if(&a)) { + return PigeonInternalDeepEquals(*da, std::get(b)); + } else if (const ::flutter::EncodableList* la = + std::get_if<::flutter::EncodableList>(&a)) { + return PigeonInternalDeepEquals(*la, std::get<::flutter::EncodableList>(b)); + } else if (const ::flutter::EncodableMap* ma = + std::get_if<::flutter::EncodableMap>(&a)) { + return PigeonInternalDeepEquals(*ma, std::get<::flutter::EncodableMap>(b)); + } + return a == b; +} + +template +size_t PigeonInternalDeepHash(const T& v); + +size_t PigeonInternalDeepHash(const double& v); + +template +size_t PigeonInternalDeepHash(const std::vector& v); + +template +size_t PigeonInternalDeepHash(const std::map& v); + +template +size_t PigeonInternalDeepHash(const std::optional& v); + +template +size_t PigeonInternalDeepHash(const std::unique_ptr& v); + +size_t PigeonInternalDeepHash(const ::flutter::EncodableValue& v); + +template +size_t PigeonInternalDeepHash(const T& v) { + return std::hash()(v); +} + +template +size_t PigeonInternalDeepHash(const std::vector& v) { + size_t result = 1; + for (const auto& item : v) { + result = result * 31 + PigeonInternalDeepHash(item); + } + return result; +} + +template +size_t PigeonInternalDeepHash(const std::map& v) { + size_t result = 0; + for (const auto& kv : v) { + result += ((PigeonInternalDeepHash(kv.first) * 31) ^ + PigeonInternalDeepHash(kv.second)); + } + return result; +} + +size_t PigeonInternalDeepHash(const double& v) { + if (std::isnan(v)) { + // Normalize NaN to a consistent hash. + return std::hash()(std::numeric_limits::quiet_NaN()); + } + if (v == 0.0) { + // Normalize -0.0 to 0.0 so they have the same hash code. + return std::hash()(0.0); + } + return std::hash()(v); +} + +template +size_t PigeonInternalDeepHash(const std::optional& v) { + return v ? PigeonInternalDeepHash(*v) : 0; +} + +template +size_t PigeonInternalDeepHash(const std::unique_ptr& v) { + return v ? PigeonInternalDeepHash(*v) : 0; +} + +size_t PigeonInternalDeepHash(const ::flutter::EncodableValue& v) { + size_t result = v.index(); + if (const double* dv = std::get_if(&v)) { + result = result * 31 + PigeonInternalDeepHash(*dv); + } else if (const ::flutter::EncodableList* lv = + std::get_if<::flutter::EncodableList>(&v)) { + result = result * 31 + PigeonInternalDeepHash(*lv); + } else if (const ::flutter::EncodableMap* mv = + std::get_if<::flutter::EncodableMap>(&v)) { + result = result * 31 + PigeonInternalDeepHash(*mv); + } else { + std::visit( + [&result](const auto& val) { + using T = std::decay_t; + if constexpr (!std::is_same_v && + !std::is_same_v && + !std::is_same_v && + !std::is_same_v && + !std::is_same_v) { + result = result * 31 + PigeonInternalDeepHash(val); + } + }, + v); + } + return result; +} + +} // namespace // MessageData MessageData::MessageData(const Code& code, const EncodableMap& data) @@ -102,10 +310,32 @@ MessageData MessageData::FromEncodableList(const EncodableList& list) { return decoded; } +bool MessageData::operator==(const MessageData& other) const { + return PigeonInternalDeepEquals(name_, other.name_) && + PigeonInternalDeepEquals(description_, other.description_) && + PigeonInternalDeepEquals(code_, other.code_) && + PigeonInternalDeepEquals(data_, other.data_); +} + +bool MessageData::operator!=(const MessageData& other) const { + return !(*this == other); +} + +size_t MessageData::Hash() const { + size_t result = 1; + result = result * 31 + PigeonInternalDeepHash(name_); + result = result * 31 + PigeonInternalDeepHash(description_); + result = result * 31 + PigeonInternalDeepHash(code_); + result = result * 31 + PigeonInternalDeepHash(data_); + return result; +} + +size_t PigeonInternalDeepHash(const MessageData& v) { return v.Hash(); } + PigeonInternalCodecSerializer::PigeonInternalCodecSerializer() {} EncodableValue PigeonInternalCodecSerializer::ReadValueOfType( - uint8_t type, flutter::ByteStreamReader* stream) const { + uint8_t type, ::flutter::ByteStreamReader* stream) const { switch (type) { case 129: { const auto& encodable_enum_arg = ReadValue(stream); @@ -120,12 +350,12 @@ EncodableValue PigeonInternalCodecSerializer::ReadValueOfType( std::get(ReadValue(stream)))); } default: - return flutter::StandardCodecSerializer::ReadValueOfType(type, stream); + return ::flutter::StandardCodecSerializer::ReadValueOfType(type, stream); } } void PigeonInternalCodecSerializer::WriteValue( - const EncodableValue& value, flutter::ByteStreamWriter* stream) const { + const EncodableValue& value, ::flutter::ByteStreamWriter* stream) const { if (const CustomEncodableValue* custom_value = std::get_if(&value)) { if (custom_value->type() == typeid(Code)) { @@ -144,23 +374,23 @@ void PigeonInternalCodecSerializer::WriteValue( return; } } - flutter::StandardCodecSerializer::WriteValue(value, stream); + ::flutter::StandardCodecSerializer::WriteValue(value, stream); } /// The codec used by ExampleHostApi. -const flutter::StandardMessageCodec& ExampleHostApi::GetCodec() { - return flutter::StandardMessageCodec::GetInstance( +const ::flutter::StandardMessageCodec& ExampleHostApi::GetCodec() { + return ::flutter::StandardMessageCodec::GetInstance( &PigeonInternalCodecSerializer::GetInstance()); } // Sets up an instance of `ExampleHostApi` to handle messages through the // `binary_messenger`. -void ExampleHostApi::SetUp(flutter::BinaryMessenger* binary_messenger, +void ExampleHostApi::SetUp(::flutter::BinaryMessenger* binary_messenger, ExampleHostApi* api) { ExampleHostApi::SetUp(binary_messenger, api, ""); } -void ExampleHostApi::SetUp(flutter::BinaryMessenger* binary_messenger, +void ExampleHostApi::SetUp(::flutter::BinaryMessenger* binary_messenger, ExampleHostApi* api, const std::string& message_channel_suffix) { const std::string prepended_suffix = @@ -176,7 +406,7 @@ void ExampleHostApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { ErrorOr output = api->GetHostLanguage(); if (output.has_error()) { @@ -203,7 +433,7 @@ void ExampleHostApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_arg = args.at(0); @@ -243,7 +473,7 @@ void ExampleHostApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_message_arg = args.at(0); @@ -287,18 +517,20 @@ EncodableValue ExampleHostApi::WrapError(const FlutterError& error) { // Generated class from Pigeon that represents Flutter messages that can be // called from C++. -MessageFlutterApi::MessageFlutterApi(flutter::BinaryMessenger* binary_messenger) +MessageFlutterApi::MessageFlutterApi( + ::flutter::BinaryMessenger* binary_messenger) : binary_messenger_(binary_messenger), message_channel_suffix_("") {} -MessageFlutterApi::MessageFlutterApi(flutter::BinaryMessenger* binary_messenger, - const std::string& message_channel_suffix) +MessageFlutterApi::MessageFlutterApi( + ::flutter::BinaryMessenger* binary_messenger, + const std::string& message_channel_suffix) : binary_messenger_(binary_messenger), message_channel_suffix_(message_channel_suffix.length() > 0 ? std::string(".") + message_channel_suffix : "") {} -const flutter::StandardMessageCodec& MessageFlutterApi::GetCodec() { - return flutter::StandardMessageCodec::GetInstance( +const ::flutter::StandardMessageCodec& MessageFlutterApi::GetCodec() { + return ::flutter::StandardMessageCodec::GetInstance( &PigeonInternalCodecSerializer::GetInstance()); } diff --git a/packages/pigeon/example/app/windows/runner/messages.g.h b/packages/pigeon/example/app/windows/runner/messages.g.h index c56c0d1cf171..b23312baccff 100644 --- a/packages/pigeon/example/app/windows/runner/messages.g.h +++ b/packages/pigeon/example/app/windows/runner/messages.g.h @@ -25,17 +25,17 @@ class FlutterError { explicit FlutterError(const std::string& code, const std::string& message) : code_(code), message_(message) {} explicit FlutterError(const std::string& code, const std::string& message, - const flutter::EncodableValue& details) + const ::flutter::EncodableValue& details) : code_(code), message_(message), details_(details) {} const std::string& code() const { return code_; } const std::string& message() const { return message_; } - const flutter::EncodableValue& details() const { return details_; } + const ::flutter::EncodableValue& details() const { return details_; } private: std::string code_; std::string message_; - flutter::EncodableValue details_; + ::flutter::EncodableValue details_; }; template @@ -65,11 +65,11 @@ enum class Code { kOne = 0, kTwo = 1 }; class MessageData { public: // Constructs an object setting all non-nullable fields. - explicit MessageData(const Code& code, const flutter::EncodableMap& data); + explicit MessageData(const Code& code, const ::flutter::EncodableMap& data); // Constructs an object setting all fields. explicit MessageData(const std::string* name, const std::string* description, - const Code& code, const flutter::EncodableMap& data); + const Code& code, const ::flutter::EncodableMap& data); const std::string* name() const; void set_name(const std::string_view* value_arg); @@ -82,22 +82,29 @@ class MessageData { const Code& code() const; void set_code(const Code& value_arg); - const flutter::EncodableMap& data() const; - void set_data(const flutter::EncodableMap& value_arg); + const ::flutter::EncodableMap& data() const; + void set_data(const ::flutter::EncodableMap& value_arg); + + bool operator==(const MessageData& other) const; + bool operator!=(const MessageData& other) const; + /// Returns a hash code value for the object. This method is supported for the + /// benefit of hash tables. + size_t Hash() const; private: - static MessageData FromEncodableList(const flutter::EncodableList& list); - flutter::EncodableList ToEncodableList() const; + static MessageData FromEncodableList(const ::flutter::EncodableList& list); + ::flutter::EncodableList ToEncodableList() const; friend class ExampleHostApi; friend class MessageFlutterApi; friend class PigeonInternalCodecSerializer; std::optional name_; std::optional description_; Code code_; - flutter::EncodableMap data_; + ::flutter::EncodableMap data_; }; -class PigeonInternalCodecSerializer : public flutter::StandardCodecSerializer { +class PigeonInternalCodecSerializer + : public ::flutter::StandardCodecSerializer { public: PigeonInternalCodecSerializer(); inline static PigeonInternalCodecSerializer& GetInstance() { @@ -105,12 +112,12 @@ class PigeonInternalCodecSerializer : public flutter::StandardCodecSerializer { return sInstance; } - void WriteValue(const flutter::EncodableValue& value, - flutter::ByteStreamWriter* stream) const override; + void WriteValue(const ::flutter::EncodableValue& value, + ::flutter::ByteStreamWriter* stream) const override; protected: - flutter::EncodableValue ReadValueOfType( - uint8_t type, flutter::ByteStreamReader* stream) const override; + ::flutter::EncodableValue ReadValueOfType( + uint8_t type, ::flutter::ByteStreamReader* stream) const override; }; // Generated interface from Pigeon that represents a handler of messages from @@ -126,16 +133,16 @@ class ExampleHostApi { std::function reply)> result) = 0; // The codec used by ExampleHostApi. - static const flutter::StandardMessageCodec& GetCodec(); + static const ::flutter::StandardMessageCodec& GetCodec(); // Sets up an instance of `ExampleHostApi` to handle messages through the // `binary_messenger`. - static void SetUp(flutter::BinaryMessenger* binary_messenger, + static void SetUp(::flutter::BinaryMessenger* binary_messenger, ExampleHostApi* api); - static void SetUp(flutter::BinaryMessenger* binary_messenger, + static void SetUp(::flutter::BinaryMessenger* binary_messenger, ExampleHostApi* api, const std::string& message_channel_suffix); - static flutter::EncodableValue WrapError(std::string_view error_message); - static flutter::EncodableValue WrapError(const FlutterError& error); + static ::flutter::EncodableValue WrapError(std::string_view error_message); + static ::flutter::EncodableValue WrapError(const FlutterError& error); protected: ExampleHostApi() = default; @@ -144,16 +151,16 @@ class ExampleHostApi { // called from C++. class MessageFlutterApi { public: - MessageFlutterApi(flutter::BinaryMessenger* binary_messenger); - MessageFlutterApi(flutter::BinaryMessenger* binary_messenger, + MessageFlutterApi(::flutter::BinaryMessenger* binary_messenger); + MessageFlutterApi(::flutter::BinaryMessenger* binary_messenger, const std::string& message_channel_suffix); - static const flutter::StandardMessageCodec& GetCodec(); + static const ::flutter::StandardMessageCodec& GetCodec(); void FlutterMethod(const std::string* a_string, std::function&& on_success, std::function&& on_error); private: - flutter::BinaryMessenger* binary_messenger_; + ::flutter::BinaryMessenger* binary_messenger_; std::string message_channel_suffix_; }; diff --git a/packages/pigeon/lib/src/ast.dart b/packages/pigeon/lib/src/ast.dart index 669d3bdca61a..aba0e0891cae 100644 --- a/packages/pigeon/lib/src/ast.dart +++ b/packages/pigeon/lib/src/ast.dart @@ -91,10 +91,10 @@ class Method extends Node { @override String toString() { - final String objcSelectorStr = objcSelector.isEmpty + final objcSelectorStr = objcSelector.isEmpty ? '' : ' objcSelector:$objcSelector'; - final String swiftFunctionStr = swiftFunction.isEmpty + final swiftFunctionStr = swiftFunction.isEmpty ? '' : ' swiftFunction:$swiftFunction'; return '(Method name:$name returnType:$returnType parameters:$parameters isAsynchronous:$isAsynchronous$objcSelectorStr$swiftFunctionStr documentationComments:$documentationComments)'; @@ -202,7 +202,7 @@ class AstProxyApi extends Api { /// This method also assumes that the type of [superClass] is annotated with /// `@ProxyApi`. Otherwise, throws an [ArgumentError]. Iterable allSuperClasses() { - final List superClassChain = []; + final superClassChain = []; if (superClass != null && !superClass!.isProxyApi) { throw ArgumentError( @@ -259,7 +259,7 @@ class AstProxyApi extends Api { final Set interfaceApisFromSuperClasses = superClass! .associatedProxyApi! ._recursiveFindAllInterfaceApis(); - for (final AstProxyApi proxyApi in interfaceApisFromSuperClasses) { + for (final proxyApi in interfaceApisFromSuperClasses) { yield* proxyApi.methods.map((Method method) => (method, proxyApi)); } } @@ -320,7 +320,7 @@ class AstProxyApi extends Api { Set _recursiveFindAllInterfaceApis([ Set seenApis = const {}, ]) { - final Set allInterfaces = {}; + final allInterfaces = {}; allInterfaces.addAll( interfaces.map((TypeDeclaration type) { @@ -339,9 +339,9 @@ class AstProxyApi extends Api { // Adds the current api since it would be invalid for it to be an interface // of itself. - final Set newSeenApis = {...seenApis, this}; + final newSeenApis = {...seenApis, this}; - for (final AstProxyApi interfaceApi in {...allInterfaces}) { + for (final interfaceApi in {...allInterfaces}) { allInterfaces.addAll( interfaceApi._recursiveFindAllInterfaceApis(newSeenApis), ); @@ -397,7 +397,7 @@ class Constructor extends Method { @override String toString() { - final String swiftFunctionStr = swiftFunction.isEmpty + final swiftFunctionStr = swiftFunction.isEmpty ? '' : ' swiftFunction:$swiftFunction'; return '(Constructor name:$name parameters:$parameters $swiftFunctionStr documentationComments:$documentationComments)'; @@ -496,13 +496,13 @@ class TypeDeclaration { associatedProxyApi = null, typeArguments = const []; - /// The base name of the [TypeDeclaration] (ex 'Foo' to 'Foo?'). + /// The base name of the [TypeDeclaration] (ex `Foo` to `Foo?`). final String baseName; /// Whether the declaration represents 'void'. bool get isVoid => baseName == 'void'; - /// Whether the type arguments to the entity (ex 'Bar' to 'Foo?'). + /// Whether the type arguments to the entity (ex `Bar` to `Foo?`). final List typeArguments; /// Whether the type is nullable. @@ -530,7 +530,7 @@ class TypeDeclaration { int get hashCode { // This has to be implemented because TypeDeclaration is used as a Key to a // Map in generator_tools.dart. - int hash = 17; + var hash = 17; hash = hash * 37 + baseName.hashCode; hash = hash * 37 + isNullable.hashCode; for (final TypeDeclaration typeArgument in typeArguments) { @@ -555,7 +555,8 @@ class TypeDeclaration { } } - /// Returns duplicated `TypeDeclaration` with attached `associatedEnum` value. + /// Returns a new [TypeDeclaration] with [enumDefinition] as the + /// [associatedEnum] value. TypeDeclaration copyWithEnum(Enum enumDefinition) { return TypeDeclaration( baseName: baseName, @@ -565,7 +566,8 @@ class TypeDeclaration { ); } - /// Returns duplicated `TypeDeclaration` with attached `associatedClass` value. + /// Returns a new [TypeDeclaration] with [classDefinition] as the + /// [associatedClass] value. TypeDeclaration copyWithClass(Class classDefinition) { return TypeDeclaration( baseName: baseName, @@ -575,7 +577,8 @@ class TypeDeclaration { ); } - /// Returns duplicated `TypeDeclaration` with attached `associatedProxyApi` value. + /// Returns a new [TypeDeclaration] with [proxyApiDefinition] as the + /// [associatedProxyApi] value. TypeDeclaration copyWithProxyApi(AstProxyApi proxyApiDefinition) { return TypeDeclaration( baseName: baseName, @@ -585,7 +588,7 @@ class TypeDeclaration { ); } - /// Returns duplicated `TypeDeclaration` with attached `associatedProxyApi` value. + /// Returns a new [TypeDeclaration] with [types] as the [typeArguments] value. TypeDeclaration copyWithTypeArguments(List types) { return TypeDeclaration( baseName: baseName, @@ -599,7 +602,7 @@ class TypeDeclaration { @override String toString() { - final String typeArgumentsStr = typeArguments.isEmpty + final typeArgumentsStr = typeArguments.isEmpty ? '' : ' typeArguments:$typeArguments'; return '(TypeDeclaration baseName:$baseName isNullable:$isNullable$typeArgumentsStr isEnum:$isEnum isClass:$isClass isProxyApi:$isProxyApi)'; diff --git a/packages/pigeon/lib/src/ast_generator.dart b/packages/pigeon/lib/src/ast_generator.dart index 187d75219905..877218337b97 100644 --- a/packages/pigeon/lib/src/ast_generator.dart +++ b/packages/pigeon/lib/src/ast_generator.dart @@ -7,11 +7,11 @@ import 'generator_tools.dart'; /// Writes the AST representation of [root] to [sink]. void generateAst(Root root, StringSink sink) { - final Indent indent = Indent(sink); - final String output = root.toString(); - bool isFirst = true; + final indent = Indent(); + final output = root.toString(); + var isFirst = true; for (final int ch in output.runes) { - final String chStr = String.fromCharCode(ch); + final chStr = String.fromCharCode(ch); if (chStr == '(') { if (isFirst) { isFirst = false; @@ -26,4 +26,5 @@ void generateAst(Root root, StringSink sink) { indent.add(chStr); } indent.addln(''); + sink.write(indent.toString()); } diff --git a/packages/pigeon/lib/src/cpp/cpp_generator.dart b/packages/pigeon/lib/src/cpp/cpp_generator.dart index 78f6eb263eee..ffaf56787d66 100644 --- a/packages/pigeon/lib/src/cpp/cpp_generator.dart +++ b/packages/pigeon/lib/src/cpp/cpp_generator.dart @@ -20,7 +20,7 @@ const DocumentCommentSpecification _docCommentSpec = DocumentCommentSpecification(_commentPrefix); /// The default serializer for Flutter. -const String _standardCodecSerializer = 'flutter::StandardCodecSerializer'; +const String _standardCodecSerializer = '::flutter::StandardCodecSerializer'; /// The name of the codec serializer. const String _codecSerializerName = '${classNamePrefix}CodecSerializer'; @@ -87,7 +87,7 @@ class CppOptions { /// Converts a [CppOptions] to a Map representation where: /// `x = CppOptions.fromMap(x.toMap())`. Map toMap() { - final Map result = { + final result = { if (headerIncludePath != null) 'headerIncludePath': headerIncludePath!, if (namespace != null) 'namespace': namespace!, if (copyrightHeader != null) 'copyrightHeader': copyrightHeader!, @@ -232,7 +232,7 @@ class CppHeaderGenerator extends StructuredGenerator { } indent.newln(); if (generatorOptions.namespace?.endsWith('_pigeontest') ?? false) { - final String testFixtureClass = + final testFixtureClass = '${_pascalCaseFromSnakeCase(generatorOptions.namespace!.replaceAll('_pigeontest', ''))}Test'; indent.writeln('class $testFixtureClass;'); } @@ -262,7 +262,7 @@ class CppHeaderGenerator extends StructuredGenerator { member.documentationComments, _docCommentSpec, ); - final String valueName = 'k${_pascalCaseFromCamelCase(member.name)}'; + final valueName = 'k${_pascalCaseFromCamelCase(member.name)}'; indent.writeln( '$valueName = $index${index == anEnum.members.length - 1 ? '' : ','}', ); @@ -333,7 +333,7 @@ class CppHeaderGenerator extends StructuredGenerator { } indent.newln(); - const List generatedMessages = [ + const generatedMessages = [ ' Generated class from Pigeon that represents data sent in messages.', ]; @@ -417,7 +417,7 @@ class CppHeaderGenerator extends StructuredGenerator { ); } - for (final NamedType field in orderedFields) { + for (final field in orderedFields) { addDocumentationComments( indent, field.documentationComments, @@ -459,6 +459,30 @@ class CppHeaderGenerator extends StructuredGenerator { } indent.newln(); } + + _writeFunctionDeclaration( + indent, + 'operator==', + returnType: 'bool', + parameters: ['const ${classDefinition.name}& other'], + isConst: true, + ); + _writeFunctionDeclaration( + indent, + 'operator!=', + returnType: 'bool', + parameters: ['const ${classDefinition.name}& other'], + isConst: true, + ); + indent.writeln( + '/// Returns a hash code value for the object. This method is supported for the benefit of hash tables.', + ); + _writeFunctionDeclaration( + indent, + 'Hash', + returnType: 'size_t', + isConst: true, + ); }); _writeAccessBlock(indent, _ClassAccess.private, () { @@ -466,22 +490,22 @@ class CppHeaderGenerator extends StructuredGenerator { indent, 'FromEncodableList', returnType: isOverflowClass - ? 'flutter::EncodableValue' + ? '::flutter::EncodableValue' : classDefinition.name, - parameters: ['const flutter::EncodableList& list'], + parameters: ['const ::flutter::EncodableList& list'], isStatic: true, ); _writeFunctionDeclaration( indent, 'ToEncodableList', - returnType: 'flutter::EncodableList', + returnType: '::flutter::EncodableList', isConst: true, ); if (isOverflowClass) { _writeFunctionDeclaration( indent, 'Unwrap', - returnType: 'flutter::EncodableValue', + returnType: '::flutter::EncodableValue', ); } if (!isOverflowClass && root.requiresOverflowClass) { @@ -508,7 +532,7 @@ class CppHeaderGenerator extends StructuredGenerator { indent.writeln('friend class $testFixtureClass;'); } - for (final NamedType field in orderedFields) { + for (final field in orderedFields) { final HostDatatype hostDatatype = getFieldHostDatatype( field, _baseCppTypeForBuiltinDartType, @@ -556,8 +580,8 @@ class CppHeaderGenerator extends StructuredGenerator { 'WriteValue', returnType: _voidType, parameters: [ - 'const flutter::EncodableValue& value', - 'flutter::ByteStreamWriter* stream', + 'const ::flutter::EncodableValue& value', + '::flutter::ByteStreamWriter* stream', ], isConst: true, isOverride: true, @@ -567,10 +591,10 @@ class CppHeaderGenerator extends StructuredGenerator { _writeFunctionDeclaration( indent, 'ReadValueOfType', - returnType: 'flutter::EncodableValue', + returnType: '::flutter::EncodableValue', parameters: [ 'uint8_t type', - 'flutter::ByteStreamReader* stream', + '::flutter::ByteStreamReader* stream', ], isConst: true, isOverride: true, @@ -588,7 +612,7 @@ class CppHeaderGenerator extends StructuredGenerator { AstFlutterApi api, { required String dartPackageName, }) { - const List generatedMessages = [ + const generatedMessages = [ ' Generated class from Pigeon that represents Flutter messages that can be called from C++.', ]; addDocumentationComments( @@ -603,20 +627,20 @@ class CppHeaderGenerator extends StructuredGenerator { _writeFunctionDeclaration( indent, api.name, - parameters: ['flutter::BinaryMessenger* binary_messenger'], + parameters: ['::flutter::BinaryMessenger* binary_messenger'], ); _writeFunctionDeclaration( indent, api.name, parameters: [ - 'flutter::BinaryMessenger* binary_messenger', + '::flutter::BinaryMessenger* binary_messenger', 'const std::string& message_channel_suffix', ], ); _writeFunctionDeclaration( indent, 'GetCodec', - returnType: 'const flutter::StandardMessageCodec&', + returnType: 'const ::flutter::StandardMessageCodec&', isStatic: true, ); for (final Method func in api.methods) { @@ -643,7 +667,7 @@ class CppHeaderGenerator extends StructuredGenerator { func.parameters, _getArgumentName, ); - final List parameters = [ + final parameters = [ ...map2(argTypes, argNames, (String x, String y) => '$x $y'), ..._flutterApiCallbackParameters(returnType), ]; @@ -656,7 +680,7 @@ class CppHeaderGenerator extends StructuredGenerator { } }); indent.addScoped(' private:', null, () { - indent.writeln('flutter::BinaryMessenger* binary_messenger_;'); + indent.writeln('::flutter::BinaryMessenger* binary_messenger_;'); indent.writeln('std::string message_channel_suffix_;'); }); }, nestCount: 0); @@ -671,7 +695,7 @@ class CppHeaderGenerator extends StructuredGenerator { AstHostApi api, { required String dartPackageName, }) { - const List generatedMessages = [ + const generatedMessages = [ ' Generated interface from Pigeon that represents a handler of messages from Flutter.', ]; addDocumentationComments( @@ -711,7 +735,7 @@ class CppHeaderGenerator extends StructuredGenerator { ); final String returnTypeName = _hostApiReturnType(returnType); - final List parameters = []; + final parameters = []; if (method.parameters.isNotEmpty) { final Iterable argTypes = method.parameters.map(( NamedType arg, @@ -758,7 +782,7 @@ class CppHeaderGenerator extends StructuredGenerator { _writeFunctionDeclaration( indent, 'GetCodec', - returnType: 'const flutter::StandardMessageCodec&', + returnType: 'const ::flutter::StandardMessageCodec&', isStatic: true, ); indent.writeln( @@ -770,7 +794,7 @@ class CppHeaderGenerator extends StructuredGenerator { returnType: _voidType, isStatic: true, parameters: [ - 'flutter::BinaryMessenger* binary_messenger', + '::flutter::BinaryMessenger* binary_messenger', '${api.name}* api', ], ); @@ -780,7 +804,7 @@ class CppHeaderGenerator extends StructuredGenerator { returnType: _voidType, isStatic: true, parameters: [ - 'flutter::BinaryMessenger* binary_messenger', + '::flutter::BinaryMessenger* binary_messenger', '${api.name}* api', 'const std::string& message_channel_suffix', ], @@ -788,14 +812,14 @@ class CppHeaderGenerator extends StructuredGenerator { _writeFunctionDeclaration( indent, 'WrapError', - returnType: 'flutter::EncodableValue', + returnType: '::flutter::EncodableValue', isStatic: true, parameters: ['std::string_view error_message'], ); _writeFunctionDeclaration( indent, 'WrapError', - returnType: 'flutter::EncodableValue', + returnType: '::flutter::EncodableValue', isStatic: true, parameters: ['const FlutterError& error'], ); @@ -839,17 +863,17 @@ class FlutterError { \t\t: code_(code) {} \texplicit FlutterError(const std::string& code, const std::string& message) \t\t: code_(code), message_(message) {} -\texplicit FlutterError(const std::string& code, const std::string& message, const flutter::EncodableValue& details) +\texplicit FlutterError(const std::string& code, const std::string& message, const ::flutter::EncodableValue& details) \t\t: code_(code), message_(message), details_(details) {} \tconst std::string& code() const { return code_; } \tconst std::string& message() const { return message_; } -\tconst flutter::EncodableValue& details() const { return details_; } +\tconst ::flutter::EncodableValue& details() const { return details_; } private: \tstd::string code_; \tstd::string message_; -\tflutter::EncodableValue details_; +\t::flutter::EncodableValue details_; };'''); } @@ -937,6 +961,8 @@ class CppSourceGenerator extends StructuredGenerator { ]); indent.newln(); _writeSystemHeaderIncludeBlock(indent, [ + 'cmath', + 'limits', 'map', 'string', 'optional', @@ -963,15 +989,15 @@ class CppSourceGenerator extends StructuredGenerator { Indent indent, { required String dartPackageName, }) { - final List usingDirectives = [ - 'flutter::BasicMessageChannel', - 'flutter::CustomEncodableValue', - 'flutter::EncodableList', - 'flutter::EncodableMap', - 'flutter::EncodableValue', + final usingDirectives = [ + '::flutter::BasicMessageChannel', + '::flutter::CustomEncodableValue', + '::flutter::EncodableList', + '::flutter::EncodableMap', + '::flutter::EncodableValue', ]; usingDirectives.sort(); - for (final String using in usingDirectives) { + for (final using in usingDirectives) { indent.writeln('using $using;'); } indent.newln(); @@ -988,6 +1014,10 @@ class CppSourceGenerator extends StructuredGenerator { EncodableValue(""));'''); }, ); + indent.writeln('namespace {'); + _writeDeepEquals(indent); + _writeDeepHash(indent); + indent.writeln('} // namespace'); } @override @@ -1025,7 +1055,7 @@ class CppSourceGenerator extends StructuredGenerator { } // Getters and setters. - for (final NamedType field in orderedFields) { + for (final field in orderedFields) { _writeCppSourceClassField( generatorOptions, root, @@ -1052,6 +1082,267 @@ class CppSourceGenerator extends StructuredGenerator { classDefinition, dartPackageName: dartPackageName, ); + + _writeFunctionDefinition( + indent, + 'operator==', + scope: classDefinition.name, + returnType: 'bool', + parameters: ['const ${classDefinition.name}& other'], + isConst: true, + body: () { + final Iterable checks = orderedFields.map((NamedType field) { + final String name = _makeInstanceVariableName(field); + return 'PigeonInternalDeepEquals($name, other.$name)'; + }); + if (checks.isEmpty) { + indent.writeln('return true;'); + } else { + indent.writeln('return ${checks.join(' && ')};'); + } + }, + ); + + _writeFunctionDefinition( + indent, + 'operator!=', + scope: classDefinition.name, + returnType: 'bool', + parameters: ['const ${classDefinition.name}& other'], + isConst: true, + body: () { + indent.writeln('return !(*this == other);'); + }, + ); + + _writeFunctionDefinition( + indent, + 'Hash', + scope: classDefinition.name, + returnType: 'size_t', + isConst: true, + body: () { + indent.writeln('size_t result = 1;'); + for (final field in orderedFields) { + final String name = _makeInstanceVariableName(field); + indent.writeln( + 'result = result * 31 + PigeonInternalDeepHash($name);', + ); + } + indent.writeln('return result;'); + }, + ); + + _writeFunctionDefinition( + indent, + 'PigeonInternalDeepHash', + returnType: 'size_t', + parameters: ['const ${classDefinition.name}& v'], + body: () { + indent.writeln('return v.Hash();'); + }, + ); + } + + void _writeDeepEquals(Indent indent) { + indent.format(''' +template +bool PigeonInternalDeepEquals(const T& a, const T& b); + +bool PigeonInternalDeepEquals(const double& a, const double& b); + +template +bool PigeonInternalDeepEquals(const std::vector& a, const std::vector& b); + +template +bool PigeonInternalDeepEquals(const std::map& a, const std::map& b); + +template +bool PigeonInternalDeepEquals(const std::optional& a, const std::optional& b); + +template +bool PigeonInternalDeepEquals(const std::unique_ptr& a, const std::unique_ptr& b); + +bool PigeonInternalDeepEquals(const ::flutter::EncodableValue& a, const ::flutter::EncodableValue& b); + +template +bool PigeonInternalDeepEquals(const T& a, const T& b) { + return a == b; +} + +template +bool PigeonInternalDeepEquals(const std::vector& a, const std::vector& b) { + if (a.size() != b.size()) { + return false; + } + for (size_t i = 0; i < a.size(); ++i) { + if (!PigeonInternalDeepEquals(a[i], b[i])) { + return false; + } + } + return true; +} + +template +bool PigeonInternalDeepEquals(const std::map& a, const std::map& b) { + if (a.size() != b.size()) { + return false; + } + for (const auto& kv : a) { + bool found = false; + for (const auto& b_kv : b) { + if (PigeonInternalDeepEquals(kv.first, b_kv.first)) { + if (PigeonInternalDeepEquals(kv.second, b_kv.second)) { + found = true; + break; + } else { + return false; + } + } + } + if (!found) { + return false; + } + } + return true; +} + +bool PigeonInternalDeepEquals(const double& a, const double& b) { + // Normalize -0.0 to 0.0 and handle NaN equality. + return (a == b) || (std::isnan(a) && std::isnan(b)); +} + +template +bool PigeonInternalDeepEquals(const std::optional& a, const std::optional& b) { + if (!a && !b) { + return true; + } + if (!a || !b) { + return false; + } + return PigeonInternalDeepEquals(*a, *b); +} + +template +bool PigeonInternalDeepEquals(const std::unique_ptr& a, const std::unique_ptr& b) { + if (a.get() == b.get()) { + return true; + } + if (!a || !b) { + return false; + } + return PigeonInternalDeepEquals(*a, *b); +} + +bool PigeonInternalDeepEquals(const ::flutter::EncodableValue& a, const ::flutter::EncodableValue& b) { + if (a.index() != b.index()) { + return false; + } + if (const double* da = std::get_if(&a)) { + return PigeonInternalDeepEquals(*da, std::get(b)); + } else if (const ::flutter::EncodableList* la = std::get_if<::flutter::EncodableList>(&a)) { + return PigeonInternalDeepEquals(*la, std::get<::flutter::EncodableList>(b)); + } else if (const ::flutter::EncodableMap* ma = std::get_if<::flutter::EncodableMap>(&a)) { + return PigeonInternalDeepEquals(*ma, std::get<::flutter::EncodableMap>(b)); + } + return a == b; +} +'''); + } + + void _writeDeepHash(Indent indent) { + indent.format(''' +template +size_t PigeonInternalDeepHash(const T& v); + +size_t PigeonInternalDeepHash(const double& v); + +template +size_t PigeonInternalDeepHash(const std::vector& v); + +template +size_t PigeonInternalDeepHash(const std::map& v); + +template +size_t PigeonInternalDeepHash(const std::optional& v); + +template +size_t PigeonInternalDeepHash(const std::unique_ptr& v); + +size_t PigeonInternalDeepHash(const ::flutter::EncodableValue& v); + +template +size_t PigeonInternalDeepHash(const T& v) { + return std::hash()(v); +} + +template +size_t PigeonInternalDeepHash(const std::vector& v) { + size_t result = 1; + for (const auto& item : v) { + result = result * 31 + PigeonInternalDeepHash(item); + } + return result; +} + +template +size_t PigeonInternalDeepHash(const std::map& v) { + size_t result = 0; + for (const auto& kv : v) { + result += ((PigeonInternalDeepHash(kv.first) * 31) ^ PigeonInternalDeepHash(kv.second)); + } + return result; +} + +size_t PigeonInternalDeepHash(const double& v) { + if (std::isnan(v)) { + // Normalize NaN to a consistent hash. + return std::hash()(std::numeric_limits::quiet_NaN()); + } + if (v == 0.0) { + // Normalize -0.0 to 0.0 so they have the same hash code. + return std::hash()(0.0); + } + return std::hash()(v); +} + +template +size_t PigeonInternalDeepHash(const std::optional& v) { + return v ? PigeonInternalDeepHash(*v) : 0; +} + +template +size_t PigeonInternalDeepHash(const std::unique_ptr& v) { + return v ? PigeonInternalDeepHash(*v) : 0; +} + +size_t PigeonInternalDeepHash(const ::flutter::EncodableValue& v) { + size_t result = v.index(); + if (const double* dv = std::get_if(&v)) { + result = result * 31 + PigeonInternalDeepHash(*dv); + } else if (const ::flutter::EncodableList* lv = + std::get_if<::flutter::EncodableList>(&v)) { + result = result * 31 + PigeonInternalDeepHash(*lv); + } else if (const ::flutter::EncodableMap* mv = + std::get_if<::flutter::EncodableMap>(&v)) { + result = result * 31 + PigeonInternalDeepHash(*mv); + } else { + std::visit( + [&result](const auto& val) { + using T = std::decay_t; + if constexpr (!std::is_same_v && + !std::is_same_v && + !std::is_same_v && + !std::is_same_v && + !std::is_same_v) { + result = result * 31 + PigeonInternalDeepHash(val); + } + }, + v); + } + return result; +} +'''); } @override @@ -1125,7 +1416,7 @@ class CppSourceGenerator extends StructuredGenerator { returnType: classDefinition.name, parameters: ['const EncodableList& list'], body: () { - const String instanceVariable = 'decoded'; + const instanceVariable = 'decoded'; final Iterable<_IndexedField> indexedFields = indexMap( getFieldsInSerializationOrder(classDefinition), (int index, NamedType field) => _IndexedField(index, field), @@ -1154,10 +1445,10 @@ class CppSourceGenerator extends StructuredGenerator { // Add the nullable fields via setters, since converting the encodable // values to the pointer types that the convenience constructor uses for // nullable fields is non-trivial. - for (final _IndexedField entry in nullableFields) { + for (final entry in nullableFields) { final NamedType field = entry.field; final String setterName = _makeSetterName(field); - final String encodableFieldName = + final encodableFieldName = '${_encodablePrefix}_${_makeVariableName(field)}'; indent.writeln('auto& $encodableFieldName = list[${entry.index}];'); @@ -1292,13 +1583,16 @@ EncodableValue $_overflowClassName::FromEncodableList( 'ReadValueOfType', scope: _codecSerializerName, returnType: 'EncodableValue', - parameters: ['uint8_t type', 'flutter::ByteStreamReader* stream'], + parameters: [ + 'uint8_t type', + '::flutter::ByteStreamReader* stream', + ], isConst: true, body: () { if (enumeratedTypes.isNotEmpty) { indent.writeln('switch (type) {'); indent.inc(); - for (final EnumeratedType customType in enumeratedTypes) { + for (final customType in enumeratedTypes) { if (customType.enumeration < maximumCodecFieldKey) { indent.write('case ${customType.enumeration}: '); indent.nest(1, () { @@ -1330,7 +1624,7 @@ EncodableValue $_overflowClassName::FromEncodableList( returnType: _voidType, parameters: [ 'const EncodableValue& value', - 'flutter::ByteStreamWriter* stream', + '::flutter::ByteStreamWriter* stream', ], isConst: true, body: () { @@ -1339,13 +1633,11 @@ EncodableValue $_overflowClassName::FromEncodableList( 'if (const CustomEncodableValue* custom_value = std::get_if(&value)) ', ); indent.addScoped('{', '}', () { - for (final EnumeratedType customType in enumeratedTypes) { - final String encodeString = - customType.type == CustomTypes.customClass + for (final customType in enumeratedTypes) { + final encodeString = customType.type == CustomTypes.customClass ? 'std::any_cast<${customType.name}>(*custom_value).ToEncodableList()' : 'static_cast(std::any_cast<${customType.name}>(*custom_value))'; - final String valueString = - customType.enumeration < maximumCodecFieldKey + final valueString = customType.enumeration < maximumCodecFieldKey ? encodeString : 'wrap.ToEncodableList()'; final int enumeration = @@ -1390,7 +1682,7 @@ EncodableValue $_overflowClassName::FromEncodableList( indent, api.name, scope: api.name, - parameters: ['flutter::BinaryMessenger* binary_messenger'], + parameters: ['::flutter::BinaryMessenger* binary_messenger'], initializers: [ 'binary_messenger_(binary_messenger)', 'message_channel_suffix_("")', @@ -1401,7 +1693,7 @@ EncodableValue $_overflowClassName::FromEncodableList( api.name, scope: api.name, parameters: [ - 'flutter::BinaryMessenger* binary_messenger', + '::flutter::BinaryMessenger* binary_messenger', 'const std::string& message_channel_suffix', ], initializers: [ @@ -1413,10 +1705,10 @@ EncodableValue $_overflowClassName::FromEncodableList( indent, 'GetCodec', scope: api.name, - returnType: 'const flutter::StandardMessageCodec&', + returnType: 'const ::flutter::StandardMessageCodec&', body: () { indent.writeln( - 'return flutter::StandardMessageCodec::GetInstance(&$_codecSerializerName::GetInstance());', + 'return ::flutter::StandardMessageCodec::GetInstance(&$_codecSerializerName::GetInstance());', ); }, ); @@ -1442,7 +1734,7 @@ EncodableValue $_overflowClassName::FromEncodableList( ); }, ); - final List parameters = [ + final parameters = [ ...hostParameters.map( (_HostNamedType arg) => '${_flutterApiArgumentType(arg.hostType)} ${arg.name}', @@ -1465,13 +1757,13 @@ EncodableValue $_overflowClassName::FromEncodableList( ); // Convert arguments to EncodableValue versions. - const String argumentListVariableName = 'encoded_api_arguments'; + const argumentListVariableName = 'encoded_api_arguments'; indent.write('EncodableValue $argumentListVariableName = '); if (func.parameters.isEmpty) { indent.addln('EncodableValue();'); } else { indent.addScoped('EncodableValue(EncodableList{', '});', () { - for (final _HostNamedType param in hostParameters) { + for (final param in hostParameters) { final String encodedArgument = _wrappedHostApiArgumentExpression( root, @@ -1494,9 +1786,8 @@ EncodableValue $_overflowClassName::FromEncodableList( indent.addScoped('{', '});', () { String successCallbackArgument; successCallbackArgument = 'return_value'; - final String encodedReplyName = - 'encodable_$successCallbackArgument'; - final String listReplyName = 'list_$successCallbackArgument'; + final encodedReplyName = 'encodable_$successCallbackArgument'; + final listReplyName = 'list_$successCallbackArgument'; indent.writeln( 'std::unique_ptr response = GetCodec().DecodeMessage(reply, reply_size);', ); @@ -1548,10 +1839,10 @@ EncodableValue $_overflowClassName::FromEncodableList( indent, 'GetCodec', scope: api.name, - returnType: 'const flutter::StandardMessageCodec&', + returnType: 'const ::flutter::StandardMessageCodec&', body: () { indent.writeln( - 'return flutter::StandardMessageCodec::GetInstance(&$_codecSerializerName::GetInstance());', + 'return ::flutter::StandardMessageCodec::GetInstance(&$_codecSerializerName::GetInstance());', ); }, ); @@ -1564,7 +1855,7 @@ EncodableValue $_overflowClassName::FromEncodableList( scope: api.name, returnType: _voidType, parameters: [ - 'flutter::BinaryMessenger* binary_messenger', + '::flutter::BinaryMessenger* binary_messenger', '${api.name}* api', ], body: () { @@ -1577,7 +1868,7 @@ EncodableValue $_overflowClassName::FromEncodableList( scope: api.name, returnType: _voidType, parameters: [ - 'flutter::BinaryMessenger* binary_messenger', + '::flutter::BinaryMessenger* binary_messenger', '${api.name}* api', 'const std::string& message_channel_suffix', ], @@ -1598,11 +1889,11 @@ EncodableValue $_overflowClassName::FromEncodableList( ); indent.writeScoped('if (api != nullptr) {', '} else {', () { indent.write( - 'channel.SetMessageHandler([api](const EncodableValue& message, const flutter::MessageReply& reply) ', + 'channel.SetMessageHandler([api](const EncodableValue& message, const ::flutter::MessageReply& reply) ', ); indent.addScoped('{', '});', () { indent.writeScoped('try {', '}', () { - final List methodArgument = []; + final methodArgument = []; if (method.parameters.isNotEmpty) { indent.writeln( 'const auto& args = std::get(message);', @@ -1616,8 +1907,7 @@ EncodableValue $_overflowClassName::FromEncodableList( ); final String argName = _getSafeArgumentName(index, arg); - final String encodableArgName = - '${_encodablePrefix}_$argName'; + final encodableArgName = '${_encodablePrefix}_$argName'; indent.writeln( 'const auto& $encodableArgName = args.at($index);', ); @@ -1641,8 +1931,7 @@ EncodableValue $_overflowClassName::FromEncodableList( encodableArgName: encodableArgName, apiType: ApiType.host, ); - final String unwrapEnum = - arg.type.isEnum && arg.type.isNullable + final unwrapEnum = arg.type.isEnum && arg.type.isNullable ? ' ? &(*$argName) : nullptr' : ''; methodArgument.add('$argName$unwrapEnum'); @@ -1661,7 +1950,7 @@ EncodableValue $_overflowClassName::FromEncodableList( '}', ); } - final String call = + final call = 'api->${_makeMethodName(method)}(${methodArgument.join(', ')})'; if (method.isAsynchronous) { indent.format('$call;'); @@ -1797,17 +2086,17 @@ return EncodableValue(EncodableList{ returnType: '${classDefinition.name}&', parameters: ['const ${classDefinition.name}& other'], body: () { - for (final NamedType field in fields) { + for (final field in fields) { final HostDatatype hostDatatype = getFieldHostDatatype( field, _shortBaseCppTypeForBuiltinDartType, ); final String ivarName = _makeInstanceVariableName(field); - final String otherIvar = 'other.$ivarName'; + final otherIvar = 'other.$ivarName'; final String valueExpression; if (_isPointerField(hostDatatype)) { - final String constructor = + final constructor = 'std::make_unique<${hostDatatype.datatype}>(*$otherIvar)'; valueExpression = hostDatatype.isNullable ? '$otherIvar ? $constructor : nullptr' @@ -1852,7 +2141,7 @@ return EncodableValue(EncodableList{ // Writes a setter treating the type as [type], to allow generating multiple // setter variants. void writeSetter(HostDatatype type) { - const String setterArgumentName = 'value_arg'; + const setterArgumentName = 'value_arg'; _writeFunctionDefinition( indent, setterName, @@ -1901,9 +2190,9 @@ return EncodableValue(EncodableList{ bool sourceIsField = false, }) { if (_isPointerField(type)) { - final String constructor = 'std::make_unique<${type.datatype}>'; + final constructor = 'std::make_unique<${type.datatype}>'; // If the source is a pointer field, it always needs dereferencing. - final String maybeDereference = sourceIsField ? '*' : ''; + final maybeDereference = sourceIsField ? '*' : ''; return type.isNullable ? '$variable ? $constructor(*$variable) : nullptr' : '$constructor($maybeDereference$variable)'; @@ -1923,7 +2212,7 @@ return EncodableValue(EncodableList{ final String errorCondition; final String errorGetter; - const String nullValue = 'EncodableValue()'; + const nullValue = 'EncodableValue()'; if (returnType.isVoid) { nonErrorPath = '${prefix}wrapped.push_back($nullValue);'; errorCondition = 'output.has_value()'; @@ -1934,8 +2223,8 @@ return EncodableValue(EncodableList{ _shortBaseCppTypeForBuiltinDartType, ); - const String extractedValue = 'std::move(output).TakeValue()'; - final String wrapperType = hostType.isBuiltin + const extractedValue = 'std::move(output).TakeValue()'; + final wrapperType = hostType.isBuiltin ? 'EncodableValue' : 'CustomEncodableValue'; if (returnType.isNullable) { @@ -1993,16 +2282,16 @@ ${prefix}reply(EncodableValue(std::move(wrapped)));'''; ) { final String encodableValue; if (!hostType.isBuiltin) { - final String nonNullValue = + final nonNullValue = hostType.isNullable || (!hostType.isEnum && isNestedClass) ? '*$variableName' : variableName; encodableValue = 'CustomEncodableValue($nonNullValue)'; } else if (dartType.baseName == 'Object') { - final String operator = hostType.isNullable ? '*' : ''; + final operator = hostType.isNullable ? '*' : ''; encodableValue = '$operator$variableName'; } else { - final String operator = hostType.isNullable ? '*' : ''; + final operator = hostType.isNullable ? '*' : ''; encodableValue = 'EncodableValue($operator$variableName)'; } @@ -2192,8 +2481,8 @@ String? _baseCppTypeForBuiltinDartType( TypeDeclaration type, { bool includeFlutterNamespace = true, }) { - final String flutterNamespace = includeFlutterNamespace ? 'flutter::' : ''; - final Map cppTypeForDartTypeMap = { + final flutterNamespace = includeFlutterNamespace ? '::flutter::' : ''; + final cppTypeForDartTypeMap = { 'void': 'void', 'bool': 'bool', 'int': 'int64_t', @@ -2241,7 +2530,7 @@ bool _isPointerField(HostDatatype type) { /// Returns the C++ type to use in an argument context without ownership /// transfer for the given base type. String _unownedArgumentType(HostDatatype type) { - final bool isString = type.datatype == 'std::string'; + final isString = type.datatype == 'std::string'; final String baseType = isString ? 'std::string_view' : type.datatype; if (isString || _isPodType(type)) { return type.isNullable ? 'const $baseType*' : baseType; @@ -2315,7 +2604,7 @@ String _flutterApiReturnType(HostDatatype type) { } String _getGuardName(String? headerFileName) { - const String prefix = 'PIGEON_'; + const prefix = 'PIGEON_'; if (headerFileName != null) { return '$prefix${headerFileName.replaceAll('.', '_').toUpperCase()}_'; } else { @@ -2325,7 +2614,7 @@ String _getGuardName(String? headerFileName) { void _writeSystemHeaderIncludeBlock(Indent indent, List headers) { headers.sort(); - for (final String header in headers) { + for (final header in headers) { indent.writeln('#include <$header>'); } } @@ -2352,7 +2641,7 @@ void _writeFunction( // Set the initial indentation. indent.write(''); // Write any starting annotations (e.g., 'static'). - for (final String annotation in startingAnnotations) { + for (final annotation in startingAnnotations) { indent.add('$annotation '); } // Write the signature. @@ -2380,7 +2669,7 @@ void _writeFunction( }, addTrailingNewline: false); } // Write any trailing annotations (e.g., 'const'). - for (final String annotation in trailingAnnotations) { + for (final annotation in trailingAnnotations) { indent.add(' $annotation'); } // Write the initializer list, if any. @@ -2505,7 +2794,7 @@ void _writeAccessBlock( /// Validates an AST to make sure the cpp generator supports everything. List validateCpp(InternalCppOptions options, Root root) { - final List result = []; + final result = []; for (final Api api in root.apis) { for (final Method method in api.methods) { for (final NamedType arg in method.parameters) { diff --git a/packages/pigeon/lib/src/dart/dart_generator.dart b/packages/pigeon/lib/src/dart/dart_generator.dart index a429c9e4cc35..fb65af36f161 100644 --- a/packages/pigeon/lib/src/dart/dart_generator.dart +++ b/packages/pigeon/lib/src/dart/dart_generator.dart @@ -49,7 +49,8 @@ class DartOptions { this.copyrightHeader, this.sourceOutPath, this.testOutPath, - }); + bool ignoreLints = true, + }) : _ignoreLints = ignoreLints; /// A copyright header that will get prepended to generated code. final Iterable? copyrightHeader; @@ -60,25 +61,29 @@ class DartOptions { /// Path to output generated Test file for tests. final String? testOutPath; + /// Whether to ignore lint violations in generated Dart code. + final bool _ignoreLints; + /// Creates a [DartOptions] from a Map representation where: /// `x = DartOptions.fromMap(x.toMap())`. static DartOptions fromMap(Map map) { - final Iterable? copyrightHeader = - map['copyrightHeader'] as Iterable?; + final copyrightHeader = map['copyrightHeader'] as Iterable?; return DartOptions( copyrightHeader: copyrightHeader?.cast(), sourceOutPath: map['sourceOutPath'] as String?, testOutPath: map['testOutPath'] as String?, + ignoreLints: (map['ignoreLints'] as bool?) ?? true, ); } /// Converts a [DartOptions] to a Map representation where: /// `x = DartOptions.fromMap(x.toMap())`. Map toMap() { - final Map result = { + final result = { if (copyrightHeader != null) 'copyrightHeader': copyrightHeader!, if (sourceOutPath != null) 'sourceOutPath': sourceOutPath!, if (testOutPath != null) 'testOutPath': testOutPath!, + 'ignoreLints': _ignoreLints, }; return result; } @@ -93,7 +98,12 @@ class DartOptions { /// Options that control how Dart code will be generated. class InternalDartOptions extends InternalOptions { /// Constructor for InternalDartOptions. - const InternalDartOptions({this.copyrightHeader, this.dartOut, this.testOut}); + const InternalDartOptions({ + this.copyrightHeader, + this.dartOut, + this.testOut, + required bool ignoreLints, + }) : _ignoreLints = ignoreLints; /// Creates InternalDartOptions from DartOptions. InternalDartOptions.fromDartOptions( @@ -103,7 +113,8 @@ class InternalDartOptions extends InternalOptions { String? testOut, }) : copyrightHeader = copyrightHeader ?? options.copyrightHeader, dartOut = (dartOut ?? options.sourceOutPath)!, - testOut = testOut ?? options.testOutPath; + testOut = testOut ?? options.testOutPath, + _ignoreLints = options._ignoreLints; /// A copyright header that will get prepended to generated code. final Iterable? copyrightHeader; @@ -113,6 +124,9 @@ class InternalDartOptions extends InternalOptions { /// Path to output generated Test file for tests. final String? testOut; + + /// Whether to ignore lint violations in generated Dart code. + final bool _ignoreLints; } /// Class that manages all Dart code generation. @@ -137,9 +151,20 @@ class DartGenerator extends StructuredGenerator { } indent.writeln('// ${getGeneratedCodeWarning()}'); indent.writeln('// $seeAlsoWarning'); - indent.writeln( - '// 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', - ); + indent.writeln('// ignore_for_file: unused_import, unused_shown_name'); + if (generatorOptions._ignoreLints) { + indent.writeln('// ignore_for_file: type=lint'); + } else { + // Just ignore the lint rules we know we violate and which we care about + // in our own checked-in generated files. + indent.writeln( + '// ignore_for_file: public_member_api_docs, ' + 'non_constant_identifier_names, avoid_as, unnecessary_parenthesis, ' + 'prefer_null_aware_operators, omit_local_variable_types, ' + 'omit_obvious_local_variable_types, unnecessary_import, ' + 'no_leading_underscores_for_local_identifiers', + ); + } indent.newln(); } @@ -155,19 +180,19 @@ class DartGenerator extends StructuredGenerator { indent.writeln("import 'dart:io' show Platform;"); } indent.writeln( - "import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List;", + "import 'dart:typed_data' show Float64List, Int32List, Int64List;", ); indent.newln(); - indent.writeln( - "import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer${root.containsProxyApi ? ', immutable, protected, visibleForTesting' : ''};", - ); indent.writeln("import 'package:flutter/services.dart';"); if (root.containsProxyApi) { indent.writeln( "import 'package:flutter/widgets.dart' show WidgetsFlutterBinding;", ); } + indent.writeln( + "import 'package:meta/meta.dart' show immutable, protected, visibleForTesting;", + ); } @override @@ -211,8 +236,8 @@ class DartGenerator extends StructuredGenerator { classDefinition.documentationComments, docCommentSpec, ); - final String sealed = classDefinition.isSealed ? 'sealed ' : ''; - final String implements = classDefinition.superClassName != null + final sealed = classDefinition.isSealed ? 'sealed ' : ''; + final implements = classDefinition.superClassName != null ? 'extends ${classDefinition.superClassName} ' : ''; @@ -232,7 +257,7 @@ class DartGenerator extends StructuredGenerator { docCommentSpec, ); - final String datatype = addGenericTypesNullable(field.type); + final String datatype = addGenericTypes(field.type); indent.writeln('$datatype ${field.name};'); indent.newln(); } @@ -270,11 +295,10 @@ class DartGenerator extends StructuredGenerator { for (final NamedType field in getFieldsInSerializationOrder( classDefinition, )) { - final String required = - !field.type.isNullable && field.defaultValue == null + final required = !field.type.isNullable && field.defaultValue == null ? 'required ' : ''; - final String defaultValueString = field.defaultValue == null + final defaultValueString = field.defaultValue == null ? '' : ' = ${field.defaultValue}'; indent.writeln('${required}this.${field.name}$defaultValueString,'); @@ -316,24 +340,6 @@ class DartGenerator extends StructuredGenerator { Class classDefinition, { required String dartPackageName, }) { - void writeValueDecode(NamedType field, int index) { - final String resultAt = 'result[$index]'; - final String castCallPrefix = field.type.isNullable ? '?' : '!'; - final String genericType = _makeGenericTypeArguments(field.type); - final String castCall = _makeGenericCastCall(field.type); - final String nullableTag = field.type.isNullable ? '?' : ''; - if (field.type.typeArguments.isNotEmpty) { - indent.add('($resultAt as $genericType?)$castCallPrefix$castCall'); - } else { - final String castCallForcePrefix = field.type.isNullable ? '' : '!'; - final String castString = field.type.baseName == 'Object' - ? '' - : ' as $genericType$nullableTag'; - - indent.add('$resultAt$castCallForcePrefix$castString'); - } - } - indent.write('static ${classDefinition.name} decode(Object result) '); indent.addScoped('{', '}', () { indent.writeln('result as List;'); @@ -344,7 +350,7 @@ class DartGenerator extends StructuredGenerator { final NamedType field, ) { indent.write('${field.name}: '); - writeValueDecode(field, index); + indent.add(_castValue('result[$index]', field.type)); indent.addln(','); }); }); @@ -359,6 +365,9 @@ class DartGenerator extends StructuredGenerator { Class classDefinition, { required String dartPackageName, }) { + final Iterable fields = getFieldsInSerializationOrder( + classDefinition, + ); indent.writeln('@override'); indent.writeln('// ignore: avoid_equals_and_hash_code_on_mutable_classes'); indent.writeScoped('bool operator ==(Object other) {', '}', () { @@ -369,16 +378,28 @@ class DartGenerator extends StructuredGenerator { indent.writeln('return false;'); }, ); - indent.writeScoped('if (identical(this, other)) {', '}', () { + if (fields.isEmpty) { indent.writeln('return true;'); - }); - indent.writeln('return _deepEquals(encode(), other.encode());'); + } else { + indent.writeScoped('if (identical(this, other)) {', '}', () { + indent.writeln('return true;'); + }); + final String comparisons = fields + .map( + (NamedType field) => + '_deepEquals(${field.name}, other.${field.name})', + ) + .join(' && '); + indent.writeln('return $comparisons;'); + } }); + indent.newln(); indent.writeln('@override'); indent.writeln('// ignore: avoid_equals_and_hash_code_on_mutable_classes'); - indent.writeln('int get hashCode => Object.hashAll(_toList())'); - indent.addln(';'); + indent.writeln( + 'int get hashCode => _deepHash([runtimeType, ..._toList()]);', + ); } @override @@ -403,7 +424,7 @@ class DartGenerator extends StructuredGenerator { indent.writeln('writeValue(buffer, value.index);'); } } else { - final String encodeString = customType.type == CustomTypes.customClass + final encodeString = customType.type == CustomTypes.customClass ? '.encode()' : '.index'; indent.writeln( @@ -419,7 +440,7 @@ class DartGenerator extends StructuredGenerator { EnumeratedType customType, int nonSerializedClassCount, ) { - indent.writeln('case ${customType.offset(nonSerializedClassCount)}: '); + indent.writeln('case ${customType.offset(nonSerializedClassCount)}:'); indent.nest(1, () { if (customType.type == CustomTypes.customClass) { if (customType.offset(nonSerializedClassCount) == @@ -434,7 +455,7 @@ class DartGenerator extends StructuredGenerator { ); } } else if (customType.type == CustomTypes.customEnum) { - indent.writeln('final int? value = readValue(buffer) as int?;'); + indent.writeln('final value = readValue(buffer) as int?;'); indent.writeln( 'return value == null ? null : ${customType.name}.values[value];', ); @@ -442,7 +463,7 @@ class DartGenerator extends StructuredGenerator { }); } - final EnumeratedType overflowClass = EnumeratedType( + final overflowClass = EnumeratedType( _overflowClassName, maximumCodecFieldKey, CustomTypes.customClass, @@ -467,7 +488,7 @@ class DartGenerator extends StructuredGenerator { indent.writeln('buffer.putUint8(4);'); indent.writeln('buffer.putInt64(value);'); }, addTrailingNewline: false); - int nonSerializedClassCount = 0; + var nonSerializedClassCount = 0; enumerate(enumeratedTypes, ( int index, final EnumeratedType customType, @@ -488,8 +509,8 @@ class DartGenerator extends StructuredGenerator { indent.addScoped('{', '}', () { indent.write('switch (type) '); indent.addScoped('{', '}', () { - int nonSerializedClassCount = 0; - for (final EnumeratedType customType in enumeratedTypes) { + var nonSerializedClassCount = 0; + for (final customType in enumeratedTypes) { if (customType.associatedClass?.isSealed ?? false) { nonSerializedClassCount++; } else if (customType.offset(nonSerializedClassCount) < @@ -517,6 +538,7 @@ class DartGenerator extends StructuredGenerator { /// Writes the code for host [Api], [api]. /// Example: + /// ```dart /// class FooCodec extends StandardMessageCodec {...} /// /// abstract class Foo { @@ -524,6 +546,7 @@ class DartGenerator extends StructuredGenerator { /// int add(int x, int y); /// static void setUp(Foo api, {BinaryMessenger? binaryMessenger}) {...} /// } + /// ``` @override void writeFlutterApi( InternalDartOptions generatorOptions, @@ -557,8 +580,8 @@ class DartGenerator extends StructuredGenerator { final bool isAsync = func.isAsynchronous; final String returnType = isAsync - ? 'Future<${addGenericTypesNullable(func.returnType)}>' - : addGenericTypesNullable(func.returnType); + ? 'Future<${addGenericTypes(func.returnType)}>' + : addGenericTypes(func.returnType); final String argSignature = _getMethodParameterSignature( func.parameters, ); @@ -593,6 +616,7 @@ class DartGenerator extends StructuredGenerator { /// Writes the code for host [Api], [api]. /// Example: + /// ```dart /// class FooCodec extends StandardMessageCodec {...} /// /// class Foo { @@ -600,6 +624,7 @@ class DartGenerator extends StructuredGenerator { /// static const MessageCodec codec = FooCodec(); /// Future add(int x, int y) async {...} /// } + /// ``` /// /// Messages will be sent and received in a list. /// @@ -617,7 +642,7 @@ class DartGenerator extends StructuredGenerator { required String dartPackageName, }) { indent.newln(); - bool first = true; + var first = true; addDocumentationComments(indent, api.documentationComments, docCommentSpec); indent.write('class ${api.name} '); indent.addScoped('{', '}', () { @@ -707,21 +732,21 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; Indent indent, { required String dartPackageName, }) { - final cb.Parameter binaryMessengerParameter = cb.Parameter( + final binaryMessengerParameter = cb.Parameter( (cb.ParameterBuilder builder) => builder ..name = 'binaryMessenger' ..type = cb.refer('BinaryMessenger?') ..named = true, ); - final cb.Field binaryMessengerField = cb.Field( + final binaryMessengerField = cb.Field( (cb.FieldBuilder builder) => builder ..name = '${varNamePrefix}binaryMessenger' ..type = cb.refer('BinaryMessenger?') ..modifier = cb.FieldModifier.final$, ); - final cb.Class instanceManagerApi = cb.Class( + final instanceManagerApi = cb.Class( (cb.ClassBuilder builder) => builder ..name = dartInstanceManagerApiClassName ..docs.add( @@ -776,9 +801,9 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; ]) ..body = cb.Block.of( cb.Block((cb.BlockBuilder builder) { - final StringBuffer messageHandlerSink = StringBuffer(); + final messageHandlerIndent = Indent(); writeFlutterMethodMessageHandler( - Indent(messageHandlerSink), + messageHandlerIndent, name: 'removeStrongReferenceName', parameters: [ Parameter( @@ -807,7 +832,7 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; }, ); builder.statements.add( - cb.Code(messageHandlerSink.toString()), + cb.Code(messageHandlerIndent.toString()), ); }).statements, ); @@ -827,9 +852,9 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; ), ) ..body = cb.Block((cb.BlockBuilder builder) { - final StringBuffer messageCallSink = StringBuffer(); + final messageCallIndent = Indent(); writeHostMethodMessageCall( - Indent(messageCallSink), + messageCallIndent, addSuffixVariable: false, channelName: makeRemoveStrongReferenceChannelName( dartPackageName, @@ -846,7 +871,7 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; returnType: const TypeDeclaration.voidDeclaration(), ); builder.statements.addAll([ - cb.Code(messageCallSink.toString()), + cb.Code(messageCallIndent.toString()), ]); }); }), @@ -861,23 +886,23 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; '/// This is typically called after a hot restart.', ]) ..body = cb.Block((cb.BlockBuilder builder) { - final StringBuffer messageCallSink = StringBuffer(); + final messageCallIndent = Indent(); writeHostMethodMessageCall( - Indent(messageCallSink), + messageCallIndent, addSuffixVariable: false, channelName: makeClearChannelName(dartPackageName), parameters: [], returnType: const TypeDeclaration.voidDeclaration(), ); builder.statements.addAll([ - cb.Code(messageCallSink.toString()), + cb.Code(messageCallIndent.toString()), ]); }); }), ]), ); - final cb.DartEmitter emitter = cb.DartEmitter(useNullSafetySyntax: true); + final emitter = cb.DartEmitter(useNullSafetySyntax: true); indent.format( DartFormatter( languageVersion: Version(3, 6, 0), @@ -902,14 +927,14 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; AstProxyApi api, { required String dartPackageName, }) { - const String codecName = '_${classNamePrefix}ProxyApiBaseCodec'; + const codecName = '_${classNamePrefix}ProxyApiBaseCodec'; // Each API has a private codec instance used by every host method, // constructor, or non-static field. - final String codecInstanceName = '_${varNamePrefix}codec${api.name}'; + final codecInstanceName = '_${varNamePrefix}codec${api.name}'; // AST class used by code_builder to generate the code. - final cb.Class proxyApi = cb.Class( + final proxyApi = cb.Class( (cb.ClassBuilder builder) => builder ..name = api.name ..extend = api.superClass != null @@ -1016,7 +1041,7 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; ), ); - final cb.DartEmitter emitter = cb.DartEmitter(useNullSafetySyntax: true); + final emitter = cb.DartEmitter(useNullSafetySyntax: true); indent.format(_formatter.format('${proxyApi.accept(emitter)}')); } @@ -1031,7 +1056,7 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; required String dartPackageName, required String dartOutputPackageName, }) { - final Indent indent = Indent(sink); + final indent = Indent(); final String sourceOutPath = generatorOptions.dartOut ?? ''; final String testOutPath = generatorOptions.testOut ?? ''; _writeTestPrologue(generatorOptions, root, indent); @@ -1064,7 +1089,7 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; ); for (final AstHostApi api in root.apis.whereType()) { if (api.dartHostTestHandler != null) { - final AstFlutterApi mockApi = AstFlutterApi( + final mockApi = AstFlutterApi( name: api.dartHostTestHandler!, methods: api.methods, documentationComments: api.documentationComments, @@ -1081,6 +1106,7 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; ); } } + sink.write(indent.toString()); } /// Writes file header to sink. @@ -1091,7 +1117,7 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; indent.writeln('// ${getGeneratedCodeWarning()}'); indent.writeln('// $seeAlsoWarning'); indent.writeln( - '// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, unnecessary_import, no_leading_underscores_for_local_identifiers', + '// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, unnecessary_import, no_leading_underscores_for_local_identifiers, omit_obvious_local_variable_types', ); indent.writeln('// ignore_for_file: avoid_relative_lib_imports'); } @@ -1118,7 +1144,7 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; required String dartPackageName, }) { if (root.containsHostApi || root.containsProxyApi) { - _writeCreateConnectionError(indent); + _writeExtractReplyValueOrThrow(indent); } if (root.containsFlutterApi || root.containsProxyApi || @@ -1127,6 +1153,7 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; } if (root.classes.isNotEmpty) { _writeDeepEquals(indent); + _writeDeepHash(indent); } if (root.containsProxyApi) { proxy_api_helper.writeProxyApiPigeonOverrides( @@ -1137,7 +1164,7 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; } } - /// Writes [wrapResponse] method. + /// Writes the `wrapResponse` method. void _writeWrapResponse(InternalDartOptions opt, Root root, Indent indent) { indent.newln(); indent.writeScoped( @@ -1160,30 +1187,105 @@ final BinaryMessenger? ${varNamePrefix}binaryMessenger; void _writeDeepEquals(Indent indent) { indent.format(r''' bool _deepEquals(Object? a, Object? b) { + if (identical(a, b)) { + return true; + } + if (a is double && b is double) { + if (a.isNaN && b.isNaN) { + return true; + } + return a == b; + } if (a is List && b is List) { return a.length == b.length && a.indexed - .every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); + .every(((int, dynamic) item) => _deepEquals(item.$2, b[item.$1])); } if (a is Map && b is Map) { - return a.length == b.length && a.entries.every((MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key])); + if (a.length != b.length) { + return false; + } + for (final MapEntry entryA in a.entries) { + bool found = false; + for (final MapEntry entryB in b.entries) { + if (_deepEquals(entryA.key, entryB.key)) { + if (_deepEquals(entryA.value, entryB.value)) { + found = true; + break; + } else { + return false; + } + } + } + if (!found) { + return false; + } + } + return true; } return a == b; } '''); } - void _writeCreateConnectionError(Indent indent) { + void _writeDeepHash(Indent indent) { + indent.format(r''' +int _deepHash(Object? value) { + if (value is List) { + return Object.hashAll(value.map(_deepHash)); + } + if (value is Map) { + int result = 0; + for (final MapEntry entry in value.entries) { + result += (_deepHash(entry.key) * 31) ^ _deepHash(entry.value); + } + return result; + } + if (value is double && value.isNaN) { + // Normalize NaN to a consistent hash. + return 0x7FF8000000000000.hashCode; + } + if (value is double && value == 0.0) { + // Normalize -0.0 to 0.0 so they have the same hash code. + return 0.0.hashCode; + } + return value.hashCode; +} +'''); + } + + static void _writeExtractReplyValueOrThrow(Indent indent) { indent.newln(); indent.format(''' -PlatformException _createConnectionError(String channelName) { -\treturn PlatformException( -\t\tcode: 'channel-error', -\t\tmessage: 'Unable to establish connection on channel: "\$channelName".', -\t); -}'''); +Object? _extractReplyValueOrThrow( +\t\tList? replyList, +\t\tString channelName, { +\t\trequired bool isNullValid, +}) { +\tif (replyList == null) { +\t\tthrow PlatformException( +\t\t\tcode: 'channel-error', +\t\t\tmessage: 'Unable to establish connection on channel: "\$channelName".', +\t\t); +\t} else if (replyList.length > 1) { +\t\tthrow PlatformException( +\t\t\tcode: replyList[0]! as String, +\t\t\tmessage: replyList[1] as String?, +\t\t\tdetails: replyList[2], +\t\t);'''); + // On iOS we can return nil from functions to accommodate error + // handling. Returning a nil value and not returning an error is an + // exception. + indent.format(''' +\t} else if (!isNullValid && (replyList.isNotEmpty && replyList[0] == null)) { +\t\tthrow PlatformException( +\t\t\tcode: 'null-error', +\t\t\tmessage: 'Host platform returned null value for non-null return value.', +\t\t); +\t} +\treturn replyList.firstOrNull; +} +'''); } void _writeCodecOverflowUtilities(Indent indent, List types) { @@ -1215,7 +1317,7 @@ if (wrapped == null) { } '''); indent.writeScoped('switch (type) {', '}', () { - int nonSerializedClassCount = 0; + var nonSerializedClassCount = 0; for (int i = totalCustomCodecKeysAllowed; i < types.length; i++) { if (types[i].associatedClass?.isSealed ?? false) { nonSerializedClassCount++; @@ -1253,7 +1355,7 @@ if (wrapped == null) { addDocumentationComments(indent, documentationComments, docCommentSpec); final String argSignature = _getMethodParameterSignature(parameters); indent.write( - 'Future<${addGenericTypesNullable(returnType)}> $name($argSignature) async ', + 'Future<${addGenericTypes(returnType)}> $name($argSignature) async ', ); indent.addScoped('{', '}', () { writeHostMethodMessageCall( @@ -1275,7 +1377,7 @@ if (wrapped == null) { required bool addSuffixVariable, bool insideAsyncMethod = true, }) { - String sendArgument = 'null'; + var sendArgument = 'null'; if (parameters.isNotEmpty) { final Iterable argExpressions = indexMap(parameters, ( int index, @@ -1286,13 +1388,13 @@ if (wrapped == null) { }); sendArgument = '[${argExpressions.join(', ')}]'; } - final String channelSuffix = addSuffixVariable ? '\$$_suffixVarName' : ''; - final String constOrFinal = addSuffixVariable ? 'final' : 'const'; + final channelSuffix = addSuffixVariable ? '\$$_suffixVarName' : ''; + final constOrFinal = addSuffixVariable ? 'final' : 'const'; indent.writeln( - "$constOrFinal String ${varNamePrefix}channelName = '$channelName$channelSuffix';", + "$constOrFinal ${varNamePrefix}channelName = '$channelName$channelSuffix';", ); indent.writeScoped( - 'final BasicMessageChannel ${varNamePrefix}channel = BasicMessageChannel(', + 'final ${varNamePrefix}channel = BasicMessageChannel(', ');', () { indent.writeln('${varNamePrefix}channelName,'); @@ -1300,24 +1402,8 @@ if (wrapped == null) { indent.writeln('binaryMessenger: ${varNamePrefix}binaryMessenger,'); }, ); - final String returnTypeName = _makeGenericTypeArguments(returnType); - final String genericCastCall = _makeGenericCastCall(returnType); - const String accessor = '${varNamePrefix}replyList[0]'; - // Avoid warnings from pointlessly casting to `Object?`. - final String nullablyTypedAccessor = returnTypeName == 'Object' - ? accessor - : '($accessor as $returnTypeName?)'; - final String nullHandler = returnType.isNullable - ? (genericCastCall.isEmpty ? '' : '?') - : '!'; - String returnStatement = 'return'; - if (!returnType.isVoid) { - returnStatement = - '$returnStatement $nullablyTypedAccessor$nullHandler$genericCastCall'; - } - returnStatement = '$returnStatement;'; - const String sendFutureVar = '${varNamePrefix}sendFuture'; + const sendFutureVar = '${varNamePrefix}sendFuture'; indent.writeln( 'final Future $sendFutureVar = ${varNamePrefix}channel.send($sendArgument);', ); @@ -1330,31 +1416,23 @@ if (wrapped == null) { } indent.format(''' -final List? ${varNamePrefix}replyList = -\t\tawait $sendFutureVar as List?; -if (${varNamePrefix}replyList == null) { -\tthrow _createConnectionError(${varNamePrefix}channelName); -} else if (${varNamePrefix}replyList.length > 1) { -\tthrow PlatformException( -\t\tcode: ${varNamePrefix}replyList[0]! as String, -\t\tmessage: ${varNamePrefix}replyList[1] as String?, -\t\tdetails: ${varNamePrefix}replyList[2], -\t);'''); - // On iOS we can return nil from functions to accommodate error - // handling. Returning a nil value and not returning an error is an - // exception. - if (!returnType.isNullable && !returnType.isVoid) { - indent.format(''' -} else if (${varNamePrefix}replyList[0] == null) { -\tthrow PlatformException( -\t\tcode: 'null-error', -\t\tmessage: 'Host platform returned null value for non-null return value.', -\t);'''); +final ${varNamePrefix}replyList = await $sendFutureVar as List?; +'''); + final extractCall = + ''' +_extractReplyValueOrThrow( +\t\t${varNamePrefix}replyList, +\t\t${varNamePrefix}channelName, +\t\tisNullValid: ${returnType.isNullable || returnType.isVoid}, +) +'''; + if (returnType.isVoid) { + indent.format('$extractCall;'); + } else { + const accessor = '${varNamePrefix}replyValue'; + indent.format('final Object? $accessor = $extractCall;'); + indent.format('return ${_castValue(accessor, returnType)};'); } - indent.format(''' -} else { -\t$returnStatement -}'''); if (!insideAsyncMethod) { indent.dec(); @@ -1384,16 +1462,14 @@ if (${varNamePrefix}replyList == null) { indent.write(''); indent.addScoped('{', '}', () { indent.writeln( - 'final BasicMessageChannel ${varNamePrefix}channel = BasicMessageChannel(', + 'final ${varNamePrefix}channel = BasicMessageChannel(', ); indent.nest(2, () { - final String channelSuffix = addSuffixVariable - ? r'$messageChannelSuffix' - : ''; + final channelSuffix = addSuffixVariable ? r'$messageChannelSuffix' : ''; indent.writeln("'$channelName$channelSuffix', $pigeonChannelCodec,"); indent.writeln('binaryMessenger: binaryMessenger);'); }); - final String messageHandlerSetterWithOpeningParentheses = isMockHandler + final messageHandlerSetterWithOpeningParentheses = isMockHandler ? '_testBinaryMessengerBinding!.defaultBinaryMessenger.setMockDecodedMessageHandler(${varNamePrefix}channel, ' : '${varNamePrefix}channel.setMessageHandler('; indent.write('if ($nullHandlerExpression) '); @@ -1406,67 +1482,50 @@ if (${varNamePrefix}replyList == null) { '$messageHandlerSetterWithOpeningParentheses(Object? message) async ', ); indent.addScoped('{', '});', () { - final String returnTypeString = addGenericTypesNullable(returnType); - final bool isAsync = isAsynchronous; - const String emptyReturnStatement = - 'return wrapResponse(empty: true);'; + final String returnTypeString = addGenericTypes(returnType); + const emptyReturnStatement = 'return wrapResponse(empty: true);'; String call; if (parameters.isEmpty) { call = 'api.$name()'; } else { - indent.writeln('assert(message != null,'); - indent.writeln("'Argument for $channelName was null.');"); - const String argsArray = 'args'; + const argsArray = 'args'; indent.writeln( - 'final List $argsArray = (message as List?)!;', + 'final List $argsArray = message! as List;', ); - String argNameFunc(int index, NamedType type) => - _getSafeArgumentName(index, type); enumerate(parameters, (int count, NamedType arg) { - final String argType = _addGenericTypes(arg.type); - final String argName = argNameFunc(count, arg); - final String genericArgType = _makeGenericTypeArguments(arg.type); - final String castCall = _makeGenericCastCall(arg.type); - - final String leftHandSide = 'final $argType? $argName'; - + final String argType = addGenericTypes(arg.type); + final String argName = _getSafeArgumentName(count, arg); + final argValue = '$argsArray[$count]'; indent.writeln( - '$leftHandSide = ($argsArray[$count] as $genericArgType?)${castCall.isEmpty ? '' : '?$castCall'};', + 'final $argType $argName = ${_castValue(argValue, arg.type)};', ); - - if (!arg.type.isNullable) { - indent.writeln('assert($argName != null,'); - indent.writeln( - " 'Argument for $channelName was null, expected non-null $argType.');", - ); - } }); final Iterable argNames = indexMap(parameters, ( int index, Parameter field, ) { final String name = _getSafeArgumentName(index, field); - return '${field.isNamed ? '${field.name}: ' : ''}$name${field.type.isNullable ? '' : '!'}'; + return '${field.isNamed ? '${field.name}: ' : ''}$name'; }); call = onCreateApiCall(name, parameters, argNames); } indent.writeScoped('try {', '} ', () { if (returnType.isVoid) { - if (isAsync) { + if (isAsynchronous) { indent.writeln('await $call;'); } else { indent.writeln('$call;'); } indent.writeln(emptyReturnStatement); } else { - if (isAsync) { + if (isAsynchronous) { indent.writeln('final $returnTypeString output = await $call;'); } else { indent.writeln('final $returnTypeString output = $call;'); } - const String returnExpression = 'output'; - final String returnStatement = isMockHandler + const returnExpression = 'output'; + final returnStatement = isMockHandler ? 'return [$returnExpression];' : 'return wrapResponse(result: $returnExpression);'; indent.writeln(returnStatement); @@ -1497,7 +1556,7 @@ if (${varNamePrefix}replyList == null) { /// Converts a [TypeDeclaration] to a `code_builder` Reference. cb.Reference refer(TypeDeclaration type, {bool asFuture = false}) { - final String symbol = addGenericTypesNullable(type); + final String symbol = addGenericTypes(type); return cb.refer(asFuture ? 'Future<$symbol>' : symbol); } @@ -1508,19 +1567,41 @@ String _escapeForDartSingleQuotedString(String raw) { .replaceAll(r"'", r"\'"); } -/// Creates a Dart type where all type arguments are [Objects]. +/// Creates a Dart type where all type arguments are [Object]s. String _makeGenericTypeArguments(TypeDeclaration type) { - return type.typeArguments.isNotEmpty - ? '${type.baseName}<${type.typeArguments.map((TypeDeclaration e) => 'Object?').join(', ')}>' - : _addGenericTypes(type); + if (type.typeArguments.isEmpty) { + return addGenericTypes(type); + } + + final withTypeArguments = + '${type.baseName}<${type.typeArguments.map((TypeDeclaration e) => 'Object?').join(', ')}>'; + return '$withTypeArguments${type.isNullable ? '?' : ''}'; } -/// Creates a `.cast<>` call for an type. Returns an empty string if the -/// type has no type arguments. -String _makeGenericCastCall(TypeDeclaration type) { - return type.typeArguments.isNotEmpty - ? '.cast<${_flattenTypeArguments(type.typeArguments)}>()' - : ''; +/// Casts a value to the expected type, considering nullability, and generic +/// types. +String _castValue(String value, TypeDeclaration type) { + final String typeWithTypeArgs = _makeGenericTypeArguments(type); + final nullAssert = type.isNullable ? '' : '!'; + value = '$value$nullAssert'; + if (type.typeArguments.isEmpty && type.baseName == 'Object') { + return value; + } + + final valueWithTypeCast = '$value as $typeWithTypeArgs'; + + final List typeArguments = type.typeArguments; + if (typeArguments.isEmpty) { + return valueWithTypeCast; + } + if (typeArguments.every((e) => e.baseName == 'Object' && e.isNullable)) { + return valueWithTypeCast; + } + + final nullAwareOperator = type.isNullable ? '?' : ''; + final castCall = + '$nullAwareOperator.cast<${_flattenTypeArguments(typeArguments)}>()'; + return '($valueWithTypeCast)$castCall'; } /// Returns an argument name that can be used in a context where it is possible to collide. @@ -1537,7 +1618,7 @@ String _getMethodParameterSignature( Iterable parameters, { bool addTrailingComma = false, }) { - String signature = ''; + var signature = ''; if (parameters.isEmpty) { return signature; } @@ -1553,13 +1634,11 @@ String _getMethodParameterSignature( .toList(); String getParameterString(Parameter p) { - final String required = p.isRequired && !p.isPositional ? 'required ' : ''; + final required = p.isRequired && !p.isPositional ? 'required ' : ''; - final String type = addGenericTypesNullable(p.type); + final String type = addGenericTypes(p.type); - final String defaultValue = p.defaultValue == null - ? '' - : ' = ${p.defaultValue}'; + final defaultValue = p.defaultValue == null ? '' : ' = ${p.defaultValue}'; return '$required$type ${p.name}$defaultValue'; } @@ -1577,20 +1656,18 @@ String _getMethodParameterSignature( if (requiredPositionalParams.isNotEmpty) { signature = baseParameterString; } - final String trailingComma = + final trailingComma = optionalPositionalParams.isNotEmpty || namedParams.isNotEmpty ? ',' : ''; - final String baseParams = signature.isNotEmpty - ? '$signature$trailingComma ' - : ''; + final baseParams = signature.isNotEmpty ? '$signature$trailingComma ' : ''; if (optionalPositionalParams.isNotEmpty) { - final String trailingComma = + final trailingComma = requiredPositionalParams.length + optionalPositionalParams.length > 2 ? ',' : ''; return '$baseParams[$optionalParameterString$trailingComma]'; } if (namedParams.isNotEmpty) { - final String trailingComma = + final trailingComma = addTrailingComma || requiredPositionalParams.length + namedParams.length > 2 ? ', ' @@ -1612,33 +1689,26 @@ String _flattenTypeArguments(List args) { .join(', '); } -/// Creates the type declaration for use in Dart code from a [NamedType] making sure -/// that type arguments are used for primitive generic types. -String _addGenericTypes(TypeDeclaration type) { +/// Returns the string representation of a [TypeDeclaration], including type +/// arguments and a nullability suffix, if the type is nullable. +String addGenericTypes(TypeDeclaration type) { final List typeArguments = type.typeArguments; - switch (type.baseName) { - case 'List': - return typeArguments.isEmpty + final String genericType = switch (type.baseName) { + 'List' => + typeArguments.isEmpty ? 'List' - : 'List<${_flattenTypeArguments(typeArguments)}>'; - case 'Map': - return typeArguments.isEmpty + : 'List<${_flattenTypeArguments(typeArguments)}>', + 'Map' => + typeArguments.isEmpty ? 'Map' - : 'Map<${_flattenTypeArguments(typeArguments)}>'; - default: - return type.baseName; - } -} - -/// Converts the type signature of a [TypeDeclaration] that include generic -/// types. -String addGenericTypesNullable(TypeDeclaration type) { - final String genericType = _addGenericTypes(type); + : 'Map<${_flattenTypeArguments(typeArguments)}>', + _ => type.baseName, + }; return type.isNullable ? '$genericType?' : genericType; } /// Converts [inputPath] to a posix absolute path. String _posixify(String inputPath) { - final path.Context context = path.Context(style: path.Style.posix); + final context = path.Context(style: path.Style.posix); return context.fromUri(path.toUri(path.absolute(inputPath))); } diff --git a/packages/pigeon/lib/src/dart/proxy_api_generator_helper.dart b/packages/pigeon/lib/src/dart/proxy_api_generator_helper.dart index 369a7913321c..7a95b1327ea5 100644 --- a/packages/pigeon/lib/src/dart/proxy_api_generator_helper.dart +++ b/packages/pigeon/lib/src/dart/proxy_api_generator_helper.dart @@ -43,14 +43,12 @@ Iterable asConstructorParameters({ ); } - for (final ApiField field in unattachedFields) { + for (final field in unattachedFields) { yield cb.Parameter( (cb.ParameterBuilder builder) => builder ..name = field.name ..named = true - ..type = defineType - ? cb.refer(addGenericTypesNullable(field.type)) - : null + ..type = defineType ? cb.refer(addGenericTypes(field.type)) : null ..toThis = !defineType ..required = !field.type.isNullable, ); @@ -83,7 +81,7 @@ Iterable asConstructorParameters({ ); } - for (final Method method in declaredFlutterMethods) { + for (final method in declaredFlutterMethods) { yield cb.Parameter( (cb.ParameterBuilder builder) => builder ..name = method.name @@ -113,7 +111,7 @@ Iterable asConstructorParameters({ Iterable overridesClassConstructors( Iterable proxyApis, ) sync* { - for (final AstProxyApi api in proxyApis) { + for (final api in proxyApis) { final String lowerCamelCaseApiName = toLowerCamelCase(api.name); for (final Constructor constructor in api.constructors) { @@ -166,7 +164,7 @@ Iterable overridesClassConstructors( Iterable overridesClassStaticFields( Iterable proxyApis, ) sync* { - for (final AstProxyApi api in proxyApis) { + for (final api in proxyApis) { final String lowerCamelCaseApiName = toLowerCamelCase(api.name); for (final ApiField field in api.fields.where( @@ -189,7 +187,7 @@ Iterable overridesClassStaticFields( Iterable overridesClassStaticMethods( Iterable proxyApis, ) sync* { - for (final AstProxyApi api in proxyApis) { + for (final api in proxyApis) { final String lowerCamelCaseApiName = toLowerCamelCase(api.name); for (final Method method in api.hostMethods.where( @@ -259,7 +257,7 @@ cb.FunctionType methodAsFunctionType(Method method, {required String apiName}) { cb.refer('$apiName ${classMemberNamePrefix}instance'), ...method.parameters.mapIndexed((int index, NamedType parameter) { return cb.refer( - '${addGenericTypesNullable(parameter.type)} ${getParameterName(index, parameter)}', + '${addGenericTypes(parameter.type)} ${getParameterName(index, parameter)}', ); }), ]), @@ -281,13 +279,13 @@ Iterable staticAttachedFieldsGetters( Iterable fields, { required String apiName, }) sync* { - for (final ApiField field in fields) { + for (final field in fields) { yield cb.Method( (cb.MethodBuilder builder) => builder ..name = field.name ..type = cb.MethodType.getter ..static = true - ..returns = cb.refer(addGenericTypesNullable(field.type)) + ..returns = cb.refer(addGenericTypes(field.type)) ..docs.addAll( asDocumentationComments(field.documentationComments, docCommentSpec), ) @@ -306,7 +304,7 @@ void writeProxyApiPigeonOverrides( required DartFormatter formatter, required Iterable proxyApis, }) { - final cb.Class proxyApiOverrides = cb.Class( + final proxyApiOverrides = cb.Class( (cb.ClassBuilder builder) => builder ..name = proxyApiOverridesClassName ..annotations.add(cb.refer('visibleForTesting')) @@ -325,7 +323,7 @@ void writeProxyApiPigeonOverrides( ..methods.add(overridesClassResetMethod(proxyApis)), ); - final cb.DartEmitter emitter = cb.DartEmitter(useNullSafetySyntax: true); + final emitter = cb.DartEmitter(useNullSafetySyntax: true); indent.format(formatter.format('${proxyApiOverrides.accept(emitter)}')); } @@ -345,20 +343,20 @@ Iterable constructors( required Iterable<(Method, AstProxyApi)> flutterMethodsFromInterfaces, required Iterable declaredFlutterMethods, }) sync* { - final cb.Parameter binaryMessengerParameter = cb.Parameter( + final binaryMessengerParameter = cb.Parameter( (cb.ParameterBuilder builder) => builder ..name = '${classMemberNamePrefix}binaryMessenger' ..named = true ..toSuper = true, ); - for (final Constructor constructor in constructors) { + for (final constructor in constructors) { final String? factoryConstructorName = constructor.name.isNotEmpty ? constructor.name : null; - final String constructorName = + final constructorName = '$classMemberNamePrefix${constructor.name.isNotEmpty ? constructor.name : 'new'}'; - final String overridesConstructorName = constructor.name.isNotEmpty + final overridesConstructorName = constructor.name.isNotEmpty ? '${toLowerCamelCase(apiName)}_${constructor.name}' : '${toLowerCamelCase(apiName)}_new'; @@ -394,17 +392,16 @@ Iterable constructors( ) ..optionalParameters.addAll(parameters) ..body = cb.Block((cb.BlockBuilder builder) { - final Map forwardedParams = + final forwardedParams = { + for (final cb.Parameter parameter in parameters) + parameter.name: cb.refer(parameter.name), + }; + final forwardedParamsWithoutMessengerAndManager = { - for (final cb.Parameter parameter in parameters) + for (final cb.Parameter parameter + in parametersWithoutMessengerAndManager) parameter.name: cb.refer(parameter.name), }; - final Map - forwardedParamsWithoutMessengerAndManager = { - for (final cb.Parameter parameter - in parametersWithoutMessengerAndManager) - parameter.name: cb.refer(parameter.name), - }; builder.statements.addAll([ cb.Code( @@ -462,9 +459,9 @@ Iterable constructors( const cb.Code('super.${classMemberNamePrefix}detached()'), ]) ..body = cb.Block((cb.BlockBuilder builder) { - final StringBuffer messageCallSink = StringBuffer(); + final messageCallIndent = Indent(); DartGenerator.writeHostMethodMessageCall( - Indent(messageCallSink), + messageCallIndent, addSuffixVariable: false, channelName: channelName, insideAsyncMethod: false, @@ -493,7 +490,7 @@ Iterable constructors( cb.Code( 'final BinaryMessenger? ${varNamePrefix}binaryMessenger = ${binaryMessengerParameter.name};', ), - cb.Code(messageCallSink.toString()), + cb.Code(messageCallIndent.toString()), ]); }); }); @@ -561,11 +558,11 @@ cb.Field codecInstanceField({ /// Converts unattached fields from the pigeon AST to `code_builder` /// Fields. Iterable unattachedFields(Iterable fields) sync* { - for (final ApiField field in fields) { + for (final field in fields) { yield cb.Field( (cb.FieldBuilder builder) => builder ..name = field.name - ..type = cb.refer(addGenericTypesNullable(field.type)) + ..type = cb.refer(addGenericTypes(field.type)) ..modifier = cb.FieldModifier.final$ ..docs.addAll( asDocumentationComments(field.documentationComments, docCommentSpec), @@ -583,7 +580,7 @@ Iterable flutterMethodFields( Iterable methods, { required String apiName, }) sync* { - for (final Method method in methods) { + for (final method in methods) { yield cb.Field( (cb.FieldBuilder builder) => builder ..name = method.name @@ -632,7 +629,7 @@ Iterable flutterMethodFields( Iterable interfaceApiFields( Iterable apisOfInterfaces, ) sync* { - for (final AstProxyApi proxyApi in apisOfInterfaces) { + for (final proxyApi in apisOfInterfaces) { for (final Method method in proxyApi.methods) { yield cb.Field( (cb.FieldBuilder builder) => builder @@ -659,7 +656,7 @@ Iterable interfaceApiFields( NamedType parameter, ) { return cb.refer( - '${addGenericTypesNullable(parameter.type)} ${getParameterName(index, parameter)}', + '${addGenericTypes(parameter.type)} ${getParameterName(index, parameter)}', ); }), ]), @@ -680,11 +677,11 @@ Iterable interfaceApiFields( /// final MyOtherProxyApiClass value = _pigeon_value(); /// ``` Iterable attachedFields(Iterable fields) sync* { - for (final ApiField field in fields) { + for (final field in fields) { yield cb.Field( (cb.FieldBuilder builder) => builder ..name = '${field.isStatic ? '_' : ''}${field.name}' - ..type = cb.refer(addGenericTypesNullable(field.type)) + ..type = cb.refer(addGenericTypes(field.type)) ..modifier = cb.FieldModifier.final$ ..static = field.isStatic ..late = !field.isStatic @@ -751,7 +748,7 @@ cb.Method setUpMessageHandlerMethod({ ..requiredParameters.addAll( unattachedFields.mapIndexed((int index, ApiField field) { return cb.refer( - '${addGenericTypesNullable(field.type)} ${getParameterName(index, field)}', + '${addGenericTypes(field.type)} ${getParameterName(index, field)}', ); }), ), @@ -775,7 +772,7 @@ cb.Method setUpMessageHandlerMethod({ NamedType parameter, ) { return cb.refer( - '${addGenericTypesNullable(parameter.type)} ${getParameterName(index, parameter)}', + '${addGenericTypes(parameter.type)} ${getParameterName(index, parameter)}', ); }), ]), @@ -793,10 +790,10 @@ cb.Method setUpMessageHandlerMethod({ ], if (hasCallbackConstructor) ...cb.Block((cb.BlockBuilder builder) { - final StringBuffer messageHandlerSink = StringBuffer(); - const String methodName = '${classMemberNamePrefix}newInstance'; + final messageHandlerIndent = Indent(); + const methodName = '${classMemberNamePrefix}newInstance'; DartGenerator.writeFlutterMethodMessageHandler( - Indent(messageHandlerSink), + messageHandlerIndent, name: methodName, parameters: [ Parameter( @@ -845,13 +842,13 @@ cb.Method setUpMessageHandlerMethod({ ')'; }, ); - builder.statements.add(cb.Code(messageHandlerSink.toString())); + builder.statements.add(cb.Code(messageHandlerIndent.toString())); }).statements, for (final Method method in flutterMethods) ...cb.Block((cb.BlockBuilder builder) { - final StringBuffer messageHandlerSink = StringBuffer(); + final messageHandlerIndent = Indent(); DartGenerator.writeFlutterMethodMessageHandler( - Indent(messageHandlerSink), + messageHandlerIndent, name: method.name, parameters: [ Parameter( @@ -882,11 +879,11 @@ cb.Method setUpMessageHandlerMethod({ Iterable parameters, Iterable safeArgumentNames, ) { - final String nullability = method.isRequired ? '' : '?'; + final nullability = method.isRequired ? '' : '?'; return '($methodName ?? ${safeArgumentNames.first}.$methodName)$nullability.call(${safeArgumentNames.join(',')})'; }, ); - builder.statements.add(cb.Code(messageHandlerSink.toString())); + builder.statements.add(cb.Code(messageHandlerIndent.toString())); }).statements, ]), ); @@ -904,20 +901,19 @@ Iterable attachedFieldMethods( required String codecInstanceName, required String codecName, }) sync* { - for (final ApiField field in fields) { + for (final field in fields) { yield cb.Method((cb.MethodBuilder builder) { - final String type = addGenericTypesNullable(field.type); - const String instanceName = '${varNamePrefix}instance'; - const String identifierInstanceName = - '${varNamePrefix}instanceIdentifier'; + final String type = addGenericTypes(field.type); + const instanceName = '${varNamePrefix}instance'; + const identifierInstanceName = '${varNamePrefix}instanceIdentifier'; builder ..name = '$varNamePrefix${field.name}' ..static = field.isStatic ..returns = cb.refer(type) ..body = cb.Block((cb.BlockBuilder builder) { - final StringBuffer messageCallSink = StringBuffer(); + final messageCallIndent = Indent(); DartGenerator.writeHostMethodMessageCall( - Indent(messageCallSink), + messageCallIndent, addSuffixVariable: false, channelName: makeChannelNameWithStrings( apiName: apiName, @@ -970,7 +966,7 @@ Iterable attachedFieldMethods( ), ], const cb.Code('() async {'), - cb.Code(messageCallSink.toString()), + cb.Code(messageCallIndent.toString()), const cb.Code('}();'), const cb.Code('return $instanceName;'), ]); @@ -990,13 +986,13 @@ Iterable hostMethods( required String codecInstanceName, required String codecName, }) sync* { - for (final Method method in methods) { + for (final method in methods) { assert(method.location == ApiLocation.host); final Iterable parameters = method.parameters.mapIndexed( (int index, NamedType parameter) => cb.Parameter( (cb.ParameterBuilder builder) => builder ..name = getParameterName(index, parameter) - ..type = cb.refer(addGenericTypesNullable(parameter.type)), + ..type = cb.refer(addGenericTypes(parameter.type)), ), ); yield cb.Method( @@ -1025,9 +1021,9 @@ Iterable hostMethods( ], ]) ..body = cb.Block((cb.BlockBuilder builder) { - final StringBuffer messageCallSink = StringBuffer(); + final messageCallIndent = Indent(); DartGenerator.writeHostMethodMessageCall( - Indent(messageCallSink), + messageCallIndent, addSuffixVariable: false, channelName: makeChannelNameWithStrings( apiName: apiName, @@ -1075,7 +1071,7 @@ Iterable hostMethods( const cb.Code( 'final BinaryMessenger? ${varNamePrefix}binaryMessenger = ${classMemberNamePrefix}binaryMessenger;', ), - cb.Code(messageCallSink.toString()), + cb.Code(messageCallIndent.toString()), ]); }), ); diff --git a/packages/pigeon/lib/src/functional.dart b/packages/pigeon/lib/src/functional.dart index c59e6e5391f8..01a9cf8b30a0 100644 --- a/packages/pigeon/lib/src/functional.dart +++ b/packages/pigeon/lib/src/functional.dart @@ -8,8 +8,8 @@ Iterable indexMap( Iterable iterable, U Function(int index, T value) func, ) sync* { - int index = 0; - for (final T value in iterable) { + var index = 0; + for (final value in iterable) { yield func(index, value); ++index; } @@ -17,8 +17,8 @@ Iterable indexMap( /// Performs like [forEach] but invokes [func] with an enumeration. void enumerate(Iterable iterable, void Function(int, T) func) { - int count = 0; - for (final T value in iterable) { + var count = 0; + for (final value in iterable) { func(count, value); ++count; } @@ -62,14 +62,14 @@ Iterable map3( /// Adds [value] to the end of [ts]. Iterable followedByOne(Iterable ts, T value) sync* { - for (final T item in ts) { + for (final item in ts) { yield item; } yield value; } Iterable _count() sync* { - int x = 0; + var x = 0; while (true) { yield x++; } @@ -80,7 +80,7 @@ final Iterable wholeNumbers = _count(); /// Repeats an [item] [n] times. Iterable repeat(T item, int n) sync* { - for (int i = 0; i < n; ++i) { + for (var i = 0; i < n; ++i) { yield item; } } diff --git a/packages/pigeon/lib/src/generator.dart b/packages/pigeon/lib/src/generator.dart index 34e53a7c4418..e0c240b9b794 100644 --- a/packages/pigeon/lib/src/generator.dart +++ b/packages/pigeon/lib/src/generator.dart @@ -40,7 +40,7 @@ abstract class StructuredGenerator StringSink sink, { required String dartPackageName, }) { - final Indent indent = Indent(sink); + final indent = Indent(); writeFilePrologue( generatorOptions, @@ -117,6 +117,8 @@ abstract class StructuredGenerator indent, dartPackageName: dartPackageName, ); + + sink.write(indent.toString()); } /// Adds specified headers to [indent]. diff --git a/packages/pigeon/lib/src/generator_tools.dart b/packages/pigeon/lib/src/generator_tools.dart index 2b687eb632d6..2890bb571542 100644 --- a/packages/pigeon/lib/src/generator_tools.dart +++ b/packages/pigeon/lib/src/generator_tools.dart @@ -15,11 +15,14 @@ import 'generator.dart'; /// The current version of pigeon. /// /// This must match the version in pubspec.yaml. -const String pigeonVersion = '26.1.2'; +const String pigeonVersion = '26.3.1'; + +/// Default plugin package name. +const String defaultPluginPackageName = 'dev.flutter.pigeon'; /// Read all the content from [stdin] to a String. String readStdin() { - final List bytes = []; + final bytes = []; int byte = stdin.readByteSync(); while (byte >= 0) { bytes.add(byte); @@ -31,13 +34,13 @@ String readStdin() { /// True if the generator line number should be printed out at the end of newlines. bool debugGenerators = false; -/// A helper class for managing indentation, wrapping a [StringSink]. +/// A helper class for managing indentation, wrapping a [StringBuffer]. class Indent { - /// Constructor which takes a [StringSink] [Indent] will wrap. - Indent(this._sink); - int _count = 0; - final StringSink _sink; + final StringBuffer _buffer = StringBuffer(); + + @override + String toString() => _buffer.toString(); /// String used for newlines (ex "\n"). String get newline { @@ -64,17 +67,19 @@ class Indent { /// Returns the String representing the current indentation. String str() { - String result = ''; - for (int i = 0; i < _count; i++) { + var result = ''; + for (var i = 0; i < _count; i++) { result += tab; } return result; } - /// Replaces the newlines and tabs of input and adds it to the stream. + /// Replaces the newlines and tabs of [input] and adds the result to the + /// stream. /// - /// [trimIndentation] flag finds the line with the fewest leading empty - /// spaces and trims the beginning of all lines by this number. + /// If the [trimIndentation] parameter is true, this function also finds the + /// smallest leading space count and trims the beginning of all lines by this + /// number. void format( String input, { bool leadingSpace = true, @@ -90,7 +95,7 @@ class Indent { .map((String line) => line.length - line.trimLeft().length) .reduce(min); - for (int i = 0; i < lines.length; ++i) { + for (var i = 0; i < lines.length; ++i) { final String line = lines[i].length >= indentationToRemove ? lines[i].substring(indentationToRemove) : lines[i]; @@ -112,27 +117,27 @@ class Indent { void addScoped( String? begin, String? end, - Function func, { + void Function() func, { bool addTrailingNewline = true, int nestCount = 1, }) { if (begin != null) { - _sink.write(begin + newline); + _buffer.write(begin + newline); } nest(nestCount, func); if (end != null && end.isNotEmpty) { - _sink.write(str() + end); + _buffer.write(str() + end); if (addTrailingNewline) { - _sink.write(newline); + _buffer.write(newline); } } } - /// Like `addScoped` but writes the current indentation level. + /// Like [addScoped] but writes the current indentation. void writeScoped( String? begin, String? end, - Function func, { + void Function() func, { int nestCount = 1, bool addTrailingNewline = true, }) { @@ -148,40 +153,40 @@ class Indent { /// Scoped increase of the indent level. /// /// For the execution of [func] the indentation will be incremented by the given amount. - void nest(int count, Function func) { + void nest(int count, void Function() func) { inc(count); - func(); // ignore: avoid_dynamic_calls + func(); dec(count); } /// Add [text] with indentation and a newline. void writeln(String text) { if (text.isEmpty) { - _sink.write(newline); + _buffer.write(newline); } else { - _sink.write(str() + text + newline); + _buffer.write(str() + text + newline); } } /// Add [text] with indentation. void write(String text) { - _sink.write(str() + text); + _buffer.write(str() + text); } /// Add [text] with a newline. void addln(String text) { - _sink.write(text + newline); + _buffer.write(text + newline); } /// Just adds [text]. void add(String text) { - _sink.write(text); + _buffer.write(text); } /// Adds [lines] number of newlines. void newln([int lines = 1]) { for (; lines > 0; lines--) { - _sink.write(newline); + _buffer.write(newline); } } } @@ -324,7 +329,7 @@ const String generatedCodeWarning = /// Warning printed at the top of all generated code. String getGeneratedCodeWarning() { - final String versionString = includeVersionInGeneratedWarning + final versionString = includeVersionInGeneratedWarning ? ' (v$pigeonVersion)' : ''; return 'Autogenerated from Pigeon$versionString, do not edit directly.'; @@ -396,7 +401,7 @@ bool isVoid(TypeMirror type) { /// Adds the [lines] to [indent]. void addLines(Indent indent, Iterable lines, {String? linePrefix}) { final String prefix = linePrefix ?? ''; - for (final String line in lines) { + for (final line in lines) { indent.writeln(line.isNotEmpty ? '$prefix$line' : prefix.trimRight()); } } @@ -409,7 +414,7 @@ Map mergeMaps( Map base, Map modification, ) { - final Map result = {}; + final result = {}; for (final MapEntry entry in modification.entries) { if (base.containsKey(entry.key)) { final Object entryValue = entry.value; @@ -529,7 +534,7 @@ class _Bag { } void addMany(Iterable keys, Value? value) { - for (final Key key in keys) { + for (final key in keys) { add(key, value); } } @@ -541,8 +546,8 @@ Map> getReferencedTypes( List apis, List classes, ) { - final _Bag references = _Bag(); - for (final Api api in apis) { + final references = _Bag(); + for (final api in apis) { for (final Method method in api.methods) { for (final NamedType field in method.parameters) { references.addMany(_getTypeArguments(field.type), field.offset); @@ -567,7 +572,7 @@ Map> getReferencedTypes( final Set referencedTypeNames = references.map.keys .map((TypeDeclaration e) => e.baseName) .toSet(); - final List classesToCheck = List.from(referencedTypeNames); + final classesToCheck = List.from(referencedTypeNames); while (classesToCheck.isNotEmpty) { final String next = classesToCheck.removeLast(); final Class aClass = classes.firstWhere( @@ -648,7 +653,7 @@ Iterable getEnumeratedTypes( Root root, { bool excludeSealedClasses = false, }) sync* { - int index = 0; + var index = 0; for (final Enum customEnum in root.enums) { yield EnumeratedType( @@ -726,7 +731,7 @@ Iterable asDocumentationComments( DocumentCommentSpecification commentSpec, { List generatorComments = const [], }) sync* { - final List allComments = [ + final allComments = [ ...comments, if (comments.isNotEmpty && generatorComments.isNotEmpty) '', ...generatorComments, @@ -737,7 +742,7 @@ Iterable asDocumentationComments( yield commentSpec.openCommentToken; currentLineOpenToken = commentSpec.blockContinuationToken; } - for (String line in allComments) { + for (var line in allComments) { if (line.isNotEmpty && line[0] != ' ') { line = ' $line'; } @@ -837,7 +842,7 @@ class OutputFileOptions extends InternalOptions { /// Converts strings to Upper Camel Case. String toUpperCamelCase(String text) { - final RegExp separatorPattern = RegExp(r'[ _-]'); + final separatorPattern = RegExp(r'[ _-]'); return text.split(separatorPattern).map((String word) { return word.isEmpty ? '' @@ -847,8 +852,8 @@ String toUpperCamelCase(String text) { /// Converts strings to Lower Camel Case. String toLowerCamelCase(String text) { - final RegExp separatorPattern = RegExp(r'[ _-]'); - bool firstWord = true; + final separatorPattern = RegExp(r'[ _-]'); + var firstWord = true; return text.split(separatorPattern).map((String word) { if (word.isEmpty) { return ''; diff --git a/packages/pigeon/lib/src/gobject/gobject_generator.dart b/packages/pigeon/lib/src/gobject/gobject_generator.dart index 103a2b0f9057..0906c005d78a 100644 --- a/packages/pigeon/lib/src/gobject/gobject_generator.dart +++ b/packages/pigeon/lib/src/gobject/gobject_generator.dart @@ -48,8 +48,7 @@ class GObjectOptions { /// Creates a [GObjectOptions] from a Map representation where: /// `x = GObjectOptions.fromMap(x.toMap())`. static GObjectOptions fromMap(Map map) { - final Iterable? copyrightHeader = - map['copyrightHeader'] as Iterable?; + final copyrightHeader = map['copyrightHeader'] as Iterable?; return GObjectOptions( headerIncludePath: map['header'] as String?, module: map['module'] as String?, @@ -61,7 +60,7 @@ class GObjectOptions { /// Converts a [GObjectOptions] to a Map representation where: /// `x = GObjectOptions.fromMap(x.toMap())`. Map toMap() { - final Map result = { + final result = { if (headerIncludePath != null) 'header': headerIncludePath!, if (module != null) 'module': module!, if (copyrightHeader != null) 'copyrightHeader': copyrightHeader!, @@ -215,8 +214,8 @@ class GObjectHeaderGenerator final String enumName = _getClassName(module, anEnum.name); indent.newln(); - final List enumValueCommentLines = []; - for (int i = 0; i < anEnum.members.length; i++) { + final enumValueCommentLines = []; + for (var i = 0; i < anEnum.members.length; i++) { final EnumMember member = anEnum.members[i]; final String itemName = _getEnumValue( dartPackageName, @@ -233,7 +232,7 @@ class GObjectHeaderGenerator ...anEnum.documentationComments, ], _docCommentSpec); indent.writeScoped('typedef enum {', '} $enumName;', () { - for (int i = 0; i < anEnum.members.length; i++) { + for (var i = 0; i < anEnum.members.length; i++) { final EnumMember member = anEnum.members[i]; final String itemName = _getEnumValue( dartPackageName, @@ -270,7 +269,7 @@ class GObjectHeaderGenerator _writeDeclareFinalType(indent, module, classDefinition.name); indent.newln(); - final List constructorArgs = []; + final constructorArgs = []; for (final NamedType field in classDefinition.fields) { final String fieldName = _getFieldName(field.name); final String type = _getType(module, field.type); @@ -279,7 +278,7 @@ class GObjectHeaderGenerator constructorArgs.add('size_t ${fieldName}_length'); } } - final List constructorFieldCommentLines = []; + final constructorFieldCommentLines = []; for (final NamedType field in classDefinition.fields) { final String fieldName = _getFieldName(field.name); constructorFieldCommentLines.add('$fieldName: field in this object.'); @@ -320,7 +319,7 @@ class GObjectHeaderGenerator '', 'Returns: the field value.', ], _docCommentSpec); - final List getterArgs = [ + final getterArgs = [ '$className* object', if (_isNumericListType(field.type)) 'size_t* length', ]; @@ -328,6 +327,31 @@ class GObjectHeaderGenerator '$returnType ${methodPrefix}_get_$fieldName(${getterArgs.join(', ')});', ); } + + indent.newln(); + addDocumentationComments(indent, [ + '${methodPrefix}_equals:', + '@a: a #$className.', + '@b: another #$className.', + '', + 'Checks if two #$className objects are equal.', + '', + 'Returns: TRUE if @a and @b are equal.', + ], _docCommentSpec); + indent.writeln( + 'gboolean ${methodPrefix}_equals($className* a, $className* b);', + ); + + indent.newln(); + addDocumentationComments(indent, [ + '${methodPrefix}_hash:', + '@object: a #$className.', + '', + 'Calculates a hash code for a #$className object.', + '', + 'Returns: the hash code.', + ], _docCommentSpec); + indent.writeln('guint ${methodPrefix}_hash($className* object);'); } @override @@ -362,7 +386,7 @@ class GObjectHeaderGenerator ], _docCommentSpec); } - for (final EnumeratedType customType in customTypes) { + for (final customType in customTypes) { final String customTypeId = _getCustomTypeId(module, customType); indent.writeln('extern const int $customTypeId;'); } @@ -413,7 +437,7 @@ class GObjectHeaderGenerator final String responseName = _getResponseName(api.name, method.name); final String responseClassName = _getClassName(module, responseName); - final List asyncArgs = ['$className* api']; + final asyncArgs = ['$className* api']; for (final Parameter param in method.parameters) { final String paramName = _snakeCaseFromCamelCase(param.name); asyncArgs.add('${_getType(module, param.type)} $paramName'); @@ -427,7 +451,7 @@ class GObjectHeaderGenerator 'gpointer user_data', ]); indent.newln(); - final List methodParameterCommentLines = []; + final methodParameterCommentLines = []; for (final Parameter param in method.parameters) { final String paramName = _snakeCaseFromCamelCase(param.name); methodParameterCommentLines.add( @@ -453,7 +477,7 @@ class GObjectHeaderGenerator "void ${methodPrefix}_$methodName(${asyncArgs.join(', ')});", ); - final List finishArgs = [ + final finishArgs = [ '$className* api', 'GAsyncResult* result', 'GError** error', @@ -561,7 +585,7 @@ class GObjectHeaderGenerator else 'Returns: a return value.', ], _docCommentSpec); - final String returnType = _isNullablePrimitiveType(method.returnType) + final returnType = _isNullablePrimitiveType(method.returnType) ? '$primitiveType*' : primitiveType; indent.writeln( @@ -654,7 +678,7 @@ class GObjectHeaderGenerator final String returnType = _getType(module, method.returnType); indent.newln(); - final List constructorArgs = [ + final constructorArgs = [ if (returnType != 'void') '$returnType return_value', if (_isNumericListType(method.returnType)) 'size_t return_value_length', ]; @@ -701,7 +725,7 @@ class GObjectHeaderGenerator final String responseName = _getResponseName(api.name, method.name); final String responseClassName = _getClassName(module, responseName); - final List methodArgs = []; + final methodArgs = []; for (final Parameter param in method.parameters) { final String name = _snakeCaseFromCamelCase(param.name); methodArgs.add('${_getType(module, param.type)} $name'); @@ -714,7 +738,7 @@ class GObjectHeaderGenerator '${className}ResponseHandle* response_handle', 'gpointer user_data', ]); - final String returnType = method.isAsynchronous + final returnType = method.isAsynchronous ? 'void' : '$responseClassName*'; indent.writeln("$returnType (*$methodName)(${methodArgs.join(', ')});"); @@ -735,7 +759,7 @@ class GObjectHeaderGenerator final String returnType = _getType(module, method.returnType); indent.newln(); - final List respondArgs = [ + final respondArgs = [ '${className}ResponseHandle* response_handle', if (returnType != 'void') '$returnType return_value', if (_isNumericListType(method.returnType)) 'size_t return_value_length', @@ -755,7 +779,7 @@ class GObjectHeaderGenerator ); indent.newln(); - final List respondErrorArgs = [ + final respondErrorArgs = [ '${className}ResponseHandle* response_handle', 'const gchar* code', 'const gchar* message', @@ -819,7 +843,14 @@ class GObjectSourceGenerator required String dartPackageName, }) { indent.newln(); + indent.writeln('#include '); + indent.newln(); + indent.writeln('#include '); indent.writeln('#include "${generatorOptions.headerIncludePath}"'); + + _writeHashHelpers(indent); + _writeDeepEquals(indent); + _writeDeepHash(indent); } @override @@ -855,7 +886,7 @@ class GObjectSourceGenerator indent.newln(); _writeDispose(indent, module, classDefinition.name, () { - bool haveSelf = false; + var haveSelf = false; for (final NamedType field in classDefinition.fields) { final String fieldName = _getFieldName(field.name); final String? clear = _getClearFunction(field.type, 'self->$fieldName'); @@ -875,7 +906,7 @@ class GObjectSourceGenerator indent.newln(); _writeClassInit(indent, module, classDefinition.name, () {}); - final List constructorArgs = []; + final constructorArgs = []; for (final NamedType field in classDefinition.fields) { final String fieldName = _getFieldName(field.name); constructorArgs.add('${_getType(module, field.type)} $fieldName'); @@ -946,7 +977,7 @@ class GObjectSourceGenerator final String returnType = _getType(module, field.type); indent.newln(); - final List getterArgs = [ + final getterArgs = [ '$className* self', if (_isNumericListType(field.type)) 'size_t* length', ]; @@ -986,8 +1017,8 @@ class GObjectSourceGenerator 'static $className* ${methodPrefix}_new_from_list(FlValue* values) {', '}', () { - final List args = []; - for (int i = 0; i < classDefinition.fields.length; i++) { + final args = []; + for (var i = 0; i < classDefinition.fields.length; i++) { final NamedType field = classDefinition.fields[i]; final String fieldName = _getFieldName(field.name); final String fieldType = _getType(module, field.type); @@ -1040,6 +1071,281 @@ class GObjectSourceGenerator indent.writeln('return ${methodPrefix}_new(${args.join(', ')});'); }, ); + + _writeClassEquality( + generatorOptions, + root, + indent, + classDefinition, + dartPackageName: dartPackageName, + ); + } + + void _writeClassEquality( + InternalGObjectOptions generatorOptions, + Root root, + Indent indent, + Class classDefinition, { + required String dartPackageName, + }) { + final String module = _getModule(generatorOptions, dartPackageName); + final String snakeModule = _snakeCaseFromCamelCase(module); + final String className = _getClassName(module, classDefinition.name); + final String snakeClassName = _snakeCaseFromCamelCase(classDefinition.name); + + final String methodPrefix = _getMethodPrefix(module, classDefinition.name); + final String testMacro = '${snakeModule}_IS_$snakeClassName'.toUpperCase(); + + indent.newln(); + indent.writeScoped('gboolean ${methodPrefix}_equals($className* a, $className* b) {', '}', () { + indent.writeScoped('if (a == b) {', '}', () { + indent.writeln('return TRUE;'); + }); + indent.writeScoped('if (a == nullptr || b == nullptr) {', '}', () { + indent.writeln('return FALSE;'); + }); + for (final NamedType field in classDefinition.fields) { + final String fieldName = _getFieldName(field.name); + if (field.type.isClass) { + final String fieldMethodPrefix = _getMethodPrefix( + module, + field.type.baseName, + ); + indent.writeScoped( + 'if (!${fieldMethodPrefix}_equals(a->$fieldName, b->$fieldName)) {', + '}', + () { + indent.writeln('return FALSE;'); + }, + ); + } else if (field.type.isEnum) { + if (field.type.isNullable) { + indent.writeScoped( + 'if ((a->$fieldName == nullptr) != (b->$fieldName == nullptr)) {', + '}', + () { + indent.writeln('return FALSE;'); + }, + ); + indent.writeScoped( + 'if (a->$fieldName != nullptr && *a->$fieldName != *b->$fieldName) {', + '}', + () { + indent.writeln('return FALSE;'); + }, + ); + } else { + indent.writeScoped( + 'if (a->$fieldName != b->$fieldName) {', + '}', + () { + indent.writeln('return FALSE;'); + }, + ); + } + } else if (_isNumericListType(field.type)) { + indent.writeScoped('if (a->$fieldName != b->$fieldName) {', '}', () { + indent.writeScoped( + 'if (a->$fieldName == nullptr || b->$fieldName == nullptr) {', + '}', + () { + indent.writeln('return FALSE;'); + }, + ); + indent.writeScoped( + 'if (a->${fieldName}_length != b->${fieldName}_length) {', + '}', + () { + indent.writeln('return FALSE;'); + }, + ); + if (field.type.baseName == 'Float32List' || + field.type.baseName == 'Float64List') { + indent.writeScoped( + 'for (size_t i = 0; i < a->${fieldName}_length; i++) {', + '}', + () { + indent.writeScoped( + 'if (!flpigeon_equals_double(a->$fieldName[i], b->$fieldName[i])) {', + '}', + () { + indent.writeln('return FALSE;'); + }, + ); + }, + ); + } else { + final elementSize = field.type.baseName == 'Uint8List' + ? 'sizeof(uint8_t)' + : field.type.baseName == 'Int32List' + ? 'sizeof(int32_t)' + : 'sizeof(int64_t)'; + indent.writeScoped( + 'if (memcmp(a->$fieldName, b->$fieldName, a->${fieldName}_length * $elementSize) != 0) {', + '}', + () { + indent.writeln('return FALSE;'); + }, + ); + } + }); + } else if (field.type.baseName == 'bool' || + field.type.baseName == 'int') { + if (field.type.isNullable) { + indent.writeScoped( + 'if ((a->$fieldName == nullptr) != (b->$fieldName == nullptr)) {', + '}', + () { + indent.writeln('return FALSE;'); + }, + ); + indent.writeScoped( + 'if (a->$fieldName != nullptr && *a->$fieldName != *b->$fieldName) {', + '}', + () { + indent.writeln('return FALSE;'); + }, + ); + } else { + indent.writeScoped( + 'if (a->$fieldName != b->$fieldName) {', + '}', + () { + indent.writeln('return FALSE;'); + }, + ); + } + } else if (field.type.baseName == 'double') { + if (field.type.isNullable) { + indent.writeScoped( + 'if ((a->$fieldName == nullptr) != (b->$fieldName == nullptr)) {', + '}', + () { + indent.writeln('return FALSE;'); + }, + ); + indent.writeScoped( + 'if (a->$fieldName != nullptr && !flpigeon_equals_double(*a->$fieldName, *b->$fieldName)) {', + '}', + () { + indent.writeln('return FALSE;'); + }, + ); + } else { + indent.writeScoped( + 'if (!flpigeon_equals_double(a->$fieldName, b->$fieldName)) {', + '}', + () { + indent.writeln('return FALSE;'); + }, + ); + } + } else if (field.type.baseName == 'String') { + indent.writeScoped( + 'if (g_strcmp0(a->$fieldName, b->$fieldName) != 0) {', + '}', + () { + indent.writeln('return FALSE;'); + }, + ); + } else { + indent.writeScoped( + 'if (!flpigeon_deep_equals(a->$fieldName, b->$fieldName)) {', + '}', + () { + indent.writeln('return FALSE;'); + }, + ); + } + } + indent.writeln('return TRUE;'); + }); + + indent.newln(); + indent.writeScoped('guint ${methodPrefix}_hash($className* self) {', '}', () { + indent.writeln('g_return_val_if_fail($testMacro(self), 0);'); + indent.writeln('guint result = 0;'); + for (final NamedType field in classDefinition.fields) { + final String fieldName = _getFieldName(field.name); + if (field.type.isClass) { + final String fieldMethodPrefix = _getMethodPrefix( + module, + field.type.baseName, + ); + indent.writeln( + 'result = result * 31 + ${fieldMethodPrefix}_hash(self->$fieldName);', + ); + } else if (field.type.isEnum) { + if (field.type.isNullable) { + indent.writeln( + 'result = result * 31 + (self->$fieldName != nullptr ? static_cast(*self->$fieldName) : 0);', + ); + } else { + indent.writeln( + 'result = result * 31 + static_cast(self->$fieldName);', + ); + } + } else if (_isNumericListType(field.type)) { + indent.writeScoped('{', '}', () { + indent.writeln('size_t len = self->${fieldName}_length;'); + final String elementTypeName = _getType( + module, + field.type, + isElementType: true, + ); + indent.writeln('const $elementTypeName* data = self->$fieldName;'); + indent.writeScoped('if (data != nullptr) {', '}', () { + indent.writeScoped('for (size_t i = 0; i < len; i++) {', '}', () { + if (field.type.baseName == 'Int64List') { + indent.writeln( + 'result = result * 31 + static_cast(data[i] ^ (data[i] >> 32));', + ); + } else if (field.type.baseName == 'Float32List' || + field.type.baseName == 'Float64List') { + indent.writeln( + 'result = result * 31 + flpigeon_hash_double(data[i]);', + ); + } else { + indent.writeln( + 'result = result * 31 + static_cast(data[i]);', + ); + } + }); + }); + }); + } else if (field.type.baseName == 'bool' || + field.type.baseName == 'int') { + if (field.type.isNullable) { + indent.writeln( + 'result = result * 31 + (self->$fieldName != nullptr ? static_cast(*self->$fieldName) : 0);', + ); + } else { + indent.writeln( + 'result = result * 31 + static_cast(self->$fieldName);', + ); + } + } else if (field.type.baseName == 'double') { + if (field.type.isNullable) { + indent.writeln( + 'result = result * 31 + (self->$fieldName != nullptr ? flpigeon_hash_double(*self->$fieldName) : 0);', + ); + } else { + indent.writeln( + 'result = result * 31 + flpigeon_hash_double(self->$fieldName);', + ); + } + } else if (field.type.baseName == 'String') { + indent.writeln( + 'result = result * 31 + (self->$fieldName != nullptr ? g_str_hash(self->$fieldName) : 0);', + ); + } else { + indent.writeln( + 'result = result * 31 + flpigeon_deep_hash(self->$fieldName);', + ); + } + } + indent.writeln('return result;'); + }); } @override @@ -1076,12 +1382,12 @@ class GObjectSourceGenerator ); indent.newln(); - for (final EnumeratedType customType in customTypes) { + for (final customType in customTypes) { final String customTypeId = _getCustomTypeId(module, customType); indent.writeln('const int $customTypeId = ${customType.enumeration};'); } - for (final EnumeratedType customType in customTypes) { + for (final customType in customTypes) { final String customTypeName = _getClassName(module, customType.name); final String snakeCustomTypeName = _snakeCaseFromCamelCase( customTypeName, @@ -1089,7 +1395,7 @@ class GObjectSourceGenerator final String customTypeId = _getCustomTypeId(module, customType); indent.newln(); - final String valueType = customType.type == CustomTypes.customClass + final valueType = customType.type == CustomTypes.customClass ? '$customTypeName*' : 'FlValue*'; indent.writeScoped( @@ -1129,7 +1435,7 @@ class GObjectSourceGenerator 'switch (fl_value_get_custom_type(value)) {', '}', () { - for (final EnumeratedType customType in customTypes) { + for (final customType in customTypes) { final String customTypeId = _getCustomTypeId( module, customType, @@ -1170,7 +1476,7 @@ class GObjectSourceGenerator }, ); - for (final EnumeratedType customType in customTypes) { + for (final customType in customTypes) { final String customTypeName = _getClassName(module, customType.name); final String snakeCustomTypeName = _snakeCaseFromCamelCase( customTypeName, @@ -1217,7 +1523,7 @@ class GObjectSourceGenerator '}', () { indent.writeScoped('switch (type) {', '}', () { - for (final EnumeratedType customType in customTypes) { + for (final customType in customTypes) { final String customTypeName = _getClassName( module, customType.name, @@ -1456,7 +1762,7 @@ class GObjectSourceGenerator ); indent.newln(); - final String returnType = _isNullablePrimitiveType(method.returnType) + final returnType = _isNullablePrimitiveType(method.returnType) ? '$primitiveType*' : primitiveType; indent.writeScoped( @@ -1515,7 +1821,7 @@ class GObjectSourceGenerator }, ); - final List asyncArgs = ['$className* self']; + final asyncArgs = ['$className* self']; for (final Parameter param in method.parameters) { final String name = _snakeCaseFromCamelCase(param.name); asyncArgs.add('${_getType(module, param.type)} $name'); @@ -1571,7 +1877,7 @@ class GObjectSourceGenerator }, ); - final List finishArgs = [ + final finishArgs = [ '$className* self', 'GAsyncResult* result', 'GError** error', @@ -1695,7 +2001,7 @@ class GObjectSourceGenerator final String returnType = _getType(module, method.returnType); indent.newln(); - final List constructorArgs = [ + final constructorArgs = [ if (returnType != 'void') '$returnType return_value', if (_isNumericListType(method.returnType)) 'size_t return_value_length', ]; @@ -1793,8 +2099,8 @@ class GObjectSourceGenerator ); indent.newln(); - final List methodArgs = []; - for (int i = 0; i < method.parameters.length; i++) { + final methodArgs = []; + for (var i = 0; i < method.parameters.length; i++) { final Parameter param = method.parameters[i]; final String paramName = _snakeCaseFromCamelCase(param.name); final String paramType = _getType(module, param.type); @@ -1839,7 +2145,7 @@ class GObjectSourceGenerator } } if (method.isAsynchronous) { - final List vfuncArgs = []; + final vfuncArgs = []; vfuncArgs.addAll(methodArgs); vfuncArgs.addAll(['handle', 'self->user_data']); indent.writeln( @@ -1849,7 +2155,7 @@ class GObjectSourceGenerator "self->vtable->$methodName(${vfuncArgs.join(', ')});", ); } else { - final List vfuncArgs = []; + final vfuncArgs = []; vfuncArgs.addAll(methodArgs); vfuncArgs.add('self->user_data'); indent.writeln( @@ -1960,7 +2266,7 @@ class GObjectSourceGenerator ); indent.newln(); - final List respondArgs = [ + final respondArgs = [ '${className}ResponseHandle* response_handle', if (returnType != 'void') '$returnType return_value', if (_isNumericListType(method.returnType)) 'size_t return_value_length', @@ -1969,7 +2275,7 @@ class GObjectSourceGenerator "void ${methodPrefix}_respond_$methodName(${respondArgs.join(', ')}) {", '}', () { - final List returnArgs = [ + final returnArgs = [ if (returnType != 'void') 'return_value', if (_isNumericListType(method.returnType)) 'return_value_length', ]; @@ -1990,7 +2296,7 @@ class GObjectSourceGenerator ); indent.newln(); - final List respondErrorArgs = [ + final respondErrorArgs = [ '${className}ResponseHandle* response_handle', 'const gchar* code', 'const gchar* message', @@ -2029,7 +2335,7 @@ String _getModule( // Returns the header guard defintion for [headerFileName]. String _getGuardName(String? headerFileName) { - const String prefix = 'PIGEON_'; + const prefix = 'PIGEON_'; if (headerFileName != null) { return '$prefix${headerFileName.replaceAll('.', '_').toUpperCase()}_'; } else { @@ -2197,7 +2503,7 @@ String _getClassName(String module, String name) { // Returns the name to use for a class field with [name]. String _getFieldName(String name) { - final List reservedNames = ['type']; + final reservedNames = ['type']; if (reservedNames.contains(name)) { name += '_'; } @@ -2206,7 +2512,7 @@ String _getFieldName(String name) { // Returns the name to user for a class method with [name] String _getMethodName(String name) { - final List reservedNames = ['new', 'get_type']; + final reservedNames = ['new', 'get_type']; if (reservedNames.contains(name)) { name += '_'; } @@ -2238,7 +2544,7 @@ String _getCustomTypeId(String module, EnumeratedType customType) { final String snakeCustomTypeName = _snakeCaseFromCamelCase(customTypeName); - final String customTypeId = '${snakeCustomTypeName}_type_id'; + final customTypeId = '${snakeCustomTypeName}_type_id'; return customTypeId; } @@ -2255,6 +2561,7 @@ String _getType( TypeDeclaration type, { bool isOutput = false, bool primitive = false, + bool isElementType = false, }) { if (type.isClass) { return '${_getClassName(module, type.baseName)}*'; @@ -2274,14 +2581,29 @@ String _getType( } else if (type.baseName == 'String') { return isOutput ? 'gchar*' : 'const gchar*'; } else if (type.baseName == 'Uint8List') { + if (isElementType) { + return 'uint8_t'; + } return isOutput ? 'uint8_t*' : 'const uint8_t*'; } else if (type.baseName == 'Int32List') { + if (isElementType) { + return 'int32_t'; + } return isOutput ? 'int32_t*' : 'const int32_t*'; } else if (type.baseName == 'Int64List') { + if (isElementType) { + return 'int64_t'; + } return isOutput ? 'int64_t*' : 'const int64_t*'; } else if (type.baseName == 'Float32List') { + if (isElementType) { + return 'float'; + } return isOutput ? 'float*' : 'const float*'; } else if (type.baseName == 'Float64List') { + if (isElementType) { + return 'double'; + } return isOutput ? 'double*' : 'const double*'; } else { throw Exception('Unknown type ${type.baseName}'); @@ -2499,7 +2821,8 @@ String _fromFlValue(String module, TypeDeclaration type, String variableName) { } else if (type.baseName == 'Int64List') { return 'fl_value_get_int64_list($variableName)'; } else if (type.baseName == 'Float32List') { - return 'fl_value_get_float32_list($variableName)'; + // TODO(stuartmorgan): Support Float32List. + return 'nullptr'; } else if (type.baseName == 'Float64List') { return 'fl_value_get_float_list($variableName)'; } else { @@ -2513,3 +2836,263 @@ String _getResponseName(String name, String methodName) { methodName[0].toUpperCase() + methodName.substring(1); return '$name${upperMethodName}Response'; } + +void _writeHashHelpers(Indent indent) { + indent.writeScoped( + 'static guint G_GNUC_UNUSED flpigeon_hash_double(double v) {', + '}', + () { + indent.writeScoped('if (std::isnan(v)) {', '}', () { + indent.writeln('return static_cast(0x7FF80000);'); + }); + indent.writeScoped('if (v == 0.0) {', '}', () { + indent.writeln('v = 0.0;'); + }); + indent.writeln('union { double d; uint64_t u; } u;'); + indent.writeln('u.d = v;'); + indent.writeln('return static_cast(u.u ^ (u.u >> 32));'); + }, + ); + indent.writeScoped( + 'static gboolean G_GNUC_UNUSED flpigeon_equals_double(double a, double b) {', + '}', + () { + indent.writeln('return (a == b) || (std::isnan(a) && std::isnan(b));'); + }, + ); +} + +void _writeDeepEquals(Indent indent) { + indent.writeScoped( + 'static gboolean G_GNUC_UNUSED flpigeon_deep_equals(FlValue* a, FlValue* b) {', + '}', + () { + indent.writeScoped('if (a == b) {', '}', () { + indent.writeln('return TRUE;'); + }); + indent.writeScoped('if (a == nullptr || b == nullptr) {', '}', () { + indent.writeln('return FALSE;'); + }); + indent.writeScoped( + 'if (fl_value_get_type(a) != fl_value_get_type(b)) {', + '}', + () { + indent.writeln('return FALSE;'); + }, + ); + indent.writeScoped('switch (fl_value_get_type(a)) {', '}', () { + indent.writeln('case FL_VALUE_TYPE_NULL:'); + indent.writeln(' return TRUE;'); + indent.writeln('case FL_VALUE_TYPE_BOOL:'); + indent.writeln( + ' return fl_value_get_bool(a) == fl_value_get_bool(b);', + ); + indent.writeln('case FL_VALUE_TYPE_INT:'); + indent.writeln(' return fl_value_get_int(a) == fl_value_get_int(b);'); + indent.writeln('case FL_VALUE_TYPE_FLOAT: {'); + indent.writeln( + ' return flpigeon_equals_double(fl_value_get_float(a), fl_value_get_float(b));', + ); + indent.writeln('}'); + indent.writeln('case FL_VALUE_TYPE_STRING:'); + indent.writeln( + ' return g_strcmp0(fl_value_get_string(a), fl_value_get_string(b)) == 0;', + ); + indent.writeln('case FL_VALUE_TYPE_UINT8_LIST:'); + indent.writeln( + ' return fl_value_get_length(a) == fl_value_get_length(b) &&', + ); + indent.writeln( + ' memcmp(fl_value_get_uint8_list(a), fl_value_get_uint8_list(b), fl_value_get_length(a)) == 0;', + ); + indent.writeln('case FL_VALUE_TYPE_INT32_LIST:'); + indent.writeln( + ' return fl_value_get_length(a) == fl_value_get_length(b) &&', + ); + indent.writeln( + ' memcmp(fl_value_get_int32_list(a), fl_value_get_int32_list(b), fl_value_get_length(a) * sizeof(int32_t)) == 0;', + ); + indent.writeln('case FL_VALUE_TYPE_INT64_LIST:'); + indent.writeln( + ' return fl_value_get_length(a) == fl_value_get_length(b) &&', + ); + indent.writeln( + ' memcmp(fl_value_get_int64_list(a), fl_value_get_int64_list(b), fl_value_get_length(a) * sizeof(int64_t)) == 0;', + ); + indent.writeln('case FL_VALUE_TYPE_FLOAT_LIST: {'); + indent.writeln(' size_t len = fl_value_get_length(a);'); + indent.writeln(' if (len != fl_value_get_length(b)) {'); + indent.writeln(' return FALSE;'); + indent.writeln(' }'); + indent.writeln(' const double* a_data = fl_value_get_float_list(a);'); + indent.writeln(' const double* b_data = fl_value_get_float_list(b);'); + indent.writeScoped(' for (size_t i = 0; i < len; i++) {', '}', () { + indent.writeln( + 'if (!flpigeon_equals_double(a_data[i], b_data[i])) {', + ); + indent.writeln(' return FALSE;'); + indent.writeln('}'); + }); + indent.writeln(' return TRUE;'); + indent.writeln('}'); + indent.writeln('case FL_VALUE_TYPE_LIST: {'); + indent.writeln(' size_t len = fl_value_get_length(a);'); + indent.writeln(' if (len != fl_value_get_length(b)) {'); + indent.writeln(' return FALSE;'); + indent.writeln(' }'); + indent.writeScoped(' for (size_t i = 0; i < len; i++) {', '}', () { + indent.writeln( + 'if (!flpigeon_deep_equals(fl_value_get_list_value(a, i), fl_value_get_list_value(b, i))) {', + ); + indent.writeln(' return FALSE;'); + indent.writeln('}'); + }); + indent.writeln(' return TRUE;'); + indent.writeln('}'); + indent.writeln('case FL_VALUE_TYPE_MAP: {'); + indent.writeln(' size_t len = fl_value_get_length(a);'); + indent.writeln(' if (len != fl_value_get_length(b)) {'); + indent.writeln(' return FALSE;'); + indent.writeln(' }'); + indent.writeScoped(' for (size_t i = 0; i < len; i++) {', '}', () { + indent.writeln('FlValue* key = fl_value_get_map_key(a, i);'); + indent.writeln('FlValue* val = fl_value_get_map_value(a, i);'); + indent.writeln('gboolean found = FALSE;'); + indent.writeScoped('for (size_t j = 0; j < len; j++) {', '}', () { + indent.writeln('FlValue* b_key = fl_value_get_map_key(b, j);'); + indent.writeScoped( + 'if (flpigeon_deep_equals(key, b_key)) {', + '}', + () { + indent.writeln( + 'FlValue* b_val = fl_value_get_map_value(b, j);', + ); + indent.writeln('if (flpigeon_deep_equals(val, b_val)) {'); + indent.nest(1, () { + indent.writeln('found = TRUE;'); + indent.writeln('break;'); + }); + indent.writeln('} else {'); + indent.nest(1, () { + indent.writeln('return FALSE;'); + }); + indent.writeln('}'); + }, + ); + }); + indent.writeln('if (!found) {'); + indent.writeln(' return FALSE;'); + indent.writeln('}'); + }); + indent.writeln(' return TRUE;'); + indent.writeln('}'); + indent.writeln('default:'); + indent.writeln(' return FALSE;'); + }); + indent.writeln('return FALSE;'); + }, + ); +} + +void _writeDeepHash(Indent indent) { + indent.writeScoped( + 'static guint G_GNUC_UNUSED flpigeon_deep_hash(FlValue* value) {', + '}', + () { + indent.writeScoped('if (value == nullptr) {', '}', () { + indent.writeln('return 0;'); + }); + indent.writeScoped('switch (fl_value_get_type(value)) {', '}', () { + indent.writeln('case FL_VALUE_TYPE_NULL:'); + indent.writeln(' return 0;'); + indent.writeln('case FL_VALUE_TYPE_BOOL:'); + indent.writeln(' return fl_value_get_bool(value) ? 1231 : 1237;'); + indent.writeln('case FL_VALUE_TYPE_INT: {'); + indent.writeln(' int64_t v = fl_value_get_int(value);'); + indent.writeln(' return static_cast(v ^ (v >> 32));'); + indent.writeln('}'); + indent.writeln('case FL_VALUE_TYPE_FLOAT:'); + indent.writeln( + ' return flpigeon_hash_double(fl_value_get_float(value));', + ); + indent.writeln('case FL_VALUE_TYPE_STRING:'); + indent.writeln(' return g_str_hash(fl_value_get_string(value));'); + indent.writeln('case FL_VALUE_TYPE_UINT8_LIST: {'); + indent.writeln(' guint result = 1;'); + indent.writeln(' size_t len = fl_value_get_length(value);'); + indent.writeln( + ' const uint8_t* data = fl_value_get_uint8_list(value);', + ); + indent.writeScoped(' for (size_t i = 0; i < len; i++) {', ' }', () { + indent.writeln(' result = result * 31 + data[i];'); + }); + indent.writeln(' return result;'); + indent.writeln('}'); + indent.writeln('case FL_VALUE_TYPE_INT32_LIST: {'); + indent.writeln(' guint result = 1;'); + indent.writeln(' size_t len = fl_value_get_length(value);'); + indent.writeln( + ' const int32_t* data = fl_value_get_int32_list(value);', + ); + indent.writeScoped(' for (size_t i = 0; i < len; i++) {', ' }', () { + indent.writeln( + ' result = result * 31 + static_cast(data[i]);', + ); + }); + indent.writeln(' return result;'); + indent.writeln('}'); + indent.writeln('case FL_VALUE_TYPE_INT64_LIST: {'); + indent.writeln(' guint result = 1;'); + indent.writeln(' size_t len = fl_value_get_length(value);'); + indent.writeln( + ' const int64_t* data = fl_value_get_int64_list(value);', + ); + indent.writeScoped(' for (size_t i = 0; i < len; i++) {', ' }', () { + indent.writeln( + ' result = result * 31 + static_cast(data[i] ^ (data[i] >> 32));', + ); + }); + indent.writeln(' return result;'); + indent.writeln('}'); + indent.writeln('case FL_VALUE_TYPE_FLOAT_LIST: {'); + indent.writeln(' guint result = 1;'); + indent.writeln(' size_t len = fl_value_get_length(value);'); + indent.writeln( + ' const double* data = fl_value_get_float_list(value);', + ); + indent.writeScoped(' for (size_t i = 0; i < len; i++) {', '}', () { + indent.writeln( + 'result = result * 31 + flpigeon_hash_double(data[i]);', + ); + }); + indent.writeln(' return result;'); + indent.writeln('}'); + indent.writeln('case FL_VALUE_TYPE_LIST: {'); + indent.writeln(' guint result = 1;'); + indent.writeln(' size_t len = fl_value_get_length(value);'); + indent.writeScoped(' for (size_t i = 0; i < len; i++) {', '}', () { + indent.writeln( + 'result = result * 31 + flpigeon_deep_hash(fl_value_get_list_value(value, i));', + ); + }); + indent.writeln(' return result;'); + indent.writeln('}'); + indent.writeln('case FL_VALUE_TYPE_MAP: {'); + indent.writeln(' guint result = 0;'); + indent.writeln(' size_t len = fl_value_get_length(value);'); + indent.writeScoped(' for (size_t i = 0; i < len; i++) {', '}', () { + indent.writeln( + 'result += ((flpigeon_deep_hash(fl_value_get_map_key(value, i)) * 31) ^ flpigeon_deep_hash(fl_value_get_map_value(value, i)));', + ); + }); + indent.writeln(' return result;'); + indent.writeln('}'); + indent.writeln('default:'); + indent.writeln( + ' return static_cast(fl_value_get_type(value));', + ); + }); + indent.writeln('return 0;'); + }, + ); +} diff --git a/packages/pigeon/lib/src/java/java_generator.dart b/packages/pigeon/lib/src/java/java_generator.dart index de675d734581..4b7f792dc1c3 100644 --- a/packages/pigeon/lib/src/java/java_generator.dart +++ b/packages/pigeon/lib/src/java/java_generator.dart @@ -59,8 +59,7 @@ class JavaOptions { /// Creates a [JavaOptions] from a Map representation where: /// `x = JavaOptions.fromMap(x.toMap())`. static JavaOptions fromMap(Map map) { - final Iterable? copyrightHeader = - map['copyrightHeader'] as Iterable?; + final copyrightHeader = map['copyrightHeader'] as Iterable?; return JavaOptions( className: map['className'] as String?, package: map['package'] as String?, @@ -72,7 +71,7 @@ class JavaOptions { /// Converts a [JavaOptions] to a Map representation where: /// `x = JavaOptions.fromMap(x.toMap())`. Map toMap() { - final Map result = { + final result = { if (className != null) 'className': className!, if (package != null) 'package': package!, if (copyrightHeader != null) 'copyrightHeader': copyrightHeader!, @@ -203,10 +202,15 @@ class JavaGenerator extends StructuredGenerator { '@SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression", "serial"})', ); if (generatorOptions.useGeneratedAnnotation ?? false) { - indent.writeln('@javax.annotation.Generated("dev.flutter.pigeon")'); + indent.writeln( + '@javax.annotation.Generated("$defaultPluginPackageName")', + ); } indent.writeln('public class ${generatorOptions.className!} {'); indent.inc(); + _writeNumberHelpers(indent); + _writeDeepEquals(indent); + _writeDeepHashCode(indent); } @override @@ -218,7 +222,7 @@ class JavaGenerator extends StructuredGenerator { required String dartPackageName, }) { String camelToSnake(String camelCase) { - final RegExp regex = RegExp('([a-z])([A-Z]+)'); + final regex = RegExp('([a-z])([A-Z]+)'); return camelCase .replaceAllMapped(regex, (Match m) => '${m[1]}_${m[2]}') .toUpperCase(); @@ -263,7 +267,7 @@ class JavaGenerator extends StructuredGenerator { Class classDefinition, { required String dartPackageName, }) { - const List generatedMessages = [ + const generatedMessages = [ ' Generated class from Pigeon that represents data sent in messages.', ]; indent.newln(); @@ -313,9 +317,7 @@ class JavaGenerator extends StructuredGenerator { field, (TypeDeclaration x) => _javaTypeForBuiltinDartType(x), ); - final String nullability = field.type.isNullable - ? '@Nullable ' - : '@NonNull '; + final nullability = field.type.isNullable ? '@Nullable ' : '@NonNull '; addDocumentationComments( indent, field.documentationComments, @@ -384,13 +386,7 @@ class JavaGenerator extends StructuredGenerator { final Iterable checks = classDefinition.fields.map(( NamedType field, ) { - // Objects.equals only does pointer equality for array types. - if (_javaTypeIsArray(field.type)) { - return 'Arrays.equals(${field.name}, that.${field.name})'; - } - return field.type.isNullable - ? 'Objects.equals(${field.name}, that.${field.name})' - : '${field.name}.equals(that.${field.name})'; + return 'pigeonDeepEquals(${field.name}, that.${field.name})'; }); indent.writeln('return ${checks.join(' && ')};'); }); @@ -399,36 +395,273 @@ class JavaGenerator extends StructuredGenerator { // Implement hashCode(). indent.writeln('@Override'); indent.writeScoped('public int hashCode() {', '}', () { - // As with equalty checks, arrays need special handling. - final Iterable arrayFieldNames = classDefinition.fields - .where((NamedType field) => _javaTypeIsArray(field.type)) - .map((NamedType field) => field.name); - final Iterable nonArrayFieldNames = classDefinition.fields - .where((NamedType field) => !_javaTypeIsArray(field.type)) - .map((NamedType field) => field.name); - final String nonArrayHashValue = nonArrayFieldNames.isNotEmpty - ? 'Objects.hash(${nonArrayFieldNames.join(', ')})' - : '0'; - - if (arrayFieldNames.isEmpty) { - // Return directly if there are no array variables, to avoid redundant - // variable lint warnings. - indent.writeln('return $nonArrayHashValue;'); + final Iterable fieldNames = classDefinition.fields.map( + (NamedType field) => field.name, + ); + if (fieldNames.isEmpty) { + indent.writeln('return Objects.hash(getClass());'); } else { - const String resultVar = '${varNamePrefix}result'; - indent.writeln('int $resultVar = $nonArrayHashValue;'); - // Manually mix in the Arrays.hashCode values. - for (final String name in arrayFieldNames) { - indent.writeln( - '$resultVar = 31 * $resultVar + Arrays.hashCode($name);', - ); - } - indent.writeln('return $resultVar;'); + indent.writeln( + 'Object[] fields = new Object[] {getClass(), ${fieldNames.join(', ')}};', + ); + indent.writeln('return pigeonDeepHashCode(fields);'); } }); indent.newln(); } + void _writeDeepEquals(Indent indent) { + indent.writeScoped( + 'static boolean pigeonDeepEquals(Object a, Object b) {', + '}', + () { + indent.writeln('if (a == b) { return true; }'); + indent.writeln('if (a == null || b == null) { return false; }'); + indent.writeScoped( + 'if (a instanceof byte[] && b instanceof byte[]) {', + '}', + () { + indent.writeln('return Arrays.equals((byte[]) a, (byte[]) b);'); + }, + ); + indent.writeScoped( + 'if (a instanceof int[] && b instanceof int[]) {', + '}', + () { + indent.writeln('return Arrays.equals((int[]) a, (int[]) b);'); + }, + ); + indent.writeScoped( + 'if (a instanceof long[] && b instanceof long[]) {', + '}', + () { + indent.writeln('return Arrays.equals((long[]) a, (long[]) b);'); + }, + ); + indent.writeScoped( + 'if (a instanceof double[] && b instanceof double[]) {', + '}', + () { + indent.writeln('double[] da = (double[]) a;'); + indent.writeln('double[] db = (double[]) b;'); + indent.writeScoped('if (da.length != db.length) {', '}', () { + indent.writeln('return false;'); + }); + indent.writeScoped( + 'for (int i = 0; i < da.length; i++) {', + '}', + () { + indent.writeScoped( + 'if (!pigeonDoubleEquals(da[i], db[i])) {', + '}', + () { + indent.writeln('return false;'); + }, + ); + }, + ); + indent.writeln('return true;'); + }, + ); + indent.writeScoped( + 'if (a instanceof List && b instanceof List) {', + '}', + () { + indent.writeln('List listA = (List) a;'); + indent.writeln('List listB = (List) b;'); + indent.writeln( + 'if (listA.size() != listB.size()) { return false; }', + ); + indent.writeScoped( + 'for (int i = 0; i < listA.size(); i++) {', + '}', + () { + indent.writeScoped( + 'if (!pigeonDeepEquals(listA.get(i), listB.get(i))) {', + '}', + () { + indent.writeln('return false;'); + }, + ); + }, + ); + indent.writeln('return true;'); + }, + ); + indent.writeScoped( + 'if (a instanceof Map && b instanceof Map) {', + '}', + () { + indent.writeln('Map mapA = (Map) a;'); + indent.writeln('Map mapB = (Map) b;'); + indent.writeln('if (mapA.size() != mapB.size()) { return false; }'); + indent.writeScoped( + 'for (Map.Entry entryA : mapA.entrySet()) {', + '}', + () { + indent.writeln('Object keyA = entryA.getKey();'); + indent.writeln('Object valueA = entryA.getValue();'); + indent.writeln('boolean found = false;'); + indent.writeScoped( + 'for (Map.Entry entryB : mapB.entrySet()) {', + '}', + () { + indent.writeln('Object keyB = entryB.getKey();'); + indent.writeScoped( + 'if (pigeonDeepEquals(keyA, keyB)) {', + '}', + () { + indent.writeln('Object valueB = entryB.getValue();'); + indent.writeln( + 'if (pigeonDeepEquals(valueA, valueB)) {', + ); + indent.nest(1, () { + indent.writeln('found = true;'); + indent.writeln('break;'); + }); + indent.writeln('} else {'); + indent.nest(1, () { + indent.writeln('return false;'); + }); + indent.writeln('}'); + }, + ); + }, + ); + indent.writeScoped('if (!found) {', '}', () { + indent.writeln('return false;'); + }); + }, + ); + indent.writeln('return true;'); + }, + ); + indent.writeScoped( + 'if (a instanceof Double && b instanceof Double) {', + '}', + () { + indent.writeln( + 'return pigeonDoubleEquals((double) a, (double) b);', + ); + }, + ); + indent.writeScoped( + 'if (a instanceof Float && b instanceof Float) {', + '}', + () { + indent.writeln('return pigeonFloatEquals((float) a, (float) b);'); + }, + ); + indent.writeln('return a.equals(b);'); + }, + ); + indent.newln(); + } + + void _writeDeepHashCode(Indent indent) { + indent.writeScoped('static int pigeonDeepHashCode(Object value) {', '}', () { + indent.writeln('if (value == null) { return 0; }'); + indent.writeScoped('if (value instanceof byte[]) {', '}', () { + indent.writeln('return Arrays.hashCode((byte[]) value);'); + }); + indent.writeScoped('if (value instanceof int[]) {', '}', () { + indent.writeln('return Arrays.hashCode((int[]) value);'); + }); + indent.writeScoped('if (value instanceof long[]) {', '}', () { + indent.writeln('return Arrays.hashCode((long[]) value);'); + }); + indent.writeScoped('if (value instanceof double[]) {', '}', () { + indent.writeln('double[] da = (double[]) value;'); + indent.writeln('int result = 1;'); + indent.writeScoped('for (double d : da) {', '}', () { + indent.writeln('result = 31 * result + pigeonDoubleHashCode(d);'); + }); + indent.writeln('return result;'); + }); + indent.writeScoped('if (value instanceof List) {', '}', () { + indent.writeln('int result = 1;'); + indent.writeScoped('for (Object item : (List) value) {', '}', () { + indent.writeln('result = 31 * result + pigeonDeepHashCode(item);'); + }); + indent.writeln('return result;'); + }); + indent.writeScoped('if (value instanceof Map) {', '}', () { + indent.writeln('int result = 0;'); + indent.writeScoped( + 'for (Map.Entry entry : ((Map) value).entrySet()) {', + '}', + () { + indent.writeln( + 'result += ((pigeonDeepHashCode(entry.getKey()) * 31) ^ pigeonDeepHashCode(entry.getValue()));', + ); + }, + ); + indent.writeln('return result;'); + }); + indent.writeScoped('if (value instanceof Object[]) {', '}', () { + indent.writeln('int result = 1;'); + indent.writeScoped('for (Object item : (Object[]) value) {', '}', () { + indent.writeln('result = 31 * result + pigeonDeepHashCode(item);'); + }); + indent.writeln('return result;'); + }); + indent.writeScoped('if (value instanceof Double) {', '}', () { + indent.writeln('return pigeonDoubleHashCode((double) value);'); + }); + indent.writeScoped('if (value instanceof Float) {', '}', () { + indent.writeln('return pigeonFloatHashCode((float) value);'); + }); + indent.writeln('return value.hashCode();'); + }); + indent.newln(); + } + + void _writeNumberHelpers(Indent indent) { + indent.writeScoped( + 'static boolean pigeonDoubleEquals(double a, double b) {', + '}', + () { + indent.writeln('// Normalize -0.0 to 0.0 and handle NaN equality.'); + indent.writeln( + 'return (a == 0.0 ? 0.0 : a) == (b == 0.0 ? 0.0 : b) || (Double.isNaN(a) && Double.isNaN(b));', + ); + }, + ); + indent.newln(); + indent.writeScoped( + 'static boolean pigeonFloatEquals(float a, float b) {', + '}', + () { + indent.writeln('// Normalize -0.0 to 0.0 and handle NaN equality.'); + indent.writeln( + 'return (a == 0.0f ? 0.0f : a) == (b == 0.0f ? 0.0f : b) || (Float.isNaN(a) && Float.isNaN(b));', + ); + }, + ); + indent.newln(); + indent.writeScoped('static int pigeonDoubleHashCode(double d) {', '}', () { + indent.writeln( + '// Normalize -0.0 to 0.0 and handle NaN to ensure consistent hash codes.', + ); + indent.writeScoped('if (d == 0.0) {', '}', () { + indent.writeln('d = 0.0;'); + }); + indent.writeln('long bits = Double.doubleToLongBits(d);'); + indent.writeln('return (int) (bits ^ (bits >>> 32));'); + }); + indent.newln(); + indent.writeScoped('static int pigeonFloatHashCode(float f) {', '}', () { + indent.writeln( + '// Normalize -0.0 to 0.0 and handle NaN to ensure consistent hash codes.', + ); + indent.writeScoped('if (f == 0.0f) {', '}', () { + indent.writeln('f = 0.0f;'); + }); + indent.writeln('return Float.floatToIntBits(f);'); + }); + indent.newln(); + } + void _writeClassBuilder( InternalJavaOptions generatorOptions, Root root, @@ -444,9 +677,7 @@ class JavaGenerator extends StructuredGenerator { field, (TypeDeclaration x) => _javaTypeForBuiltinDartType(x), ); - final String nullability = field.type.isNullable - ? '@Nullable' - : '@NonNull'; + final nullability = field.type.isNullable ? '@Nullable' : '@NonNull'; indent.newln(); indent.writeln( 'private @Nullable ${hostDatatype.datatype} ${field.name};', @@ -465,7 +696,7 @@ class JavaGenerator extends StructuredGenerator { indent.newln(); indent.write('public @NonNull ${classDefinition.name} build() '); indent.addScoped('{', '}', () { - const String returnVal = 'pigeonReturn'; + const returnVal = 'pigeonReturn'; indent.writeln( '${classDefinition.name} $returnVal = new ${classDefinition.name}();', ); @@ -516,7 +747,7 @@ class JavaGenerator extends StructuredGenerator { 'static @NonNull ${classDefinition.name} fromList(@NonNull ArrayList ${varNamePrefix}list) ', ); indent.addScoped('{', '}', () { - const String result = 'pigeonResult'; + const result = 'pigeonResult'; indent.writeln( '${classDefinition.name} $result = new ${classDefinition.name}();', ); @@ -550,13 +781,13 @@ class JavaGenerator extends StructuredGenerator { ).toList(); void writeEncodeLogic(EnumeratedType customType) { - final String encodeString = customType.type == CustomTypes.customClass + final encodeString = customType.type == CustomTypes.customClass ? 'toList()' : 'index'; - final String nullCheck = customType.type == CustomTypes.customEnum + final nullCheck = customType.type == CustomTypes.customEnum ? 'value == null ? null : ' : ''; - final String valueString = customType.enumeration < maximumCodecFieldKey + final valueString = customType.enumeration < maximumCodecFieldKey ? '$nullCheck((${customType.name}) value).$encodeString' : 'wrap.toList()'; final int enumeration = customType.enumeration < maximumCodecFieldKey @@ -600,7 +831,7 @@ class JavaGenerator extends StructuredGenerator { } } - final EnumeratedType overflowClass = EnumeratedType( + final overflowClass = EnumeratedType( _overflowClassName, maximumCodecFieldKey, CustomTypes.customClass, @@ -632,7 +863,7 @@ class JavaGenerator extends StructuredGenerator { '}', () { indent.writeScoped('switch (type) {', '}', () { - for (final EnumeratedType customType in enumeratedTypes) { + for (final customType in enumeratedTypes) { if (customType.enumeration < maximumCodecFieldKey) { writeDecodeLogic(customType); } @@ -670,19 +901,16 @@ class JavaGenerator extends StructuredGenerator { List types, { required String dartPackageName, }) { - final NamedType overflowInteration = NamedType( + final overflowInteration = NamedType( name: 'type', type: const TypeDeclaration(baseName: 'int', isNullable: false), ); - final NamedType overflowObject = NamedType( + final overflowObject = NamedType( name: 'wrapped', type: const TypeDeclaration(baseName: 'Object', isNullable: true), ); - final List overflowFields = [ - overflowInteration, - overflowObject, - ]; - final Class overflowClass = Class( + final overflowFields = [overflowInteration, overflowObject]; + final overflowClass = Class( name: _overflowClassName, fields: overflowFields, ); @@ -734,6 +962,7 @@ if (wrapped == null) { /// Writes the code for a flutter [Api], [api]. /// Example: + /// ```java /// public static final class Foo { /// public Foo(BinaryMessenger argBinaryMessenger) {...} /// public interface Result { @@ -741,6 +970,7 @@ if (wrapped == null) { /// } /// public int add(int x, int y, Result result) {...} /// } + /// ``` @override void writeFlutterApi( InternalJavaOptions generatorOptions, @@ -754,7 +984,7 @@ if (wrapped == null) { return '${_getArgumentName(count, argument)}Arg'; } - const List generatedMessages = [ + const generatedMessages = [ ' Generated class from Pigeon that represents Flutter messages that can be called from Java.', ]; addDocumentationComments( @@ -844,7 +1074,7 @@ if (wrapped == null) { ); } indent.addScoped('{', '}', () { - const String channel = 'channel'; + const channel = 'channel'; indent.writeln( 'final String channelName = "${makeChannelName(api, func, dartPackageName)}" + messageChannelSuffix;', ); @@ -888,7 +1118,7 @@ if (wrapped == null) { if (func.returnType.isVoid) { indent.writeln('result.success();'); } else { - const String output = 'output'; + const output = 'output'; final String outputExpression; indent.writeln('@SuppressWarnings("ConstantConditions")'); outputExpression = @@ -950,7 +1180,7 @@ if (wrapped == null) { AstHostApi api, { required String dartPackageName, }) { - const List generatedMessages = [ + const generatedMessages = [ ' Generated interface from Pigeon that represents a handler of messages from Flutter.', ]; addDocumentationComments( @@ -1033,7 +1263,7 @@ if (wrapped == null) { final String returnType = method.isAsynchronous ? 'void' : _javaTypeForDartType(method.returnType); - final List argSignature = []; + final argSignature = []; if (method.parameters.isNotEmpty) { final Iterable argTypes = method.parameters.map( (NamedType e) => _nullsafeJavaTypeForDartType(e.type), @@ -1102,7 +1332,7 @@ if (wrapped == null) { ? 'Void' : _javaTypeForDartType(method.returnType); indent.writeln('ArrayList wrapped = new ArrayList<>();'); - final List methodArgument = []; + final methodArgument = []; if (method.parameters.isNotEmpty) { indent.writeln( 'ArrayList args = (ArrayList) message;', @@ -1110,8 +1340,8 @@ if (wrapped == null) { enumerate(method.parameters, (int index, NamedType arg) { final String argType = _javaTypeForDartType(arg.type); final String argName = _getSafeArgumentName(index, arg); - final String argExpression = argName; - String accessor = 'args.get($index)'; + final argExpression = argName; + var accessor = 'args.get($index)'; if (argType != 'Object') { accessor = _cast(accessor, javaType: argType); } @@ -1120,17 +1350,15 @@ if (wrapped == null) { }); } if (method.isAsynchronous) { - final String resultValue = method.returnType.isVoid - ? 'null' - : 'result'; + final resultValue = method.returnType.isVoid ? 'null' : 'result'; final String resultType = _getResultType(method.returnType); - final String resultParam = method.returnType.isVoid + final resultParam = method.returnType.isVoid ? '' : '$returnType result'; - final String addResultArg = method.returnType.isVoid + final addResultArg = method.returnType.isVoid ? 'null' : resultValue; - const String resultName = 'resultCallback'; + const resultName = 'resultCallback'; indent.format(''' $resultType $resultName = \t\tnew $resultType() { @@ -1147,8 +1375,7 @@ $resultType $resultName = '''); methodArgument.add(resultName); } - final String call = - 'api.${method.name}(${methodArgument.join(', ')})'; + final call = 'api.${method.name}(${methodArgument.join(', ')})'; if (method.isAsynchronous) { indent.writeln('$call;'); } else { @@ -1341,7 +1568,7 @@ protected static ArrayList wrapError(@NonNull Throwable exception) { /// Converts an expression that evaluates to an nullable int to an expression /// that evaluates to a nullable enum. String _intToEnum(String expression, String enumName, bool nullable) { - final String toEnum = '$enumName.values()[((Long) $expression).intValue()]'; + final toEnum = '$enumName.values()[((Long) $expression).intValue()]'; return nullable ? '$expression == null ? null : $toEnum' : toEnum; } @@ -1381,12 +1608,8 @@ String _javaTypeForBuiltinGenericDartType( } } -bool _javaTypeIsArray(TypeDeclaration type) { - return _javaTypeForBuiltinDartType(type)?.endsWith('[]') ?? false; -} - String? _javaTypeForBuiltinDartType(TypeDeclaration type) { - const Map javaTypeForDartTypeMap = { + const javaTypeForDartTypeMap = { 'bool': 'Boolean', 'int': 'Long', 'String': 'String', diff --git a/packages/pigeon/lib/src/kotlin/kotlin_generator.dart b/packages/pigeon/lib/src/kotlin/kotlin_generator.dart index 7745dd9e7aa8..fee33c6b66d6 100644 --- a/packages/pigeon/lib/src/kotlin/kotlin_generator.dart +++ b/packages/pigeon/lib/src/kotlin/kotlin_generator.dart @@ -35,6 +35,10 @@ const String _pigeonMethodChannelCodec = 'PigeonMethodCodec'; const String _overflowClassName = '${classNamePrefix}CodecOverflow'; +/// Kotlin file-level annotation for generated code. +const String kotlinGeneratedAnnotation = + '@file:Generated("$defaultPluginPackageName")'; + /// Options that control how Kotlin code will be generated. class KotlinOptions { /// Creates a [KotlinOptions] object @@ -44,6 +48,7 @@ class KotlinOptions { this.errorClassName, this.includeErrorClass = true, this.fileSpecificClassNameComponent, + this.useGeneratedAnnotation = false, }); /// The package where the generated class will live. @@ -64,6 +69,11 @@ class KotlinOptions { /// A String to augment class names to avoid cross file collisions. final String? fileSpecificClassNameComponent; + /// Determines if the `javax.annotation.Generated` is used in the output. This + /// is false by default since that dependency isn't available in plugins by + /// default. + final bool useGeneratedAnnotation; + /// Creates a [KotlinOptions] from a Map representation where: /// `x = KotlinOptions.fromMap(x.toMap())`. static KotlinOptions fromMap(Map map) { @@ -74,19 +84,21 @@ class KotlinOptions { includeErrorClass: map['includeErrorClass'] as bool? ?? true, fileSpecificClassNameComponent: map['fileSpecificClassNameComponent'] as String?, + useGeneratedAnnotation: map['useGeneratedAnnotation'] as bool? ?? false, ); } /// Converts a [KotlinOptions] to a Map representation where: /// `x = KotlinOptions.fromMap(x.toMap())`. Map toMap() { - final Map result = { + final result = { if (package != null) 'package': package!, if (copyrightHeader != null) 'copyrightHeader': copyrightHeader!, if (errorClassName != null) 'errorClassName': errorClassName!, 'includeErrorClass': includeErrorClass, if (fileSpecificClassNameComponent != null) 'fileSpecificClassNameComponent': fileSpecificClassNameComponent!, + 'useGeneratedAnnotation': useGeneratedAnnotation, }; return result; } @@ -108,6 +120,7 @@ class InternalKotlinOptions extends InternalOptions { this.errorClassName, this.includeErrorClass = true, this.fileSpecificClassNameComponent, + this.useGeneratedAnnotation = false, }); /// Creates InternalKotlinOptions from KotlinOptions. @@ -119,6 +132,7 @@ class InternalKotlinOptions extends InternalOptions { copyrightHeader = options.copyrightHeader ?? copyrightHeader, errorClassName = options.errorClassName, includeErrorClass = options.includeErrorClass, + useGeneratedAnnotation = options.useGeneratedAnnotation, fileSpecificClassNameComponent = options.fileSpecificClassNameComponent ?? kotlinOut.split('/').lastOrNull?.split('.').first; @@ -143,6 +157,11 @@ class InternalKotlinOptions extends InternalOptions { /// A String to augment class names to avoid cross file collisions. final String? fileSpecificClassNameComponent; + + /// Determines if the `javax.annotation.Generated` is used in the output. This + /// is false by default since that dependency isn't available in plugins by + /// default. + final bool useGeneratedAnnotation; } /// Options that control how Kotlin code will be generated for a specific @@ -192,6 +211,9 @@ class KotlinGenerator extends StructuredGenerator { indent.writeln('// ${getGeneratedCodeWarning()}'); indent.writeln('// $seeAlsoWarning'); indent.writeln('@file:Suppress("UNCHECKED_CAST", "ArrayInDataClass")'); + if (generatorOptions.useGeneratedAnnotation) { + indent.writeln(kotlinGeneratedAnnotation); + } } @override @@ -215,6 +237,9 @@ class KotlinGenerator extends StructuredGenerator { indent.writeln('import io.flutter.plugin.common.StandardMessageCodec'); indent.writeln('import java.io.ByteArrayOutputStream'); indent.writeln('import java.nio.ByteBuffer'); + if (generatorOptions.useGeneratedAnnotation) { + indent.writeln('import javax.annotation.Generated'); + } } @override @@ -267,7 +292,7 @@ class KotlinGenerator extends StructuredGenerator { Class classDefinition, { required String dartPackageName, }) { - final List generatedMessages = [ + final generatedMessages = [ ' Generated class from Pigeon that represents data sent in messages.', ]; if (classDefinition.isSealed) { @@ -320,19 +345,49 @@ class KotlinGenerator extends StructuredGenerator { required String dartPackageName, }) { indent.writeScoped('override fun equals(other: Any?): Boolean {', '}', () { - indent.writeScoped('if (other !is ${classDefinition.name}) {', '}', () { - indent.writeln('return false'); - }); + indent.writeScoped( + 'if (other == null || other.javaClass != javaClass) {', + '}', + () { + indent.writeln('return false'); + }, + ); indent.writeScoped('if (this === other) {', '}', () { indent.writeln('return true'); }); - indent.write( - 'return ${_getUtilsClassName(generatorOptions)}.deepEquals(toList(), other.toList())', + + indent.writeln('val other = other as ${classDefinition.name}'); + final Iterable fields = getFieldsInSerializationOrder( + classDefinition, ); + if (fields.isEmpty) { + indent.writeln('return true'); + } else { + final String utils = _getUtilsClassName(generatorOptions); + final String comparisons = fields + .map( + (NamedType field) => + '$utils.deepEquals(this.${field.name}, other.${field.name})', + ) + .join(' && '); + indent.writeln('return $comparisons'); + } }); indent.newln(); - indent.writeln('override fun hashCode(): Int = toList().hashCode()'); + indent.writeScoped('override fun hashCode(): Int {', '}', () { + final Iterable fields = getFieldsInSerializationOrder( + classDefinition, + ); + final String utils = _getUtilsClassName(generatorOptions); + indent.writeln('var result = javaClass.hashCode()'); + for (final field in fields) { + indent.writeln( + 'result = 31 * result + $utils.deepHash(this.${field.name})', + ); + } + indent.writeln('return result'); + }); } void _writeDataClassSignature( @@ -340,9 +395,9 @@ class KotlinGenerator extends StructuredGenerator { Class classDefinition, { bool private = false, }) { - final String privateString = private ? 'private ' : ''; - final String classType = classDefinition.isSealed ? 'sealed' : 'data'; - final String inheritance = classDefinition.superClass != null + final privateString = private ? 'private ' : ''; + final classType = classDefinition.isSealed ? 'sealed' : 'data'; + final inheritance = classDefinition.superClass != null ? ' : ${classDefinition.superClassName}()' : ''; indent.write('$privateString$classType class ${classDefinition.name} '); @@ -406,7 +461,7 @@ class KotlinGenerator extends StructuredGenerator { int index, final NamedType field, ) { - final String listValue = '${varNamePrefix}list[$index]'; + final listValue = '${varNamePrefix}list[$index]'; indent.writeln( 'val ${field.name} = ${_cast(indent, listValue, type: field.type)}', ); @@ -416,7 +471,7 @@ class KotlinGenerator extends StructuredGenerator { for (final NamedType field in getFieldsInSerializationOrder( classDefinition, )) { - final String comma = + final comma = getFieldsInSerializationOrder(classDefinition).last == field ? '' : ', '; @@ -436,7 +491,7 @@ class KotlinGenerator extends StructuredGenerator { indent.write( 'val ${field.name}: ${_nullSafeKotlinTypeForDartType(field.type)}', ); - final String defaultNil = field.type.isNullable ? ' = null' : ''; + final defaultNil = field.type.isNullable ? ' = null' : ''; indent.add(defaultNil); } @@ -475,10 +530,10 @@ class KotlinGenerator extends StructuredGenerator { ).toList(); void writeEncodeLogic(EnumeratedType customType) { - final String encodeString = customType.type == CustomTypes.customClass + final encodeString = customType.type == CustomTypes.customClass ? 'toList()' : 'raw.toLong()'; - final String valueString = customType.enumeration < maximumCodecFieldKey + final valueString = customType.enumeration < maximumCodecFieldKey ? 'value.$encodeString' : 'wrap.toList()'; final int enumeration = customType.enumeration < maximumCodecFieldKey @@ -512,7 +567,7 @@ class KotlinGenerator extends StructuredGenerator { }); } - final EnumeratedType overflowClass = EnumeratedType( + final overflowClass = EnumeratedType( '${generatorOptions.fileSpecificClassNameComponent}$_overflowClassName', maximumCodecFieldKey, CustomTypes.customClass, @@ -540,7 +595,7 @@ class KotlinGenerator extends StructuredGenerator { if (root.classes.isNotEmpty || root.enums.isNotEmpty) { indent.add('when (type) '); indent.addScoped('{', '}', () { - for (final EnumeratedType customType in enumeratedTypes) { + for (final customType in enumeratedTypes) { if (customType.enumeration < maximumCodecFieldKey) { writeDecodeLogic(customType); } @@ -586,19 +641,16 @@ class KotlinGenerator extends StructuredGenerator { List types, { required String dartPackageName, }) { - final NamedType overflowInt = NamedType( + final overflowInt = NamedType( name: 'type', type: const TypeDeclaration(baseName: 'int', isNullable: false), ); - final NamedType overflowObject = NamedType( + final overflowObject = NamedType( name: 'wrapped', type: const TypeDeclaration(baseName: 'Object', isNullable: true), ); - final List overflowFields = [ - overflowInt, - overflowObject, - ]; - final Class overflowClass = Class( + final overflowFields = [overflowInt, overflowObject]; + final overflowClass = Class( name: '${generatorOptions.fileSpecificClassNameComponent}$_overflowClassName', fields: overflowFields, @@ -665,7 +717,7 @@ if (wrapped == null) { AstFlutterApi api, { required String dartPackageName, }) { - const List generatedMessages = [ + const generatedMessages = [ ' Generated class from Pigeon that represents Flutter messages that can be called from Kotlin.', ]; addDocumentationComments( @@ -746,7 +798,7 @@ if (wrapped == null) { }) { final String apiName = api.name; - const List generatedMessages = [ + const generatedMessages = [ ' Generated interface from Pigeon that represents a handler of messages from Flutter.', ]; addDocumentationComments( @@ -840,7 +892,7 @@ if (wrapped == null) { Indent indent, { required String dartPackageName, }) { - final String instanceManagerApiName = + final instanceManagerApiName = '${kotlinInstanceManagerClassName(generatorOptions)}Api'; addDocumentationComments(indent, [ @@ -869,7 +921,7 @@ if (wrapped == null) { 'fun setUpMessageHandlers(binaryMessenger: BinaryMessenger, instanceManager: ${kotlinInstanceManagerClassName(generatorOptions)}?) {', '}', () { - const String setHandlerCondition = 'instanceManager != null'; + const setHandlerCondition = 'instanceManager != null'; _writeHostMethodMessageHandler( indent, generatorOptions: generatorOptions, @@ -1000,7 +1052,7 @@ if (wrapped == null) { 'override fun writeValue(stream: ByteArrayOutputStream, value: Any?) {', '}', () { - final List nonProxyApiTypes = [ + final nonProxyApiTypes = [ 'Boolean', 'ByteArray', 'Double', @@ -1042,7 +1094,7 @@ if (wrapped == null) { api.kotlinOptions?.fullClassName ?? api.name; final int? minApi = api.kotlinOptions?.minAndroidApi; - final String versionCheck = minApi != null + final versionCheck = minApi != null ? 'android.os.Build.VERSION.SDK_INT >= $minApi && ' : ''; @@ -1079,7 +1131,7 @@ if (wrapped == null) { AstProxyApi api, { required String dartPackageName, }) { - final String kotlinApiName = '$hostProxyApiPrefix${api.name}'; + final kotlinApiName = '$hostProxyApiPrefix${api.name}'; addDocumentationComments( indent, @@ -1088,7 +1140,7 @@ if (wrapped == null) { ); indent.writeln('@Suppress("UNCHECKED_CAST")'); // The API only needs to be abstract if there are methods to override. - final String classModifier = api.hasMethodsRequiringImplementation() + final classModifier = api.hasMethodsRequiringImplementation() ? 'abstract' : 'open'; indent.writeScoped( @@ -1098,7 +1150,7 @@ if (wrapped == null) { final String fullKotlinClassName = api.kotlinOptions?.fullClassName ?? api.name; - final TypeDeclaration apiAsTypeDeclaration = TypeDeclaration( + final apiAsTypeDeclaration = TypeDeclaration( baseName: api.name, isNullable: false, associatedProxyApi: api, @@ -1237,6 +1289,10 @@ if (wrapped == null) { EventChannel(messenger, channelName, ${generatorOptions.fileSpecificClassNameComponent}$_pigeonMethodChannelCodec).setStreamHandler(internalStreamHandler) } } + // Implement methods from ${generatorOptions.fileSpecificClassNameComponent}PigeonEventChannelWrapper + override fun onListen(p0: Any?, sink: PigeonEventSink<${_kotlinTypeForDartType(func.returnType)}>) {} + + override fun onCancel(p0: Any?) {} } '''); } @@ -1316,35 +1372,157 @@ if (wrapped == null) { void _writeDeepEquals(InternalKotlinOptions generatorOptions, Indent indent) { indent.format(''' fun deepEquals(a: Any?, b: Any?): Boolean { + if (a === b) { + return true + } + if (a == null || b == null) { + return false + } if (a is ByteArray && b is ByteArray) { - return a.contentEquals(b) + return a.contentEquals(b) } if (a is IntArray && b is IntArray) { - return a.contentEquals(b) + return a.contentEquals(b) } if (a is LongArray && b is LongArray) { - return a.contentEquals(b) + return a.contentEquals(b) } if (a is DoubleArray && b is DoubleArray) { - return a.contentEquals(b) + if (a.size != b.size) return false + for (i in a.indices) { + if (!doubleEquals(a[i], b[i])) return false + } + return true + } + if (a is FloatArray && b is FloatArray) { + if (a.size != b.size) return false + for (i in a.indices) { + if (!floatEquals(a[i], b[i])) return false + } + return true } if (a is Array<*> && b is Array<*>) { - return a.size == b.size && - a.indices.all{ deepEquals(a[it], b[it]) } + if (a.size != b.size) return false + for (i in a.indices) { + if (!deepEquals(a[i], b[i])) return false + } + return true } if (a is List<*> && b is List<*>) { - return a.size == b.size && - a.indices.all{ deepEquals(a[it], b[it]) } + if (a.size != b.size) return false + val iterA = a.iterator() + val iterB = b.iterator() + while (iterA.hasNext() && iterB.hasNext()) { + if (!deepEquals(iterA.next(), iterB.next())) return false + } + return true } if (a is Map<*, *> && b is Map<*, *>) { - return a.size == b.size && a.all { - (b as Map).contains(it.key) && - deepEquals(it.value, b[it.key]) + if (a.size != b.size) return false + for (entry in a) { + val key = entry.key + var found = false + for (bEntry in b) { + if (deepEquals(key, bEntry.key)) { + if (deepEquals(entry.value, bEntry.value)) { + found = true + break + } else { + return false + } + } + } + if (!found) return false } + return true + } + if (a is Double && b is Double) { + return doubleEquals(a, b) + } + if (a is Float && b is Float) { + return floatEquals(a, b) } return a == b } - '''); +'''); + } + + void _writeDeepHash(InternalKotlinOptions generatorOptions, Indent indent) { + indent.format(''' +fun deepHash(value: Any?): Int { + return when (value) { + null -> 0 + is ByteArray -> value.contentHashCode() + is IntArray -> value.contentHashCode() + is LongArray -> value.contentHashCode() + is DoubleArray -> { + var result = 1 + for (item in value) { + result = 31 * result + doubleHash(item) + } + result + } + is FloatArray -> { + var result = 1 + for (item in value) { + result = 31 * result + floatHash(item) + } + result + } + is Array<*> -> { + var result = 1 + for (item in value) { + result = 31 * result + deepHash(item) + } + result + } + is List<*> -> { + var result = 1 + for (item in value) { + result = 31 * result + deepHash(item) + } + result + } + is Map<*, *> -> { + var result = 0 + for (entry in value) { + result += ((deepHash(entry.key) * 31) xor deepHash(entry.value)) + } + result + } + is Double -> doubleHash(value) + is Float -> floatHash(value) + else -> value.hashCode() + } +} +'''); + } + + void _writeNumberHelpers(Indent indent) { + indent.format(''' +fun doubleEquals(a: Double, b: Double): Boolean { + // Normalize -0.0 to 0.0 and handle NaN equality. + return (if (a == 0.0) 0.0 else a) == (if (b == 0.0) 0.0 else b) || (a.isNaN() && b.isNaN()) +} + +fun floatEquals(a: Float, b: Float): Boolean { + // Normalize -0.0 to 0.0 and handle NaN equality. + return (if (a == 0.0f) 0.0f else a) == (if (b == 0.0f) 0.0f else b) || (a.isNaN() && b.isNaN()) +} + +fun doubleHash(d: Double): Int { + // Normalize -0.0 to 0.0 and handle NaN to ensure consistent hash codes. + val normalized = if (d == 0.0) 0.0 else d + val bits = java.lang.Double.doubleToLongBits(normalized) + return (bits xor (bits ushr 32)).toInt() +} + +fun floatHash(f: Float): Int { + // Normalize -0.0 to 0.0 and handle NaN to ensure consistent hash codes. + val normalized = if (f == 0.0f) 0.0f else f + return java.lang.Float.floatToIntBits(normalized) +} +'''); } @override @@ -1366,7 +1544,9 @@ fun deepEquals(a: Any?, b: Any?): Boolean { _writeWrapError(generatorOptions, indent); } if (root.classes.isNotEmpty) { + _writeNumberHelpers(indent); _writeDeepEquals(generatorOptions, indent); + _writeDeepHash(generatorOptions, indent); } }, ); @@ -1389,7 +1569,7 @@ fun deepEquals(a: Any?, b: Any?): Boolean { String Function(int index, NamedType type) getArgumentName = _getArgumentName, }) { - final List argSignature = []; + final argSignature = []; if (parameters.isNotEmpty) { final Iterable argTypes = parameters.map( (NamedType e) => _nullSafeKotlinTypeForDartType(e.type), @@ -1406,7 +1586,7 @@ fun deepEquals(a: Any?, b: Any?): Boolean { ? '' : _nullSafeKotlinTypeForDartType(returnType); - final String resultType = returnType.isVoid ? 'Unit' : returnTypeString; + final resultType = returnType.isVoid ? 'Unit' : returnTypeString; addDocumentationComments(indent, documentationComments, _docCommentSpec); if (minApiRequirement != null) { @@ -1415,8 +1595,8 @@ fun deepEquals(a: Any?, b: Any?): Boolean { ); } - final String openKeyword = isOpen ? 'open ' : ''; - final String abstractKeyword = isAbstract ? 'abstract ' : ''; + final openKeyword = isOpen ? 'open ' : ''; + final abstractKeyword = isAbstract ? 'abstract ' : ''; if (isAsynchronous) { argSignature.add('callback: (Result<$resultType>) -> Unit'); @@ -1462,16 +1642,16 @@ fun deepEquals(a: Any?, b: Any?): Boolean { indent.write('if ($setHandlerCondition) '); indent.addScoped('{', '}', () { - final String messageVarName = parameters.isNotEmpty ? 'message' : '_'; + final messageVarName = parameters.isNotEmpty ? 'message' : '_'; indent.write('channel.setMessageHandler '); indent.addScoped('{ $messageVarName, reply ->', '}', () { - final List methodArguments = []; + final methodArguments = []; if (parameters.isNotEmpty) { indent.writeln('val args = message as List'); enumerate(parameters, (int index, NamedType arg) { final String argName = _getSafeArgumentName(index, arg); - final String argIndex = 'args[$index]'; + final argIndex = 'args[$index]'; indent.writeln( 'val $argName = ${_castForceUnwrap(argIndex, arg.type, indent)}', ); @@ -1598,7 +1778,7 @@ fun deepEquals(a: Any?, b: Any?): Boolean { sendArgument = 'listOf(${enumSafeArgNames.join(', ')})'; } - const String channel = 'channel'; + const channel = 'channel'; indent.writeln('val channelName = "$channelName"'); indent.writeln( 'val $channel = BasicMessageChannel(binaryMessenger, channelName, codec)', @@ -1646,7 +1826,7 @@ fun deepEquals(a: Any?, b: Any?): Boolean { final String instanceManagerName = kotlinInstanceManagerClassName( generatorOptions, ); - final String instanceManagerApiName = '${instanceManagerName}Api'; + final instanceManagerApiName = '${instanceManagerName}Api'; addDocumentationComments(indent, [ ' Provides implementations for each ProxyApi implementation and provides access to resources', @@ -1688,7 +1868,7 @@ fun deepEquals(a: Any?, b: Any?): Boolean { } ) }'''); - for (final AstProxyApi api in allProxyApis) { + for (final api in allProxyApis) { _writeMethodDeclaration( indent, name: 'get$hostProxyApiPrefix${api.name}', @@ -1721,7 +1901,7 @@ fun deepEquals(a: Any?, b: Any?): Boolean { indent.writeln( '$instanceManagerApiName.setUpMessageHandlers(binaryMessenger, instanceManager)', ); - for (final AstProxyApi api in allProxyApis) { + for (final api in allProxyApis) { final bool hasHostMessageCalls = api.constructors.isNotEmpty || api.attachedFields.isNotEmpty || @@ -1738,7 +1918,7 @@ fun deepEquals(a: Any?, b: Any?): Boolean { indent.writeln( '$instanceManagerApiName.setUpMessageHandlers(binaryMessenger, null)', ); - for (final AstProxyApi api in allProxyApis) { + for (final api in allProxyApis) { if (api.hasAnyHostMessageCalls()) { indent.writeln( '$hostProxyApiPrefix${api.name}.setUpMessageHandlers(binaryMessenger, null)', @@ -2244,6 +2424,18 @@ fun deepEquals(a: Any?, b: Any?): Boolean { $errorClassName("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return'''); }, + addTrailingNewline: false, + ); + indent.writeScoped( + ' else if (!pigeonRegistrar.instanceManager.containsInstance(${classMemberNamePrefix}instanceArg)) {', + '}', + () { + indent.format(''' + callback( + Result.failure( + $errorClassName("missing-instance-error", "Callback to `${api.name}.${method.name}` failed because native instance was not in the instance manager.", ""))) + return'''); + }, ); indent.writeln( 'val binaryMessenger = pigeonRegistrar.binaryMessenger', @@ -2267,13 +2459,13 @@ fun deepEquals(a: Any?, b: Any?): Boolean { // // These are used for inherited Flutter methods. void _writeProxyApiInheritedApiMethods(Indent indent, AstProxyApi api) { - final Set inheritedApiNames = { + final inheritedApiNames = { if (api.superClass != null) api.superClass!.baseName, ...api.interfaces.map((TypeDeclaration type) => type.baseName), }; - for (final String name in inheritedApiNames) { + for (final name in inheritedApiNames) { indent.writeln('@Suppress("FunctionName")'); - final String apiName = '$hostProxyApiPrefix$name'; + final apiName = '$hostProxyApiPrefix$name'; _writeMethodDeclaration( indent, name: '${classMemberNamePrefix}get$apiName', @@ -2361,7 +2553,7 @@ String _kotlinTypeForBuiltinGenericDartType(TypeDeclaration type) { } String? _kotlinTypeForBuiltinDartType(TypeDeclaration type) { - const Map kotlinTypeForDartTypeMap = { + const kotlinTypeForDartTypeMap = { 'void': 'Void', 'bool': 'Boolean', 'String': 'String', @@ -2399,7 +2591,7 @@ String _kotlinTypeForDartType(TypeDeclaration type) { } String _nullSafeKotlinTypeForDartType(TypeDeclaration type) { - final String nullSafe = type.isNullable ? '?' : ''; + final nullSafe = type.isNullable ? '?' : ''; return '${_kotlinTypeForDartType(type)}$nullSafe'; } diff --git a/packages/pigeon/lib/src/objc/objc_generator.dart b/packages/pigeon/lib/src/objc/objc_generator.dart index 57ca9840e3ff..af0ad6d1ea2a 100644 --- a/packages/pigeon/lib/src/objc/objc_generator.dart +++ b/packages/pigeon/lib/src/objc/objc_generator.dart @@ -68,8 +68,7 @@ class ObjcOptions { /// Creates a [ObjcOptions] from a Map representation where: /// `x = ObjcOptions.fromMap(x.toMap())`. static ObjcOptions fromMap(Map map) { - final Iterable? copyrightHeader = - map['copyrightHeader'] as Iterable?; + final copyrightHeader = map['copyrightHeader'] as Iterable?; return ObjcOptions( headerIncludePath: map['headerIncludePath'] as String?, prefix: map['prefix'] as String?, @@ -82,7 +81,7 @@ class ObjcOptions { /// Converts a [ObjcOptions] to a Map representation where: /// `x = ObjcOptions.fromMap(x.toMap())`. Map toMap() { - final Map result = { + final result = { if (headerIncludePath != null) 'headerIncludePath': headerIncludePath!, if (prefix != null) 'prefix': prefix!, if (copyrightHeader != null) 'copyrightHeader': copyrightHeader!, @@ -204,7 +203,7 @@ class ObjcHeaderGenerator extends StructuredGenerator { Indent indent, { required String dartPackageName, }) { - indent.writeln('#import '); + indent.writeln('@import Foundation;'); indent.newln(); indent.writeln('@protocol FlutterBinaryMessenger;'); @@ -449,7 +448,7 @@ class ObjcHeaderGenerator extends StructuredGenerator { lastArgType = 'FlutterError *_Nullable *_Nonnull'; lastArgName = 'error'; } - final List generatorComments = []; + final generatorComments = []; if (!func.returnType.isNullable && !func.returnType.isVoid && !func.isAsynchronous) { @@ -514,16 +513,13 @@ class ObjcSourceGenerator extends StructuredGenerator { indent.writeln('#import "${generatorOptions.headerIncludePath}"'); indent.newln(); indent.writeln('#if TARGET_OS_OSX'); - indent.writeln('#import '); + indent.writeln('@import FlutterMacOS;'); indent.writeln('#else'); - indent.writeln('#import '); - indent.writeln('#endif'); - indent.newln(); - - indent.writeln('#if !__has_feature(objc_arc)'); - indent.writeln('#error File requires ARC to be enabled.'); + indent.writeln('@import Flutter;'); indent.writeln('#endif'); indent.newln(); + _writeDeepEquals(indent); + _writeDeepHash(indent); } @override @@ -620,10 +616,76 @@ class ObjcSourceGenerator extends StructuredGenerator { classDefinition, dartPackageName: dartPackageName, ); + _writeObjcEquality(generatorOptions, indent, classDefinition); indent.writeln('@end'); indent.newln(); } + void _writeObjcEquality( + InternalObjcOptions generatorOptions, + Indent indent, + Class classDefinition, + ) { + final String className = _className( + generatorOptions.prefix, + classDefinition.name, + ); + indent.write('- (BOOL)isEqual:(id)object '); + indent.addScoped('{', '}', () { + indent.writeScoped('if (self == object) {', '}', () { + indent.writeln('return YES;'); + }); + indent.writeScoped( + 'if (![object isKindOfClass:[self class]]) {', + '}', + () { + indent.writeln('return NO;'); + }, + ); + indent.writeln('$className *other = ($className *)object;'); + final Iterable checks = classDefinition.fields.map(( + NamedType field, + ) { + final String name = field.name; + if (_usesPrimitive(field.type)) { + if (field.type.baseName == 'double') { + return '(self.$name == other.$name || (isnan(self.$name) && isnan(other.$name)))'; + } + return 'self.$name == other.$name'; + } else { + return 'FLTPigeonDeepEquals(self.$name, other.$name)'; + } + }); + if (checks.isEmpty) { + indent.writeln('return YES;'); + } else { + indent.writeln('return ${checks.join(' && ')};'); + } + }); + indent.newln(); + indent.write('- (NSUInteger)hash '); + indent.addScoped('{', '}', () { + indent.writeln('NSUInteger result = [self class].hash;'); + for (final NamedType field in classDefinition.fields) { + final String name = field.name; + if (_usesPrimitive(field.type)) { + if (field.type.baseName == 'double') { + indent.writeln( + 'result = result * 31 + (isnan(self.$name) ? (NSUInteger)0x7FF8000000000000 : @(self.$name).hash);', + ); + } else { + indent.writeln('result = result * 31 + @(self.$name).hash;'); + } + } else { + indent.writeln( + 'result = result * 31 + FLTPigeonDeepHash(self.$name);', + ); + } + } + indent.writeln('return result;'); + }); + } + @override void writeClassEncode( InternalObjcOptions generatorOptions, @@ -657,19 +719,19 @@ class ObjcSourceGenerator extends StructuredGenerator { ); indent.write('+ ($className *)fromList:(NSArray *)list '); indent.addScoped('{', '}', () { - const String resultName = 'pigeonResult'; + const resultName = 'pigeonResult'; indent.writeln('$className *$resultName = [[$className alloc] init];'); enumerate(getFieldsInSerializationOrder(classDefinition), ( int index, final NamedType field, ) { - final String valueGetter = 'GetNullableObjectAtIndex(list, $index)'; + final valueGetter = 'GetNullableObjectAtIndex(list, $index)'; final String? primitiveExtractionMethod = _nsnumberExtractionMethod( field.type, ); final String ivarValueExpression; if (field.type.isEnum && !field.type.isNullable) { - final String varName = + final varName = 'boxed${_enumName(field.type.baseName, prefix: generatorOptions.prefix)}'; _writeEnumBoxToEnum( indent, @@ -770,7 +832,7 @@ if (self.wrapped == nil) { String? prefix, { bool isOverflowClass = false, }) { - String readValue = '[self readValue]'; + var readValue = '[self readValue]'; if (isOverflowClass) { readValue = 'self.wrapped'; } @@ -785,7 +847,7 @@ if (self.wrapped == nil) { !isOverflowClass ? '{' : '', !isOverflowClass ? '}' : null, () { - String enumAsNumber = 'enumAsNumber'; + var enumAsNumber = 'enumAsNumber'; if (!isOverflowClass) { indent.writeln('NSNumber *$enumAsNumber = $readValue;'); indent.write('return $enumAsNumber == nil ? nil : '); @@ -809,16 +871,16 @@ if (self.wrapped == nil) { Indent indent, { required String dartPackageName, }) { - const String codecName = 'PigeonCodec'; + const codecName = 'PigeonCodec'; final List enumeratedTypes = getEnumeratedTypes( root, excludeSealedClasses: true, ).toList(); - final String readerWriterName = + final readerWriterName = '${generatorOptions.prefix}${toUpperCamelCase(generatorOptions.fileSpecificClassNameComponent ?? '')}${codecName}ReaderWriter'; - final String readerName = + final readerName = '${generatorOptions.prefix}${toUpperCamelCase(generatorOptions.fileSpecificClassNameComponent ?? '')}${codecName}Reader'; - final String writerName = + final writerName = '${generatorOptions.prefix}${toUpperCamelCase(generatorOptions.fileSpecificClassNameComponent ?? '')}${codecName}Writer'; if (root.requiresOverflowClass) { @@ -837,7 +899,7 @@ if (self.wrapped == nil) { indent.write('- (nullable id)readValueOfType:(UInt8)type '); indent.addScoped('{', '}', () { indent.writeScoped('switch (type) {', '}', () { - for (final EnumeratedType customType in enumeratedTypes) { + for (final customType in enumeratedTypes) { if (customType.enumeration < maximumCodecFieldKey) { indent.write('case ${customType.enumeration}: '); _writeCodecDecode( @@ -869,11 +931,11 @@ if (self.wrapped == nil) { indent.write('- (void)writeValue:(id)value '); indent.addScoped('{', '}', () { indent.write(''); - for (final EnumeratedType customType in enumeratedTypes) { - final String encodeString = customType.type == CustomTypes.customClass + for (final customType in enumeratedTypes) { + final encodeString = customType.type == CustomTypes.customClass ? '[value toList]' : '(value == nil ? [NSNull null] : [NSNumber numberWithInteger:box.value])'; - final String valueString = customType.enumeration < maximumCodecFieldKey + final valueString = customType.enumeration < maximumCodecFieldKey ? encodeString : '[wrap toList]'; final String className = customType.type == CustomTypes.customClass @@ -986,7 +1048,7 @@ if (self.wrapped == nil) { }) { final String apiName = _className(generatorOptions.prefix, api.name); - const String channelName = 'channel'; + const channelName = 'channel'; indent.write( 'void SetUp$apiName(id binaryMessenger, NSObject<$apiName> *api) ', ); @@ -1121,10 +1183,10 @@ static FlutterError *createConnectionError(NSString *channelName) { ) { void unpackArgs(String variable) { indent.writeln('NSArray *args = $variable;'); - int count = 0; + var count = 0; for (final NamedType arg in func.parameters) { final String argName = _getSafeArgName(count, arg); - final String valueGetter = 'GetNullableObjectAtIndex(args, $count)'; + final valueGetter = 'GetNullableObjectAtIndex(args, $count)'; final String? primitiveExtractionMethod = _nsnumberExtractionMethod( arg.type, ); @@ -1135,7 +1197,7 @@ static FlutterError *createConnectionError(NSString *channelName) { final String ivarValueExpression; String beforeString = objcArgType.beforeString; if (arg.type.isEnum && !arg.type.isNullable) { - final String varName = + final varName = 'boxed${_enumName(arg.type.baseName, prefix: generatorOptions.prefix)}'; _writeEnumBoxToEnum( indent, @@ -1169,7 +1231,7 @@ static FlutterError *createConnectionError(NSString *channelName) { _ObjcType returnType, ) { if (func.returnType.isVoid) { - const String callback = 'callback(wrapResult(nil, error));'; + const callback = 'callback(wrapResult(nil, error));'; if (func.parameters.isEmpty) { indent.writeScoped( '[api ${selectorComponents.first}:^(FlutterError *_Nullable error) {', @@ -1188,8 +1250,8 @@ static FlutterError *createConnectionError(NSString *channelName) { ); } } else { - const String callback = 'callback(wrapResult(output, error));'; - String returnTypeString = '${returnType.beforeString}_Nullable output'; + const callback = 'callback(wrapResult(output, error));'; + var returnTypeString = '${returnType.beforeString}_Nullable output'; if (func.returnType.isEnum) { returnTypeString = @@ -1233,9 +1295,7 @@ static FlutterError *createConnectionError(NSString *channelName) { } // TODO(gaaclarke): Incorporate this into _getSelectorComponents. - final String lastSelectorComponent = func.isAsynchronous - ? 'completion' - : 'error'; + final lastSelectorComponent = func.isAsynchronous ? 'completion' : 'error'; final String selector = _getSelector(func, lastSelectorComponent); indent.writeln( 'NSCAssert([api respondsToSelector:@selector($selector)], @"$apiName api (%@) doesn\'t respond to @selector($selector)", api);', @@ -1271,7 +1331,7 @@ static FlutterError *createConnectionError(NSString *channelName) { if (func.isAsynchronous) { writeAsyncBindings(selectorComponents, callSignature, returnType); } else { - final String syncCall = func.parameters.isEmpty + final syncCall = func.parameters.isEmpty ? '[api ${selectorComponents.first}:&error]' : '[api $callSignature error:&error]'; writeSyncBindings(syncCall, returnType); @@ -1360,7 +1420,7 @@ taskQueue:$taskQueue languageOptions.prefix, ); indent.writeScoped(' {', '}', () { - const String result = 'pigeonResult'; + const result = 'pigeonResult'; indent.writeln('$className* $result = [[$className alloc] init];'); for (final NamedType field in getFieldsInSerializationOrder( classDefinition, @@ -1397,7 +1457,7 @@ void _writeMethod( if (func.parameters.isEmpty) { sendArgument = 'nil'; } else { - int count = 0; + var count = 0; String makeVarOrNSNullExpression(NamedType arg) { final String argName = argNameFunc(count, arg); String varExpression = _collectionSafeExpression(argName, arg.type); @@ -1447,7 +1507,7 @@ void _writeMethod( indent.addln('];'); }); }); - final String valueOnErrorResponse = func.returnType.isVoid ? '' : 'nil, '; + final valueOnErrorResponse = func.returnType.isVoid ? '' : 'nil, '; indent.write( '[channel sendMessage:$sendArgument reply:^(NSArray *reply) ', ); @@ -1459,7 +1519,7 @@ void _writeMethod( ); }, addTrailingNewline: false); indent.addScoped('else {', '}', () { - const String nullCheck = 'reply[0] == [NSNull null] ? nil : reply[0]'; + const nullCheck = 'reply[0] == [NSNull null] ? nil : reply[0]'; if (func.returnType.isVoid) { indent.writeln('completion(nil);'); } else { @@ -1497,7 +1557,7 @@ void _writeObjcSourceClassInitializerDeclaration( String? prefix, ) { indent.write('+ (instancetype)makeWith'); - bool isFirst = true; + var isFirst = true; indent.nest(2, () { for (final NamedType field in getFieldsInSerializationOrder( classDefinition, @@ -1520,7 +1580,7 @@ void _writeObjcSourceClassInitializerDeclaration( : _enumName(x, prefix: prefix) : (String x) => '${_className(prefix, x)} *', ); - final String nullable = field.type.isNullable ? 'nullable ' : ''; + final nullable = field.type.isNullable ? 'nullable ' : ''; printer('$label:($nullable${hostDatatype.datatype})${field.name}'); } }); @@ -1609,6 +1669,104 @@ const Map _objcTypeForNonNullableDartTypeMap = 'Object': _ObjcType(baseName: 'id'), }; +void _writeDeepEquals(Indent indent) { + indent.format(''' +static BOOL __attribute__((unused)) FLTPigeonDeepEquals(id _Nullable a, id _Nullable b) { + if (a == b) { + return YES; + } + if (a == nil) { + return b == [NSNull null]; + } + if (b == nil) { + return a == [NSNull null]; + } + if ([a isKindOfClass:[NSNumber class]] && [b isKindOfClass:[NSNumber class]]) { + return [a isEqual:b] || (isnan([(NSNumber *)a doubleValue]) && isnan([(NSNumber *)b doubleValue])); + } + if ([a isKindOfClass:[NSArray class]] && [b isKindOfClass:[NSArray class]]) { + NSArray *arrayA = (NSArray *)a; + NSArray *arrayB = (NSArray *)b; + if (arrayA.count != arrayB.count) { + return NO; + } + for (NSUInteger i = 0; i < arrayA.count; i++) { + if (!FLTPigeonDeepEquals(arrayA[i], arrayB[i])) { + return NO; + } + } + return YES; + } + if ([a isKindOfClass:[NSDictionary class]] && [b isKindOfClass:[NSDictionary class]]) { + NSDictionary *dictA = (NSDictionary *)a; + NSDictionary *dictB = (NSDictionary *)b; + if (dictA.count != dictB.count) { + return NO; + } + for (id keyA in dictA) { + id valueA = dictA[keyA]; + BOOL found = NO; + for (id keyB in dictB) { + if (FLTPigeonDeepEquals(keyA, keyB)) { + id valueB = dictB[keyB]; + if (FLTPigeonDeepEquals(valueA, valueB)) { + found = YES; + break; + } else { + return NO; + } + } + } + if (!found) { + return NO; + } + } + return YES; + } + return [a isEqual:b]; +} +'''); +} + +void _writeDeepHash(Indent indent) { + indent.format(''' +static NSUInteger __attribute__((unused)) FLTPigeonDeepHash(id _Nullable value) { + if (value == nil || value == (id)[NSNull null]) { + return 0; + } + if ([value isKindOfClass:[NSNumber class]]) { + NSNumber *n = (NSNumber *)value; + double d = n.doubleValue; + if (isnan(d)) { + // Normalize NaN to a consistent hash. + return (NSUInteger)0x7FF8000000000000; + } + if (d == 0.0) { + // Normalize -0.0 to 0.0 so they have the same hash code. + d = 0.0; + } + return @(d).hash; + } + if ([value isKindOfClass:[NSArray class]]) { + NSUInteger result = 1; + for (id item in (NSArray *)value) { + result = result * 31 + FLTPigeonDeepHash(item); + } + return result; + } + if ([value isKindOfClass:[NSDictionary class]]) { + NSUInteger result = 0; + NSDictionary *dict = (NSDictionary *)value; + for (id key in dict) { + result += ((FLTPigeonDeepHash(key) * 31) ^ FLTPigeonDeepHash(dict[key])); + } + return result; + } + return [value hash]; +} +'''); +} + bool _usesPrimitive(TypeDeclaration type) { // Only non-nullable types are unboxed. if (!type.isNullable) { @@ -1767,7 +1925,7 @@ Iterable _getSelectorComponents( if (func.objcSelector.isEmpty) { final Iterator it = func.parameters.iterator; final bool hasArguments = it.moveNext(); - final String namePostfix = + final namePostfix = (lastSelectorComponent.isNotEmpty && func.parameters.isEmpty) ? 'With${_capitalize(lastSelectorComponent)}' : ''; @@ -1820,7 +1978,7 @@ String _makeObjcSignature({ if (arg.type.isEnum) { return '${arg.type.isNullable ? 'nullable ' : ''}${_enumName(arg.type.baseName, suffix: arg.type.isNullable ? ' *' : '', prefix: options.prefix, box: arg.type.isNullable)}'; } else { - final String nullable = arg.type.isNullable ? 'nullable ' : ''; + final nullable = arg.type.isNullable ? 'nullable ' : ''; final _ObjcType argType = _objcTypeForDartType( options.prefix, arg.type, @@ -1903,7 +2061,7 @@ void _writeInitializers(Indent indent) { /// Looks through the AST for features that aren't supported by the ObjC /// generator. List validateObjc(InternalObjcOptions options, Root root) { - final List errors = []; + final errors = []; for (final Api api in root.apis) { for (final Method method in api.methods) { for (final NamedType arg in method.parameters) { @@ -2000,7 +2158,7 @@ void _writeDataClassDeclaration( isNullable: field.type.isNullable, isEnum: field.type.isEnum, ); - final String nullability = field.type.isNullable ? ', nullable' : ''; + final nullability = field.type.isNullable ? ', nullable' : ''; final String fieldType = field.type.isEnum && field.type.isNullable ? _enumName( field.type.baseName, diff --git a/packages/pigeon/lib/src/pigeon_lib.dart b/packages/pigeon/lib/src/pigeon_lib.dart index 2bb976475b94..fd6b6c827b2b 100644 --- a/packages/pigeon/lib/src/pigeon_lib.dart +++ b/packages/pigeon/lib/src/pigeon_lib.dart @@ -22,8 +22,8 @@ import 'package:path/path.dart' as path; import 'ast.dart'; import 'cpp/cpp_generator.dart'; import 'dart/dart_generator.dart'; -import 'generator_tools.dart'; import 'generator_tools.dart' as generator_tools; +import 'generator_tools.dart'; import 'gobject/gobject_generator.dart'; import 'java/java_generator.dart'; import 'kotlin/kotlin_generator.dart'; @@ -264,6 +264,7 @@ class PigeonOptions { this.debugGenerators, this.basePath, String? dartPackageName, + this.ignoreLints = true, }) : _dartPackageName = dartPackageName; /// Path to the file which will be processed. @@ -339,6 +340,9 @@ class PigeonOptions { /// The name of the package the pigeon files will be used in. final String? _dartPackageName; + /// Whether to ignore lint violations in generated Dart code. + final bool ignoreLints; + /// Creates a [PigeonOptions] from a Map representation where: /// `x = PigeonOptions.fromMap(x.toMap())`. static PigeonOptions fromMap(Map map) { @@ -389,7 +393,7 @@ class PigeonOptions { /// Converts a [PigeonOptions] to a Map representation where: /// `x = PigeonOptions.fromMap(x.toMap())`. Map toMap() { - final Map result = { + final result = { if (input != null) 'input': input!, if (dartOut != null) 'dartOut': dartOut!, if (dartTestOut != null) 'dartTestOut': dartTestOut!, @@ -450,23 +454,18 @@ class Pigeon { /// [sdkPath] for specifying the Dart SDK path for /// [AnalysisContextCollection]. ParseResults parseFile(String inputPath, {String? sdkPath}) { - final List includedPaths = [ - path.absolute(path.normalize(inputPath)), - ]; - final AnalysisContextCollection collection = AnalysisContextCollection( + final includedPaths = [path.absolute(path.normalize(inputPath))]; + final collection = AnalysisContextCollection( includedPaths: includedPaths, sdkPath: sdkPath, ); - final List compilationErrors = []; - final RootBuilder rootBuilder = RootBuilder( - File(inputPath).readAsStringSync(), - ); + final compilationErrors = []; + final rootBuilder = RootBuilder(File(inputPath).readAsStringSync()); for (final AnalysisContext context in collection.contexts) { for (final String path in context.contextRoot.analyzedFiles()) { final AnalysisSession session = context.currentSession; - final ParsedUnitResult result = - session.getParsedUnit(path) as ParsedUnitResult; + final result = session.getParsedUnit(path) as ParsedUnitResult; if (result.diagnostics.isEmpty) { final dart_ast.CompilationUnit unit = result.unit; unit.accept(rootBuilder); @@ -552,6 +551,10 @@ ${_argParser.usage}'''; help: 'The package that generated Kotlin code will be in.', aliases: const ['experimental_kotlin_package'], ) + ..addFlag( + 'kotlin_use_generated_annotation', + help: 'Adds javax.annotation.Generated annotation to the output.', + ) ..addOption( 'cpp_header_out', help: 'Path to generated C++ header file (.h).', @@ -616,6 +619,11 @@ ${_argParser.usage}'''; ..addOption( 'package_name', help: 'The package that generated code will be in.', + ) + ..addFlag( + 'ignore_lints', + help: 'Ignore all lint violations in generated Dart code.', + hide: true, ); /// Convert command-line arguments to [PigeonOptions]. @@ -626,7 +634,7 @@ ${_argParser.usage}'''; // `configurePigeon` function. final ArgResults results = _argParser.parse(args); - final PigeonOptions opts = PigeonOptions( + final opts = PigeonOptions( input: results['input'] as String?, dartOut: results['dart_out'] as String?, dartTestOut: results['dart_test_out'] as String?, @@ -643,6 +651,8 @@ ${_argParser.usage}'''; kotlinOut: results['kotlin_out'] as String?, kotlinOptions: KotlinOptions( package: results['kotlin_package'] as String?, + useGeneratedAnnotation: + results['kotlin_use_generated_annotation'] as bool? ?? false, ), cppHeaderOut: results['cpp_header_out'] as String?, cppSourceOut: results['cpp_source_out'] as String?, @@ -657,6 +667,7 @@ ${_argParser.usage}'''; debugGenerators: results['debug_generators'] as bool?, basePath: results['base_path'] as String?, dartPackageName: results['package_name'] as String?, + ignoreLints: results.flag('ignore_lints'), ); return opts; } @@ -711,15 +722,15 @@ ${_argParser.usage}'''; final List safeGeneratorAdapters = adapters ?? [ - DartGeneratorAdapter(), - JavaGeneratorAdapter(), - SwiftGeneratorAdapter(), - KotlinGeneratorAdapter(), - CppGeneratorAdapter(), - GObjectGeneratorAdapter(), - DartTestGeneratorAdapter(), - ObjcGeneratorAdapter(), - AstGeneratorAdapter(), + const DartGeneratorAdapter(), + const JavaGeneratorAdapter(), + const SwiftGeneratorAdapter(), + const KotlinGeneratorAdapter(), + const CppGeneratorAdapter(), + const GObjectGeneratorAdapter(), + const DartTestGeneratorAdapter(), + const ObjcGeneratorAdapter(), + const AstGeneratorAdapter(), ]; _executeConfigurePigeon(options); @@ -731,7 +742,7 @@ ${_argParser.usage}'''; parseResults = parseResults ?? pigeon.parseFile(options.input!, sdkPath: sdkPath); - final List errors = []; + final errors = []; errors.addAll(parseResults.errors); // Helper to clean up non-Stdout sinks. @@ -750,7 +761,7 @@ ${_argParser.usage}'''; final InternalPigeonOptions internalOptions = InternalPigeonOptions.fromPigeonOptions(options); - for (final GeneratorAdapter adapter in safeGeneratorAdapters) { + for (final adapter in safeGeneratorAdapters) { final IOSink? sink = adapter.shouldGenerate( internalOptions, FileType.source, @@ -780,7 +791,7 @@ ${_argParser.usage}'''; return 1; } - for (final GeneratorAdapter adapter in safeGeneratorAdapters) { + for (final adapter in safeGeneratorAdapters) { for (final FileType fileType in adapter.fileTypeList) { final IOSink? sink = adapter.shouldGenerate(internalOptions, fileType); if (sink != null) { @@ -796,7 +807,7 @@ ${_argParser.usage}'''; /// Print a list of errors to stderr. static void printErrors(List errors) { - for (final Error err in errors) { + for (final err in errors) { if (err.filename != null) { if (err.lineNumber != null) { stderr.writeln( diff --git a/packages/pigeon/lib/src/pigeon_lib_internal.dart b/packages/pigeon/lib/src/pigeon_lib_internal.dart index 7690f5696f5f..75bbb96a293e 100644 --- a/packages/pigeon/lib/src/pigeon_lib_internal.dart +++ b/packages/pigeon/lib/src/pigeon_lib_internal.dart @@ -111,7 +111,8 @@ class InternalPigeonOptions { options.dartOptions?.sourceOutPath == null) ? null : InternalDartOptions.fromDartOptions( - options.dartOptions ?? const DartOptions(), + options.dartOptions ?? + DartOptions(ignoreLints: options.ignoreLints), dartOut: options.dartOut, testOut: options.dartTestOut, copyrightHeader: copyrightHeader, @@ -182,9 +183,9 @@ class InternalPigeonOptions { Iterable _lineReader(String path) sync* { final String contents = File(path).readAsStringSync(); - const LineSplitter lineSplitter = LineSplitter(); + const lineSplitter = LineSplitter(); final List lines = lineSplitter.convert(contents); - for (final String line in lines) { + for (final line in lines) { yield line; } } @@ -193,26 +194,19 @@ IOSink? _openSink(String? output, {String basePath = ''}) { if (output == null) { return null; } - IOSink sink; - File file; if (output == 'stdout') { - sink = stdout; - } else { - file = File(path.posix.join(basePath, output)); - file.createSync(recursive: true); - sink = file.openWrite(); + return stdout; } - return sink; + final file = File(path.posix.join(basePath, output)); + file.createSync(recursive: true); + return file.openWrite(); } /// An adapter that will call a generator to write code to a sink /// based on the contents of [InternalPigeonOptions]. abstract class GeneratorAdapter { - /// Constructor for [GeneratorAdapter] - GeneratorAdapter(this.fileTypeList); - /// A list of file types the generator should create. - List fileTypeList; + List get fileTypeList; /// Returns an [IOSink] instance to be written to /// if the [GeneratorAdapter] should generate. @@ -257,10 +251,10 @@ void _errorOnInheritedClass(List errors, String generator, Root root) { /// A [GeneratorAdapter] that generates the AST. class AstGeneratorAdapter implements GeneratorAdapter { /// Constructor for [AstGeneratorAdapter]. - AstGeneratorAdapter(); + const AstGeneratorAdapter(); @override - List fileTypeList = const [FileType.na]; + List get fileTypeList => const [FileType.na]; @override void generate( @@ -283,13 +277,13 @@ class AstGeneratorAdapter implements GeneratorAdapter { /// A [GeneratorAdapter] that generates Dart source code. class DartGeneratorAdapter implements GeneratorAdapter { /// Constructor for [DartGeneratorAdapter]. - DartGeneratorAdapter(); + const DartGeneratorAdapter(); /// A string representing the name of the language being generated. - String languageString = 'Dart'; + static const String languageString = 'Dart'; @override - List fileTypeList = const [FileType.na]; + List get fileTypeList => const [FileType.na]; @override void generate( @@ -302,7 +296,7 @@ class DartGeneratorAdapter implements GeneratorAdapter { return; } - const DartGenerator generator = DartGenerator(); + const generator = DartGenerator(); generator.generate( options.dartOptions!, root, @@ -322,10 +316,10 @@ class DartGeneratorAdapter implements GeneratorAdapter { /// A [GeneratorAdapter] that generates Dart test source code. class DartTestGeneratorAdapter implements GeneratorAdapter { /// Constructor for [DartTestGeneratorAdapter]. - DartTestGeneratorAdapter(); + const DartTestGeneratorAdapter(); @override - List fileTypeList = const [FileType.na]; + List get fileTypeList => const [FileType.na]; @override void generate( @@ -337,7 +331,7 @@ class DartTestGeneratorAdapter implements GeneratorAdapter { if (options.dartOptions == null) { return; } - const DartGenerator testGenerator = DartGenerator(); + const testGenerator = DartGenerator(); // The test code needs the actual package name of the Dart output, even if // the package name has been overridden for other uses. final String outputPackageName = @@ -370,15 +364,16 @@ class DartTestGeneratorAdapter implements GeneratorAdapter { /// A [GeneratorAdapter] that generates Objective-C code. class ObjcGeneratorAdapter implements GeneratorAdapter { /// Constructor for [ObjcGeneratorAdapter]. - ObjcGeneratorAdapter({ - this.fileTypeList = const [FileType.header, FileType.source], - }); + const ObjcGeneratorAdapter(); /// A string representing the name of the language being generated. - String languageString = 'Objective-C'; + static const String languageString = 'Objective-C'; @override - List fileTypeList; + List get fileTypeList => const [ + FileType.header, + FileType.source, + ]; @override void generate( @@ -390,12 +385,11 @@ class ObjcGeneratorAdapter implements GeneratorAdapter { if (options.objcOptions == null) { return; } - final OutputFileOptions outputFileOptions = - OutputFileOptions( - fileType: fileType, - languageOptions: options.objcOptions!, - ); - const ObjcGenerator generator = ObjcGenerator(); + final outputFileOptions = OutputFileOptions( + fileType: fileType, + languageOptions: options.objcOptions!, + ); + const generator = ObjcGenerator(); generator.generate( outputFileOptions, root, @@ -421,7 +415,7 @@ class ObjcGeneratorAdapter implements GeneratorAdapter { @override List validate(InternalPigeonOptions options, Root root) { - final List errors = []; + final errors = []; _errorOnEventChannelApi(errors, languageString, root); _errorOnSealedClass(errors, languageString, root); _errorOnInheritedClass(errors, languageString, root); @@ -432,13 +426,13 @@ class ObjcGeneratorAdapter implements GeneratorAdapter { /// A [GeneratorAdapter] that generates Java source code. class JavaGeneratorAdapter implements GeneratorAdapter { /// Constructor for [JavaGeneratorAdapter]. - JavaGeneratorAdapter(); + const JavaGeneratorAdapter(); /// A string representing the name of the language being generated. - String languageString = 'Java'; + static const String languageString = 'Java'; @override - List fileTypeList = const [FileType.na]; + List get fileTypeList => const [FileType.na]; @override void generate( @@ -450,7 +444,7 @@ class JavaGeneratorAdapter implements GeneratorAdapter { if (options.javaOptions == null) { return; } - const JavaGenerator generator = JavaGenerator(); + const generator = JavaGenerator(); generator.generate( options.javaOptions!, root, @@ -465,7 +459,7 @@ class JavaGeneratorAdapter implements GeneratorAdapter { @override List validate(InternalPigeonOptions options, Root root) { - final List errors = []; + final errors = []; _errorOnEventChannelApi(errors, languageString, root); _errorOnSealedClass(errors, languageString, root); _errorOnInheritedClass(errors, languageString, root); @@ -476,13 +470,13 @@ class JavaGeneratorAdapter implements GeneratorAdapter { /// A [GeneratorAdapter] that generates Swift source code. class SwiftGeneratorAdapter implements GeneratorAdapter { /// Constructor for [SwiftGeneratorAdapter]. - SwiftGeneratorAdapter(); + const SwiftGeneratorAdapter(); /// A string representing the name of the language being generated. - String languageString = 'Swift'; + static const String languageString = 'Swift'; @override - List fileTypeList = const [FileType.na]; + List get fileTypeList => const [FileType.na]; @override void generate( @@ -494,7 +488,7 @@ class SwiftGeneratorAdapter implements GeneratorAdapter { if (options.swiftOptions == null) { return; } - const SwiftGenerator generator = SwiftGenerator(); + const generator = SwiftGenerator(); generator.generate( options.swiftOptions!, root, @@ -517,15 +511,16 @@ class SwiftGeneratorAdapter implements GeneratorAdapter { /// A [GeneratorAdapter] that generates C++ source code. class CppGeneratorAdapter implements GeneratorAdapter { /// Constructor for [CppGeneratorAdapter]. - CppGeneratorAdapter({ - this.fileTypeList = const [FileType.header, FileType.source], - }); + const CppGeneratorAdapter(); /// A string representing the name of the language being generated. - String languageString = 'C++'; + static const String languageString = 'C++'; @override - List fileTypeList; + List get fileTypeList => const [ + FileType.header, + FileType.source, + ]; @override void generate( @@ -537,12 +532,11 @@ class CppGeneratorAdapter implements GeneratorAdapter { if (options.cppOptions == null) { return; } - final OutputFileOptions outputFileOptions = - OutputFileOptions( - fileType: fileType, - languageOptions: options.cppOptions!, - ); - const CppGenerator generator = CppGenerator(); + final outputFileOptions = OutputFileOptions( + fileType: fileType, + languageOptions: options.cppOptions!, + ); + const generator = CppGenerator(); generator.generate( outputFileOptions, root, @@ -568,7 +562,7 @@ class CppGeneratorAdapter implements GeneratorAdapter { @override List validate(InternalPigeonOptions options, Root root) { - final List errors = []; + final errors = []; _errorOnEventChannelApi(errors, languageString, root); _errorOnSealedClass(errors, languageString, root); _errorOnInheritedClass(errors, languageString, root); @@ -579,15 +573,16 @@ class CppGeneratorAdapter implements GeneratorAdapter { /// A [GeneratorAdapter] that generates GObject source code. class GObjectGeneratorAdapter implements GeneratorAdapter { /// Constructor for [GObjectGeneratorAdapter]. - GObjectGeneratorAdapter({ - this.fileTypeList = const [FileType.header, FileType.source], - }); + const GObjectGeneratorAdapter(); /// A string representing the name of the language being generated. - String languageString = 'GObject'; + static const String languageString = 'GObject'; @override - List fileTypeList; + List get fileTypeList => const [ + FileType.header, + FileType.source, + ]; @override void generate( @@ -599,12 +594,11 @@ class GObjectGeneratorAdapter implements GeneratorAdapter { if (options.gobjectOptions == null) { return; } - final OutputFileOptions outputFileOptions = - OutputFileOptions( - fileType: fileType, - languageOptions: options.gobjectOptions!, - ); - const GObjectGenerator generator = GObjectGenerator(); + final outputFileOptions = OutputFileOptions( + fileType: fileType, + languageOptions: options.gobjectOptions!, + ); + const generator = GObjectGenerator(); generator.generate( outputFileOptions, root, @@ -630,7 +624,7 @@ class GObjectGeneratorAdapter implements GeneratorAdapter { @override List validate(InternalPigeonOptions options, Root root) { - final List errors = []; + final errors = []; // TODO(tarrinneal): Remove once overflow class is added to gobject generator. // https://github.com/flutter/flutter/issues/152916 if (root.classes.length + root.enums.length > totalCustomCodecKeysAllowed) { @@ -652,10 +646,10 @@ class GObjectGeneratorAdapter implements GeneratorAdapter { /// A [GeneratorAdapter] that generates Kotlin source code. class KotlinGeneratorAdapter implements GeneratorAdapter { /// Constructor for [KotlinGeneratorAdapter]. - KotlinGeneratorAdapter({this.fileTypeList = const [FileType.na]}); + const KotlinGeneratorAdapter(); @override - List fileTypeList; + List get fileTypeList => const [FileType.na]; @override void generate( @@ -667,7 +661,7 @@ class KotlinGeneratorAdapter implements GeneratorAdapter { if (options.kotlinOptions == null) { return; } - const KotlinGenerator generator = KotlinGenerator(); + const generator = KotlinGenerator(); generator.generate( options.kotlinOptions!, root, @@ -710,7 +704,7 @@ extension _ObjectAs on Object { } List _validateAst(Root root, String source) { - final List result = []; + final result = []; final List customClasses = root.classes .map((Class x) => x.name) .toList(); @@ -808,7 +802,7 @@ List _validateAst(Root root, String source) { } } - bool containsEventChannelApi = false; + var containsEventChannelApi = false; for (final Api api in root.apis) { final String? matchingPrefix = _findMatchingPrefixOrNull( @@ -924,7 +918,7 @@ List _validateAst(Root root, String source) { } } if (method.swiftFunction.isNotEmpty) { - final RegExp signatureRegex = RegExp( + final signatureRegex = RegExp( '\\w+ *\\((\\w+:){${method.parameters.length}}\\)', ); if (!signatureRegex.hasMatch(method.swiftFunction)) { @@ -958,7 +952,7 @@ List _validateProxyApi( required Set customClasses, required Set proxyApis, }) { - final List result = []; + final result = []; bool isDataClass(NamedType type) => customClasses.contains(type.type.baseName); @@ -1008,7 +1002,7 @@ List _validateProxyApi( final Iterable interfaceNames = api.interfaces.map( (TypeDeclaration type) => type.baseName, ); - for (final String interfaceName in interfaceNames) { + for (final interfaceName in interfaceNames) { if (!proxyApis.any((AstProxyApi api) => api.name == interfaceName)) { result.add( Error( @@ -1023,7 +1017,7 @@ List _validateProxyApi( final bool hasRequiredFlutterMethod = api.flutterMethods.any( (Method method) => method.isRequired, ); - for (final AstProxyApi proxyApi in proxyApis) { + for (final proxyApi in proxyApis) { // Validate this api is not used as an attached field while either: // 1. Having an unattached field. // 2. Having a required Flutter method. @@ -1062,7 +1056,7 @@ List _validateProxyApi( final Iterable interfaceNames = proxyApi.interfaces.map( (TypeDeclaration type) => type.baseName, ); - for (final String interfaceName in interfaceNames) { + for (final interfaceName in interfaceNames) { if (interfaceName == api.name) { result.add( Error( @@ -1082,7 +1076,10 @@ List _validateProxyApi( result.add(unsupportedDataClassError(parameter)); } - if (api.fields.any((ApiField field) => field.name == parameter.name) || + if (api.fields.any( + (ApiField field) => + field.name == parameter.name && !field.isAttached, + ) || api.flutterMethods.any( (Method method) => method.name == parameter.name, )) { @@ -1123,7 +1120,7 @@ List _validateProxyApi( } } if (constructor.swiftFunction.isNotEmpty) { - final RegExp signatureRegex = RegExp( + final signatureRegex = RegExp( '\\w+ *\\((\\w+:){${constructor.parameters.length}}\\)', ); if (!signatureRegex.hasMatch(constructor.swiftFunction)) { @@ -1238,7 +1235,7 @@ String? _findMatchingPrefixOrNull( String value, { required List prefixes, }) { - for (final String prefix in prefixes) { + for (final prefix in prefixes) { if (value.startsWith(prefix)) { return prefix; } @@ -1304,19 +1301,19 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { final Set referencedTypeNames = referencedTypes.keys .map((TypeDeclaration e) => e.baseName) .toSet(); - final List nonReferencedTypes = List.from(_classes); + final nonReferencedTypes = List.from(_classes); nonReferencedTypes.removeWhere( (Class x) => referencedTypeNames.contains(x.name), ); - for (final Class x in nonReferencedTypes) { + for (final x in nonReferencedTypes) { x.isReferenced = false; } - final List referencedEnums = List.from(_enums); - bool containsHostApi = false; - bool containsFlutterApi = false; - bool containsProxyApi = false; - bool containsEventChannel = false; + final referencedEnums = List.from(_enums); + var containsHostApi = false; + var containsFlutterApi = false; + var containsProxyApi = false; + var containsEventChannel = false; for (final Api api in _apis) { switch (api) { @@ -1331,7 +1328,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { } } - final Root completeRoot = Root( + final completeRoot = Root( apis: _apis, classes: _classes, enums: referencedEnums, @@ -1341,7 +1338,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { containsEventChannel: containsEventChannel, ); - final List totalErrors = List.from(_errors); + final totalErrors = List.from(_errors); for (final MapEntry> element in referencedTypes.entries) { @@ -1394,7 +1391,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { api.superClass = _attachAssociatedDefinition(api.superClass!); } - final Set newInterfaceSet = {}; + final newInterfaceSet = {}; for (final TypeDeclaration interface in api.interfaces) { newInterfaceSet.add(_attachAssociatedDefinition(interface)); } @@ -1433,7 +1430,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { type = type.copyWithProxyApi(assocProxyApi); } if (type.typeArguments.isNotEmpty) { - final List newTypes = []; + final newTypes = []; for (final TypeDeclaration type in type.typeArguments) { newTypes.add(_attachAssociatedDefinition(type)); } @@ -1444,7 +1441,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { } List _attachAssociatedDefinitions(Iterable types) { - final List result = []; + final result = []; for (final NamedType type in types) { result.add( type.copyWithType(_attachAssociatedDefinition(type.type)) as T, @@ -1469,7 +1466,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { Object _expressionToMap(dart_ast.Expression expression) { if (expression is dart_ast.MethodInvocation) { - final Map result = {}; + final result = {}; for (final dart_ast.Expression argument in expression.argumentList.arguments) { if (argument is dart_ast.NamedExpression) { @@ -1495,7 +1492,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { } else if (expression is dart_ast.SimpleIdentifier) { return expression.name; } else if (expression is dart_ast.ListLiteral) { - final List list = []; + final list = []; for (final dart_ast.CollectionElement element in expression.elements) { if (element is dart_ast.Expression) { list.add(_expressionToMap(element)); @@ -1510,7 +1507,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { } return list; } else if (expression is dart_ast.SetOrMapLiteral) { - final Set set = {}; + final set = {}; for (final dart_ast.CollectionElement element in expression.elements) { if (element is dart_ast.Expression) { set.add(_expressionToMap(element)); @@ -1561,7 +1558,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { ), ); } - final Map pigeonOptionsMap = + final pigeonOptionsMap = _expressionToMap(node.arguments!.arguments.first) as Map; _pigeonOptions = pigeonOptionsMap; @@ -1629,7 +1626,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { (dart_ast.Annotation element) => element.name.name == 'ProxyApi', ); - final Map annotationMap = {}; + final annotationMap = {}; for (final dart_ast.Expression expression in proxyApiAnnotation.arguments!.arguments) { if (expression is dart_ast.NamedExpression) { @@ -1639,7 +1636,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { } } - final String? superClassName = annotationMap['superClass'] as String?; + final superClassName = annotationMap['superClass'] as String?; TypeDeclaration? superClass; if (superClassName != null && node.extendsClause != null) { _errors.add( @@ -1661,7 +1658,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { ); } - final Set interfaces = {}; + final interfaces = {}; if (node.implementsClause != null) { for (final dart_ast.NamedType type in node.implementsClause!.interfaces) { @@ -1672,7 +1669,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { } SwiftProxyApiOptions? swiftOptions; - final Map? swiftOptionsMap = + final swiftOptionsMap = annotationMap['swiftOptions'] as Map?; if (swiftOptionsMap != null) { swiftOptions = SwiftProxyApiOptions( @@ -1706,7 +1703,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { tryParseApiRequirement(swiftOptions?.minMacosApi); KotlinProxyApiOptions? kotlinOptions; - final Map? kotlinOptionsMap = + final kotlinOptionsMap = annotationMap['kotlinOptions'] as Map?; if (kotlinOptionsMap != null) { kotlinOptions = KotlinProxyApiOptions( @@ -1734,7 +1731,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { element.name.name == 'EventChannelApi', ); - final Map annotationMap = {}; + final annotationMap = {}; for (final dart_ast.Expression expression in annotation.arguments!.arguments) { if (expression is dart_ast.NamedExpression) { @@ -1746,7 +1743,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { SwiftEventChannelOptions? swiftOptions; KotlinEventChannelOptions? kotlinOptions; - final Map? swiftOptionsMap = + final swiftOptionsMap = annotationMap['swiftOptions'] as Map?; if (swiftOptionsMap != null) { swiftOptions = SwiftEventChannelOptions( @@ -1754,7 +1751,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { swiftOptionsMap['includeSharedClasses'] as bool? ?? true, ); } - final Map? kotlinOptionsMap = + final kotlinOptionsMap = annotationMap['kotlinOptions'] as Map?; if (kotlinOptionsMap != null) { kotlinOptions = KotlinEventChannelOptions( @@ -1793,7 +1790,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { /// Converts Token's to Strings and removes documentation comment symbol. List _documentationCommentsParser(List? comments) { - const String docCommentPrefix = '///'; + const docCommentPrefix = '///'; return comments ?.map( (Token line) => line.length > docCommentPrefix.length @@ -1818,7 +1815,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { _getFirstChildOfType(formalParameter); if (parameter != null) { final String argTypeBaseName = _getNamedTypeQualifiedName(parameter); - final bool isNullable = parameter.question != null; + final isNullable = parameter.question != null; final List argTypeArguments = _typeAnnotationsToTypeArguments(parameter.typeArguments); return Parameter( @@ -1872,7 +1869,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { if (str == null) { return null; } - for (final T value in values) { + for (final value in values) { if (value.toString() == str) { return value; } @@ -1916,36 +1913,58 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { if (_currentApi != null) { // Methods without named return types aren't supported. - final dart_ast.TypeAnnotation returnType = node.returnType!; - returnType as dart_ast.NamedType; - _currentApi!.methods.add( - Method( - name: node.name.lexeme, - returnType: TypeDeclaration( - baseName: _getNamedTypeQualifiedName(returnType), - typeArguments: _typeAnnotationsToTypeArguments( - returnType.typeArguments, - ), - isNullable: returnType.question != null, + final dart_ast.TypeAnnotation? returnType = node.returnType; + if (returnType is! dart_ast.NamedType) { + // In order to support implicit types (either `dynamic` or inherited + // return types), type aliases, function types, or record types, we'd + // need to use the analyzer's element model, via `getParsedUnit` instead + // of `getParsedUnit` in `Pigeon.parseFile`, and then access the + // resolved return type, via + // `node.declaredFragment!.element.returnType`. + String erroneousDeclaration = node.name.lexeme; + final dart_ast.AstNode? enclosingDeclaration = node.parent; + if (enclosingDeclaration is dart_ast.ClassDeclaration) { + erroneousDeclaration = + '${enclosingDeclaration.name}.$erroneousDeclaration'; + } + _errors.add( + Error( + message: + 'Expected a named type for the return type of ' + '("$erroneousDeclaration").', + lineNumber: calculateLineNumber(source, node.offset), ), - parameters: arguments, - isStatic: isStatic, - location: switch (_currentApi!) { - AstHostApi() => ApiLocation.host, - AstProxyApi() => ApiLocation.host, - AstFlutterApi() => ApiLocation.flutter, - AstEventChannelApi() => ApiLocation.host, - }, - isAsynchronous: isAsynchronous, - objcSelector: objcSelector, - swiftFunction: swiftFunction, - offset: node.offset, - taskQueueType: taskQueueType, - documentationComments: _documentationCommentsParser( - node.documentationComment?.tokens, + ); + } else { + _currentApi!.methods.add( + Method( + name: node.name.lexeme, + returnType: TypeDeclaration( + baseName: _getNamedTypeQualifiedName(returnType), + typeArguments: _typeAnnotationsToTypeArguments( + returnType.typeArguments, + ), + isNullable: returnType.question != null, + ), + parameters: arguments, + isStatic: isStatic, + location: switch (_currentApi!) { + AstHostApi() => ApiLocation.host, + AstProxyApi() => ApiLocation.host, + AstFlutterApi() => ApiLocation.flutter, + AstEventChannelApi() => ApiLocation.host, + }, + isAsynchronous: isAsynchronous, + objcSelector: objcSelector, + swiftFunction: swiftFunction, + offset: node.offset, + taskQueueType: taskQueueType, + documentationComments: _documentationCommentsParser( + node.documentationComment?.tokens, + ), ), - ), - ); + ); + } } else if (_currentClass != null) { _errors.add( Error( @@ -1986,7 +2005,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { List _typeAnnotationsToTypeArguments( dart_ast.TypeArgumentList? typeArguments, ) { - final List result = []; + final result = []; if (typeArguments != null) { for (final Object x in typeArguments.childEntities) { if (x is dart_ast.NamedType) { @@ -2016,7 +2035,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { ), ); } else if (type is dart_ast.NamedType) { - final _FindInitializer findInitializerVisitor = _FindInitializer(); + final findInitializerVisitor = _FindInitializer(); node.visitChildren(findInitializerVisitor); if (findInitializerVisitor.initializer != null) { _errors.add( @@ -2029,7 +2048,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { } else { final dart_ast.TypeArgumentList? typeArguments = type.typeArguments; final String name = node.fields.variables[0].name.lexeme; - final NamedType field = NamedType( + final field = NamedType( type: TypeDeclaration( baseName: _getNamedTypeQualifiedName(type), isNullable: type.question != null, @@ -2200,7 +2219,7 @@ class RootBuilder extends dart_ast_visitor.RecursiveAstVisitor { ), ); } else if (type is dart_ast.NamedType) { - final _FindInitializer findInitializerVisitor = _FindInitializer(); + final findInitializerVisitor = _FindInitializer(); node.visitChildren(findInitializerVisitor); if (findInitializerVisitor.initializer != null) { _errors.add( @@ -2239,8 +2258,8 @@ int? _calculateLineNumberNullable(String contents, int? offset) { /// Calculates the line number for debugging. int calculateLineNumber(String contents, int offset) { - int result = 1; - for (int i = 0; i < offset; ++i) { + var result = 1; + for (var i = 0; i < offset; ++i) { if (contents[i] == '\n') { result += 1; } diff --git a/packages/pigeon/lib/src/swift/swift_generator.dart b/packages/pigeon/lib/src/swift/swift_generator.dart index 2f30a35fd4e7..45b968ed4d10 100644 --- a/packages/pigeon/lib/src/swift/swift_generator.dart +++ b/packages/pigeon/lib/src/swift/swift_generator.dart @@ -61,7 +61,7 @@ class SwiftOptions { /// Converts a [SwiftOptions] to a Map representation where: /// `x = SwiftOptions.fromList(x.toMap())`. Map toMap() { - final Map result = { + final result = { if (copyrightHeader != null) 'copyrightHeader': copyrightHeader!, if (fileSpecificClassNameComponent != null) 'fileSpecificClassNameComponent': fileSpecificClassNameComponent!, @@ -259,9 +259,9 @@ class SwiftGenerator extends StructuredGenerator { required String dartPackageName, }) { final String codecName = _getMessageCodecName(generatorOptions); - final String readerWriterName = '${codecName}ReaderWriter'; - final String readerName = '${codecName}Reader'; - final String writerName = '${codecName}Writer'; + final readerWriterName = '${codecName}ReaderWriter'; + final readerName = '${codecName}Reader'; + final writerName = '${codecName}Writer'; final List enumeratedTypes = getEnumeratedTypes( root, @@ -293,7 +293,7 @@ class SwiftGenerator extends StructuredGenerator { }); } - final EnumeratedType overflowClass = EnumeratedType( + final overflowClass = EnumeratedType( _overflowClassName, maximumCodecFieldKey, CustomTypes.customClass, @@ -319,7 +319,7 @@ class SwiftGenerator extends StructuredGenerator { indent.addScoped('{', '}', () { indent.write('switch type '); indent.addScoped('{', '}', nestCount: 0, () { - for (final EnumeratedType customType in enumeratedTypes) { + for (final customType in enumeratedTypes) { if (customType.enumeration < maximumCodecFieldKey) { writeDecodeLogic(customType); } @@ -344,15 +344,13 @@ class SwiftGenerator extends StructuredGenerator { indent.write('override func writeValue(_ value: Any) '); indent.addScoped('{', '}', () { indent.write(''); - for (final EnumeratedType customType in enumeratedTypes) { + for (final customType in enumeratedTypes) { indent.add('if let value = value as? ${customType.name} '); indent.addScoped('{', '} else ', () { - final String encodeString = - customType.type == CustomTypes.customClass + final encodeString = customType.type == CustomTypes.customClass ? 'toList()' : 'rawValue'; - final String valueString = - customType.enumeration < maximumCodecFieldKey + final valueString = customType.enumeration < maximumCodecFieldKey ? 'value.$encodeString' : 'wrap.toList()'; final int enumeration = @@ -421,8 +419,8 @@ class SwiftGenerator extends StructuredGenerator { bool private = false, bool hashable = true, }) { - final String privateString = private ? 'private ' : ''; - final String extendsString = classDefinition.superClass != null + final privateString = private ? 'private ' : ''; + final extendsString = classDefinition.superClass != null ? ': ${classDefinition.superClass!.name}' : hashable ? ': Hashable' @@ -448,7 +446,7 @@ class SwiftGenerator extends StructuredGenerator { _writeClassInit(indent, fields.toList()); } - for (final NamedType field in fields) { + for (final field in fields) { addDocumentationComments( indent, field.documentationComments, @@ -468,19 +466,16 @@ class SwiftGenerator extends StructuredGenerator { List types, { required String dartPackageName, }) { - final NamedType overflowInt = NamedType( + final overflowInt = NamedType( name: 'type', type: const TypeDeclaration(baseName: 'Int', isNullable: false), ); - final NamedType overflowObject = NamedType( + final overflowObject = NamedType( name: 'wrapped', type: const TypeDeclaration(baseName: 'Object', isNullable: true), ); - final List overflowFields = [ - overflowInt, - overflowObject, - ]; - final Class overflowClass = Class( + final overflowFields = [overflowInt, overflowObject]; + final overflowClass = Class( name: _overflowClassName, fields: overflowFields, ); @@ -556,7 +551,7 @@ if (wrapped == nil) { Class classDefinition, { required String dartPackageName, }) { - final List generatedComments = [ + final generatedComments = [ ' Generated class from Pigeon that represents data sent in messages.', ]; if (classDefinition.isSealed) { @@ -603,7 +598,7 @@ if (wrapped == nil) { void _writeClassInit(Indent indent, List fields) { indent.writeScoped('init(', ')', () { - for (int i = 0; i < fields.length; i++) { + for (var i = 0; i < fields.length; i++) { indent.write(''); _writeClassField(indent, fields[i]); if (i == fields.length - 1) { @@ -614,7 +609,7 @@ if (wrapped == nil) { } }, addTrailingNewline: false); indent.addScoped(' {', '}', () { - for (final NamedType field in fields) { + for (final field in fields) { _writeClassFieldInit(indent, field); } }); @@ -622,7 +617,7 @@ if (wrapped == nil) { void _writeClassField(Indent indent, NamedType field, {bool addNil = true}) { indent.add('${field.name}: ${_nullSafeSwiftTypeForDartType(field.type)}'); - final String defaultNil = field.type.isNullable && addNil ? ' = nil' : ''; + final defaultNil = field.type.isNullable && addNil ? ' = nil' : ''; indent.add(defaultNil); } @@ -644,7 +639,7 @@ if (wrapped == nil) { indent.addScoped('[', ']', () { // Follow swift-format style, which is to use a trailing comma unless // there is only one element. - final String separator = classDefinition.fields.length > 1 ? ',' : ''; + final separator = classDefinition.fields.length > 1 ? ',' : ''; for (final NamedType field in getFieldsInSerializationOrder( classDefinition, )) { @@ -666,21 +661,46 @@ if (wrapped == nil) { 'static func == (lhs: ${classDefinition.name}, rhs: ${classDefinition.name}) -> Bool {', '}', () { + indent.writeScoped( + 'if Swift.type(of: lhs) != Swift.type(of: rhs) {', + '}', + () { + indent.writeln('return false'); + }, + ); if (classDefinition.isSwiftClass) { indent.writeScoped('if (lhs === rhs) {', '}', () { indent.writeln('return true'); }); } - indent.write( - 'return deepEquals${generatorOptions.fileSpecificClassNameComponent}(lhs.toList(), rhs.toList())', + final Iterable fields = getFieldsInSerializationOrder( + classDefinition, ); + if (fields.isEmpty) { + indent.writeln('return true'); + } else { + final String comparisons = fields + .map( + (NamedType field) => + 'deepEquals${generatorOptions.fileSpecificClassNameComponent ?? ''}(lhs.${field.name}, rhs.${field.name})', + ) + .join(' && '); + indent.writeln('return $comparisons'); + } }, ); + indent.newln(); indent.writeScoped('func hash(into hasher: inout Hasher) {', '}', () { - indent.writeln( - 'deepHash${generatorOptions.fileSpecificClassNameComponent}(value: toList(), hasher: &hasher)', + indent.writeln('hasher.combine("${classDefinition.name}")'); + final Iterable fields = getFieldsInSerializationOrder( + classDefinition, ); + for (final field in fields) { + indent.writeln( + 'deepHash${generatorOptions.fileSpecificClassNameComponent ?? ''}(value: ${field.name}, hasher: &hasher)', + ); + } }); } @@ -703,7 +723,7 @@ if (wrapped == nil) { int index, final NamedType field, ) { - final String listValue = '${varNamePrefix}list[$index]'; + final listValue = '${varNamePrefix}list[$index]'; _writeGenericCasting( indent: indent, @@ -720,13 +740,13 @@ if (wrapped == nil) { for (final NamedType field in getFieldsInSerializationOrder( classDefinition, )) { - final String comma = + final comma = getFieldsInSerializationOrder(classDefinition).last == field ? '' : ','; // Force-casting nullable enums in maps doesn't work the same as other types. // It needs soft-casting followed by force unwrapping. - final String forceUnwrapMapWithNullableEnums = + final forceUnwrapMapWithNullableEnums = (field.type.baseName == 'Map' && !field.type.isNullable && field.type.typeArguments.any( @@ -779,7 +799,7 @@ if (wrapped == nil) { AstFlutterApi api, { required String dartPackageName, }) { - const List generatedComments = [ + const generatedComments = [ ' Generated protocol from Pigeon that represents Flutter messages that can be called from Swift.', ]; addDocumentationComments( @@ -864,7 +884,7 @@ if (wrapped == nil) { }) { final String apiName = api.name; - const List generatedComments = [ + const generatedComments = [ ' Generated protocol from Pigeon that represents a handler of messages from Flutter.', ]; addDocumentationComments( @@ -970,7 +990,7 @@ if (wrapped == nil) { Indent indent, { required String dartPackageName, }) { - final String instanceManagerApiName = + final instanceManagerApiName = '${swiftInstanceManagerClassName(generatorOptions)}Api'; final String removeStrongReferenceName = @@ -1010,8 +1030,7 @@ if (wrapped == nil) { indent.writeln( 'let codec = ${_getMessageCodecName(generatorOptions)}.shared', ); - const String setHandlerCondition = - 'let instanceManager = instanceManager'; + const setHandlerCondition = 'let instanceManager = instanceManager'; _writeHostMethodMessageHandler( indent, name: 'removeStrongReference', @@ -1154,7 +1173,7 @@ if (wrapped == nil) { indent.newln(); indent.writeScoped('override func writeValue(_ value: Any) {', '}', () { - final List nonProxyApiTypes = [ + final nonProxyApiTypes = [ '[Any]', 'Bool', 'Data', @@ -1206,7 +1225,7 @@ if (wrapped == nil) { ); enumerate(sortedApis, (int index, AstProxyApi api) { - final TypeDeclaration apiAsTypeDecl = TypeDeclaration( + final apiAsTypeDecl = TypeDeclaration( baseName: api.name, isNullable: false, associatedProxyApi: api, @@ -1278,15 +1297,14 @@ if (wrapped == nil) { AstProxyApi api, { required String dartPackageName, }) { - final TypeDeclaration apiAsTypeDeclaration = TypeDeclaration( + final apiAsTypeDeclaration = TypeDeclaration( baseName: api.name, isNullable: false, associatedProxyApi: api, ); - final String swiftApiDelegateName = - '${hostProxyApiPrefix}Delegate${api.name}'; - final String type = api.hasMethodsRequiringImplementation() + final swiftApiDelegateName = '${hostProxyApiPrefix}Delegate${api.name}'; + final type = api.hasMethodsRequiringImplementation() ? 'protocol' : 'open class'; indent.writeScoped('$type $swiftApiDelegateName {', '}', () { @@ -1315,8 +1333,7 @@ if (wrapped == nil) { }); indent.newln(); - final String swiftApiProtocolName = - '${hostProxyApiPrefix}Protocol${api.name}'; + final swiftApiProtocolName = '${hostProxyApiPrefix}Protocol${api.name}'; indent.writeScoped('protocol $swiftApiProtocolName {', '}', () { _writeProxyApiFlutterMethods( indent, @@ -1329,7 +1346,7 @@ if (wrapped == nil) { }); indent.newln(); - final String swiftApiName = '$hostProxyApiPrefix${api.name}'; + final swiftApiName = '$hostProxyApiPrefix${api.name}'; indent.writeScoped( 'final class $swiftApiName: $swiftApiProtocolName {', '}', @@ -1457,7 +1474,7 @@ if (wrapped == nil) { indent.write('return '); indent.addScoped('[', ']', () { indent.writeln(r'"\(error)",'); - indent.writeln(r'"\(type(of: error))",'); + indent.writeln(r'"\(Swift.type(of: error))",'); indent.writeln(r'"Stacktrace: \(Thread.callStackSymbols)",'); }); }); @@ -1490,8 +1507,29 @@ private func nilOrValue(_ value: Any?) -> T? { } void _writeDeepEquals(InternalSwiftOptions generatorOptions, Indent indent) { + final deepEqualsName = + 'deepEquals${generatorOptions.fileSpecificClassNameComponent ?? ''}'; + final deepHashName = + 'deepHash${generatorOptions.fileSpecificClassNameComponent ?? ''}'; + final doubleEqualsName = + 'doubleEquals${generatorOptions.fileSpecificClassNameComponent ?? ''}'; + final doubleHashName = + 'doubleHash${generatorOptions.fileSpecificClassNameComponent ?? ''}'; indent.format(''' -func deepEquals${generatorOptions.fileSpecificClassNameComponent}(_ lhs: Any?, _ rhs: Any?) -> Bool { +private func $doubleEqualsName(_ lhs: Double, _ rhs: Double) -> Bool { + return (lhs.isNaN && rhs.isNaN) || lhs == rhs +} + +private func $doubleHashName(_ value: Double, _ hasher: inout Hasher) { + if value.isNaN { + hasher.combine(0x7FF8000000000000) + } else { + // Normalize -0.0 to 0.0 + hasher.combine(value == 0 ? 0 : value) + } +} + +func $deepEqualsName(_ lhs: Any?, _ rhs: Any?) -> Bool { let cleanLhs = nilOrValue(lhs) as Any? let cleanRhs = nilOrValue(rhs) as Any? switch (cleanLhs, cleanRhs) { @@ -1501,59 +1539,92 @@ func deepEquals${generatorOptions.fileSpecificClassNameComponent}(_ lhs: Any?, _ case (nil, _), (_, nil): return false - case is (Void, Void): + case (let lhs as AnyObject, let rhs as AnyObject) where lhs === rhs: return true - case let (cleanLhsHashable, cleanRhsHashable) as (AnyHashable, AnyHashable): - return cleanLhsHashable == cleanRhsHashable + case is (Void, Void): + return true - case let (cleanLhsArray, cleanRhsArray) as ([Any?], [Any?]): - guard cleanLhsArray.count == cleanRhsArray.count else { return false } - for (index, element) in cleanLhsArray.enumerated() { - if !deepEquals${generatorOptions.fileSpecificClassNameComponent}(element, cleanRhsArray[index]) { + case (let lhsArray, let rhsArray) as ([Any?], [Any?]): + guard lhsArray.count == rhsArray.count else { return false } + for (index, element) in lhsArray.enumerated() { + if !$deepEqualsName(element, rhsArray[index]) { return false } } return true - case let (cleanLhsDictionary, cleanRhsDictionary) as ([AnyHashable: Any?], [AnyHashable: Any?]): - guard cleanLhsDictionary.count == cleanRhsDictionary.count else { return false } - for (key, cleanLhsValue) in cleanLhsDictionary { - guard cleanRhsDictionary.index(forKey: key) != nil else { return false } - if !deepEquals${generatorOptions.fileSpecificClassNameComponent}(cleanLhsValue, cleanRhsDictionary[key]!) { + case (let lhsArray, let rhsArray) as ([Double], [Double]): + guard lhsArray.count == rhsArray.count else { return false } + for (index, element) in lhsArray.enumerated() { + if !$doubleEqualsName(element, rhsArray[index]) { return false } } return true + case (let lhsDictionary, let rhsDictionary) as ([AnyHashable: Any?], [AnyHashable: Any?]): + guard lhsDictionary.count == rhsDictionary.count else { return false } + for (lhsKey, lhsValue) in lhsDictionary { + var found = false + for (rhsKey, rhsValue) in rhsDictionary { + if $deepEqualsName(lhsKey, rhsKey) { + if $deepEqualsName(lhsValue, rhsValue) { + found = true + break + } else { + return false + } + } + } + if !found { return false } + } + return true + + case (let lhs as Double, let rhs as Double): + return $doubleEqualsName(lhs, rhs) + + case (let lhsHashable, let rhsHashable) as (AnyHashable, AnyHashable): + return lhsHashable == rhsHashable + default: - // Any other type shouldn't be able to be used with pigeon. File an issue if you find this to be untrue. return false } } -func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, hasher: inout Hasher) { - if let valueList = value as? [AnyHashable] { - for item in valueList { deepHash${generatorOptions.fileSpecificClassNameComponent}(value: item, hasher: &hasher) } - return - } - - if let valueDict = value as? [AnyHashable: AnyHashable] { - for key in valueDict.keys { - hasher.combine(key) - deepHash${generatorOptions.fileSpecificClassNameComponent}(value: valueDict[key]!, hasher: &hasher) +func $deepHashName(value: Any?, hasher: inout Hasher) { + let cleanValue = nilOrValue(value) as Any? + if let cleanValue = cleanValue { + if let doubleValue = cleanValue as? Double { + $doubleHashName(doubleValue, &hasher) + } else if let valueList = cleanValue as? [Any?] { + for item in valueList { + $deepHashName(value: item, hasher: &hasher) + } + } else if let valueList = cleanValue as? [Double] { + for item in valueList { + $doubleHashName(item, &hasher) + } + } else if let valueDict = cleanValue as? [AnyHashable: Any?] { + var result = 0 + for (key, value) in valueDict { + var entryKeyHasher = Hasher() + $deepHashName(value: key, hasher: &entryKeyHasher) + var entryValueHasher = Hasher() + $deepHashName(value: value, hasher: &entryValueHasher) + result = result &+ ((entryKeyHasher.finalize() &* 31) ^ entryValueHasher.finalize()) + } + hasher.combine(result) + } else if let hashableValue = cleanValue as? AnyHashable { + hasher.combine(hashableValue) + } else { + hasher.combine(String(describing: cleanValue)) } - return - } - - if let hashableValue = value as? AnyHashable { - hasher.combine(hashableValue.hashValue) + } else { + hasher.combine(0) } - - return hasher.combine(String(describing: value)) } - - '''); +'''); } @override @@ -1714,10 +1785,10 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has (MapEntry e) => getEnumSafeArgumentExpression(e.key, e.value), ); - final String sendArgument = parameters.isEmpty + final sendArgument = parameters.isEmpty ? 'nil' : '[${enumSafeArgNames.join(', ')}] as [Any?]'; - const String channel = 'channel'; + const channel = 'channel'; indent.writeln('let channelName: String = "$channelName"'); indent.writeln( 'let $channel = FlutterBasicMessageChannel(name: channelName, binaryMessenger: binaryMessenger, codec: codec)', @@ -1763,7 +1834,7 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has type: returnType, ); // There is a swift bug with unwrapping maps of nullable Enums; - final String enumMapForceUnwrap = + final enumMapForceUnwrap = returnType.baseName == 'Map' && returnType.typeArguments.any( (TypeDeclaration type) => type.isEnum, @@ -1790,16 +1861,16 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has String Function(List safeArgNames, {required String apiVarName})? onCreateCall, }) { - final _SwiftFunctionComponents components = _SwiftFunctionComponents( + final components = _SwiftFunctionComponents( name: name, parameters: parameters, returnType: returnType, swiftFunction: swiftFunction, ); - final String varChannelName = '${name}Channel'; + final varChannelName = '${name}Channel'; addDocumentationComments(indent, documentationComments, _docCommentSpec); - final String baseArgs = + final baseArgs = 'name: "$channelName", ' 'binaryMessenger: binaryMessenger, codec: codec'; // The version with taskQueue: is an optional protocol method that isn't @@ -1809,12 +1880,12 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has // queue variable not being nil because the earlier code to set it will // return nil on macOS where the optional parts of the protocol are not // implemented. - final String channelCreationWithoutTaskQueue = + final channelCreationWithoutTaskQueue = 'FlutterBasicMessageChannel($baseArgs)'; if (serialBackgroundQueue == null) { indent.writeln('let $varChannelName = $channelCreationWithoutTaskQueue'); } else { - final String channelCreationWithTaskQueue = + final channelCreationWithTaskQueue = 'FlutterBasicMessageChannel($baseArgs, taskQueue: $serialBackgroundQueue)'; indent.write('let $varChannelName = $serialBackgroundQueue == nil'); @@ -1827,9 +1898,9 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has indent.write('if $setHandlerCondition '); indent.addScoped('{', '}', () { indent.write('$varChannelName.setMessageHandler '); - final String messageVarName = parameters.isNotEmpty ? 'message' : '_'; + final messageVarName = parameters.isNotEmpty ? 'message' : '_'; indent.addScoped('{ $messageVarName, reply in', '}', () { - final List methodArgument = []; + final methodArgument = []; if (components.arguments.isNotEmpty) { indent.writeln('let args = message as! [Any?]'); enumerate(components.arguments, ( @@ -1837,10 +1908,10 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has _SwiftFunctionArgument arg, ) { final String argName = _getSafeArgumentName(index, arg.namedType); - final String argIndex = 'args[$index]'; + final argIndex = 'args[$index]'; final String fieldType = _swiftTypeForDartType(arg.type); // There is a swift bug with unwrapping maps of nullable Enums; - final String enumMapForceUnwrap = + final enumMapForceUnwrap = arg.type.baseName == 'Map' && arg.type.typeArguments.any( (TypeDeclaration type) => type.isEnum, @@ -1865,12 +1936,12 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has } }); } - final String tryStatement = isAsynchronous ? '' : 'try '; + final tryStatement = isAsynchronous ? '' : 'try '; late final String call; if (onCreateCall == null) { // Empty parens are not required when calling a method whose only // argument is a trailing closure. - final String argumentString = methodArgument.isEmpty && isAsynchronous + final argumentString = methodArgument.isEmpty && isAsynchronous ? '' : '(${methodArgument.join(', ')})'; call = '${tryStatement}api.${components.name}$argumentString'; @@ -1878,10 +1949,8 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has call = onCreateCall(methodArgument, apiVarName: 'api'); } if (isAsynchronous) { - final String resultName = returnType.isVoid ? 'nil' : 'res'; - final String successVariableInit = returnType.isVoid - ? '' - : '(let res)'; + final resultName = returnType.isVoid ? 'nil' : 'res'; + final successVariableInit = returnType.isVoid ? '' : '(let res)'; indent.write('$call '); indent.addScoped('{ result in', '}', () { @@ -1924,11 +1993,11 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has required InternalSwiftOptions generatorOptions, required Iterable allProxyApis, }) { - final String delegateName = + final delegateName = '${generatorOptions.fileSpecificClassNameComponent ?? ''}${proxyApiClassNamePrefix}ProxyApiDelegate'; indent.writeScoped('protocol $delegateName {', '}', () { - for (final AstProxyApi api in allProxyApis) { - final String hostApiName = '$hostProxyApiPrefix${api.name}'; + for (final api in allProxyApis) { + final hostApiName = '$hostProxyApiPrefix${api.name}'; addDocumentationComments(indent, [ ' An implementation of [$hostApiName] used to add a new Dart instance of', ' `${api.name}` to the Dart `InstanceManager` and make calls to Dart.', @@ -1947,9 +2016,9 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has .where((AstProxyApi api) => !api.hasMethodsRequiringImplementation()); if (apisThatCanHaveADefaultImpl.isNotEmpty) { indent.writeScoped('extension $delegateName {', '}', () { - for (final AstProxyApi api in apisThatCanHaveADefaultImpl) { - final String hostApiName = '$hostProxyApiPrefix${api.name}'; - final String swiftApiDelegateName = + for (final api in apisThatCanHaveADefaultImpl) { + final hostApiName = '$hostProxyApiPrefix${api.name}'; + final swiftApiDelegateName = '${hostProxyApiPrefix}Delegate${api.name}'; indent.format(''' func pigeonApi${api.name}(_ registrar: ${proxyApiRegistrarName(generatorOptions)}) -> $hostApiName { @@ -1960,7 +2029,7 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has indent.newln(); } - final String instanceManagerApiName = + final instanceManagerApiName = '${swiftInstanceManagerClassName(generatorOptions)}Api'; indent.writeScoped( @@ -2019,7 +2088,7 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has indent.writeln( '$instanceManagerApiName.setUpMessageHandlers(binaryMessenger: binaryMessenger, instanceManager: instanceManager)', ); - for (final AstProxyApi api in allProxyApis) { + for (final api in allProxyApis) { if (api.hasAnyHostMessageCalls()) { indent.writeln( '$hostProxyApiPrefix${api.name}.setUpMessageHandlers(binaryMessenger: binaryMessenger, api: apiDelegate.pigeonApi${api.name}(self))', @@ -2032,7 +2101,7 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has indent.writeln( '$instanceManagerApiName.setUpMessageHandlers(binaryMessenger: binaryMessenger, instanceManager: nil)', ); - for (final AstProxyApi api in allProxyApis) { + for (final api in allProxyApis) { if (api.hasAnyHostMessageCalls()) { indent.writeln( '$hostProxyApiPrefix${api.name}.setUpMessageHandlers(binaryMessenger: binaryMessenger, api: nil)', @@ -2052,7 +2121,7 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has required TypeDeclaration apiAsTypeDeclaration, }) { for (final Constructor constructor in api.constructors) { - final List allReferencedTypes = [ + final allReferencedTypes = [ apiAsTypeDeclaration, ...api.unattachedFields.map((ApiField field) => field.type), ...constructor.parameters.map((Parameter parameter) => parameter.type), @@ -2113,7 +2182,7 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has required TypeDeclaration apiAsTypeDeclaration, }) { for (final ApiField field in api.attachedFields) { - final List allReferencedTypes = [ + final allReferencedTypes = [ apiAsTypeDeclaration, field.type, ]; @@ -2169,7 +2238,7 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has required TypeDeclaration apiAsTypeDeclaration, }) { for (final ApiField field in api.unattachedFields) { - final List allReferencedTypes = [ + final allReferencedTypes = [ apiAsTypeDeclaration, field.type, ]; @@ -2225,7 +2294,7 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has required TypeDeclaration apiAsTypeDeclaration, }) { for (final Method method in api.hostMethods) { - final List allReferencedTypes = [ + final allReferencedTypes = [ if (!method.isStatic) apiAsTypeDeclaration, method.returnType, ...method.parameters.map((Parameter p) => p.type), @@ -2281,11 +2350,11 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has // // These are used for inherited Flutter methods. void _writeProxyApiInheritedApiMethods(Indent indent, AstProxyApi api) { - final Set inheritedApiNames = { + final inheritedApiNames = { if (api.superClass != null) api.superClass!.baseName, ...api.interfaces.map((TypeDeclaration type) => type.baseName), }; - for (final String name in inheritedApiNames) { + for (final name in inheritedApiNames) { addDocumentationComments(indent, [ 'An implementation of [$name] used to access callback methods', ], _docCommentSpec); @@ -2345,7 +2414,7 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has addTrailingNewline: false, ); indent.writeScoped(' else {', '}', () { - final String varChannelName = '${methodName}Channel'; + final varChannelName = '${methodName}Channel'; indent.format(''' let $varChannelName = FlutterBasicMessageChannel( name: "$channelName", @@ -2402,7 +2471,7 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has List methodParameters, { required String apiVarName, }) { - final List parameters = [ + final parameters = [ 'pigeonApi: $apiVarName', // Skip the identifier used by the InstanceManager. ...methodParameters.skip(1), @@ -2452,7 +2521,7 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has List methodParameters, { required String apiVarName, }) { - final String instanceArg = field.isStatic + final instanceArg = field.isStatic ? '' : ', pigeonInstance: pigeonInstanceArg'; return '$apiVarName.pigeonRegistrar.instanceManager.addDartCreatedInstance(' @@ -2505,10 +2574,8 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has List methodParameters, { required String apiVarName, }) { - final String tryStatement = method.isAsynchronous - ? '' - : 'try '; - final List parameters = [ + final tryStatement = method.isAsynchronous ? '' : 'try '; + final parameters = [ 'pigeonApi: $apiVarName', // Skip the identifier used by the InstanceManager. ...methodParameters, @@ -2541,7 +2608,7 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has required String newInstanceMethodName, required String dartPackageName, }) { - final List allReferencedTypes = [ + final allReferencedTypes = [ apiAsTypeDeclaration, ...api.unattachedFields.map((ApiField field) => field.type), ]; @@ -2655,7 +2722,7 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has bool writeBody = true, }) { for (final Method method in api.flutterMethods) { - final List allReferencedTypes = [ + final allReferencedTypes = [ apiAsTypeDeclaration, ...method.parameters.map((Parameter parameter) => parameter.type), method.returnType, @@ -2704,7 +2771,26 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return'''); - }); + }, addTrailingNewline: false); + + final String instanceArgName = _getSafeArgumentName( + 0, + NamedType(name: 'pigeonInstance', type: apiAsTypeDeclaration), + ); + indent.writeScoped( + ' else if !pigeonRegistrar.instanceManager.containsInstance($instanceArgName as AnyObject) {', + '}', + () { + indent.format(''' + completion( + .failure( + ${_getErrorClassName(generatorOptions)}( + code: "missing-instance-error", + message: "Callback to `${api.name}.${method.name}` failed because native instance was not in the instance manager.", details: ""))) + return'''); + }, + ); + indent.writeln( 'let binaryMessenger = pigeonRegistrar.binaryMessenger', ); @@ -2764,9 +2850,8 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has } void _writeProxyApiImports(Indent indent, Iterable apis) { - final Map> apisOfImports = - >{}; - for (final AstProxyApi proxyApi in apis) { + final apisOfImports = >{}; + for (final proxyApi in apis) { final String? import = proxyApi.swiftOptions?.import; if (import != null) { if (apisOfImports.containsKey(import)) { @@ -2780,7 +2865,7 @@ func deepHash${generatorOptions.fileSpecificClassNameComponent}(value: Any?, has for (final String import in apisOfImports.keys) { // If every ProxyApi that shares an import excludes a platform for // support, surround the import with `#if !os(...) #endif`. - final List unsupportedPlatforms = [ + final unsupportedPlatforms = [ if (!apisOfImports[import]!.any( (AstProxyApi api) => api.swiftOptions?.supportsIos ?? true, )) @@ -2846,7 +2931,7 @@ String? _tryGetAvailabilityAnnotation(Iterable types) { final ({_VersionRequirement? ios, _VersionRequirement? macos}) versionRequirement = _findHighestVersionRequirement(types); - final List apis = [ + final apis = [ if (versionRequirement.ios != null) 'iOS ${versionRequirement.ios!.version}', if (versionRequirement.macos != null) @@ -2876,7 +2961,7 @@ String? _tryGetUnsupportedPlatformsCondition(Iterable types) { addAllRecursive, ); - final List unsupportedPlatforms = [ + final unsupportedPlatforms = [ if (!allReferencedTypes.every((TypeDeclaration type) { return type.associatedProxyApi?.swiftOptions?.supportsIos ?? true; })) @@ -2954,7 +3039,7 @@ String? _swiftTypeForBuiltinDartType( TypeDeclaration type, { bool mapKey = false, }) { - const Map swiftTypeForDartTypeMap = { + const swiftTypeForDartTypeMap = { 'void': 'Void', 'bool': 'Bool', 'String': 'String', @@ -2997,7 +3082,7 @@ String _nullSafeSwiftTypeForDartType( TypeDeclaration type, { bool mapKey = false, }) { - final String nullSafe = type.isNullable ? '?' : ''; + final nullSafe = type.isNullable ? '?' : ''; return '${_swiftTypeForDartType(type, mapKey: mapKey)}$nullSafe'; } @@ -3011,7 +3096,7 @@ String _getMethodSignature({ String Function(int index, NamedType argument) getParameterName = _getArgumentName, }) { - final _SwiftFunctionComponents components = _SwiftFunctionComponents( + final components = _SwiftFunctionComponents( name: name, parameters: parameters, returnType: returnType, @@ -3105,7 +3190,7 @@ class _SwiftFunctionComponents { } final String argsExtractor = repeat(r'(\w+):', parameters.length).join(); - final RegExp signatureRegex = RegExp(r'(\w+) *\(' + argsExtractor + r'\)'); + final signatureRegex = RegExp(r'(\w+) *\(' + argsExtractor + r'\)'); final RegExpMatch match = signatureRegex.firstMatch(swiftFunction)!; final Iterable labels = match diff --git a/packages/pigeon/pigeons/configure_pigeon_dart_out.dart b/packages/pigeon/pigeons/configure_pigeon_dart_out.dart index 6cec4e7b43aa..05282780d62f 100644 --- a/packages/pigeon/pigeons/configure_pigeon_dart_out.dart +++ b/packages/pigeon/pigeons/configure_pigeon_dart_out.dart @@ -8,7 +8,7 @@ import 'package:pigeon/pigeon.dart'; PigeonOptions( dartOut: 'stdout', javaOut: 'stdout', - dartOptions: DartOptions(), + dartOptions: DartOptions(ignoreLints: false), ), ) @HostApi() diff --git a/packages/pigeon/pigeons/core_tests.dart b/packages/pigeon/pigeons/core_tests.dart index 8795c8de900a..f55c0bbfd519 100644 --- a/packages/pigeon/pigeons/core_tests.dart +++ b/packages/pigeon/pigeons/core_tests.dart @@ -435,6 +435,17 @@ abstract class HostIntegrationCoreApi { // ========== Synchronous nullable method tests ========== + /// Returns the result of platform-side equality check. + bool areAllNullableTypesEqual(AllNullableTypes a, AllNullableTypes b); + + /// Returns the platform-side hash code for the given object. + int getAllNullableTypesHash(AllNullableTypes value); + + /// Returns the platform-side hash code for the given object. + int getAllNullableTypesWithoutRecursionHash( + AllNullableTypesWithoutRecursion value, + ); + /// Returns the passed object, to test serialization and deserialization. @ObjCSelector('echoAllNullableTypes:') @SwiftFunction('echo(_:)') diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/android/build.gradle b/packages/pigeon/platform_tests/alternate_language_test_plugin/android/build.gradle deleted file mode 100644 index e48d831f65c5..000000000000 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/android/build.gradle +++ /dev/null @@ -1,59 +0,0 @@ -group = 'com.example.alternate_language_test_plugin' -version = '1.0' - -buildscript { - repositories { - google() - mavenCentral() - } - - dependencies { - classpath 'com.android.tools.build:gradle:8.13.1' - } -} - -rootProject.allprojects { - repositories { - google() - mavenCentral() - } -} - -apply plugin: 'com.android.library' - -android { - namespace = "com.example.alternate_language_test_plugin" - compileSdk = flutter.compileSdkVersion - - compileOptions { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 - } - - defaultConfig { - minSdkVersion 21 - } - - testOptions { - unitTests.includeAndroidResources = true - unitTests.returnDefaultValues = true - unitTests.all { - testLogging { - events "passed", "skipped", "failed", "standardOut", "standardError" - outputs.upToDateWhen {false} - showStandardStreams = true - } - } - } - - lintOptions { - checkAllWarnings = true - warningsAsErrors = true - disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency', 'NewerVersionAvailable' - } - - dependencies { - testImplementation("junit:junit:4.13.2") - testImplementation("org.mockito:mockito-core:5.19.0") - } -} diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/android/build.gradle.kts b/packages/pigeon/platform_tests/alternate_language_test_plugin/android/build.gradle.kts new file mode 100644 index 000000000000..1925992c30a2 --- /dev/null +++ b/packages/pigeon/platform_tests/alternate_language_test_plugin/android/build.gradle.kts @@ -0,0 +1,63 @@ +group = "com.example.alternate_language_test_plugin" +version = "1.0" + +buildscript { + repositories { + google() + mavenCentral() + } + + dependencies { + classpath("com.android.tools.build:gradle:8.13.1") + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +plugins { + id("com.android.library") +} + +android { + namespace = "com.example.alternate_language_test_plugin" + compileSdk = flutter.compileSdkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + defaultConfig { + minSdk = 24 + } + + testOptions { + unitTests { + isIncludeAndroidResources = true + isReturnDefaultValues = true + all { + it.outputs.upToDateWhen { false } + it.testLogging { + events("passed", "skipped", "failed", "standardOut", "standardError") + showStandardStreams = true + } + } + } + } + + lint { + checkAllWarnings = true + warningsAsErrors = true + disable.addAll(setOf("AndroidGradlePluginVersion", "InvalidPackage", "GradleDependency", "NewerVersionAvailable")) + } + + dependencies { + testImplementation("junit:junit:4.13.2") + testImplementation("org.mockito:mockito-core:5.23.0") + } +} diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/android/settings.gradle b/packages/pigeon/platform_tests/alternate_language_test_plugin/android/settings.gradle deleted file mode 100644 index 0f10659c4e4e..000000000000 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/android/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'alternate_language_test_plugin' diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/android/settings.gradle.kts b/packages/pigeon/platform_tests/alternate_language_test_plugin/android/settings.gradle.kts new file mode 100644 index 000000000000..e6c1cb2b5f2e --- /dev/null +++ b/packages/pigeon/platform_tests/alternate_language_test_plugin/android/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "alternate_language_test_plugin" diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/main/java/com/example/alternate_language_test_plugin/AlternateLanguageTestPlugin.java b/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/main/java/com/example/alternate_language_test_plugin/AlternateLanguageTestPlugin.java index 4ece8628d399..5c46688a6d95 100644 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/main/java/com/example/alternate_language_test_plugin/AlternateLanguageTestPlugin.java +++ b/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/main/java/com/example/alternate_language_test_plugin/AlternateLanguageTestPlugin.java @@ -61,6 +61,23 @@ public void noop() {} return everything; } + @Override + public @NonNull Boolean areAllNullableTypesEqual( + @NonNull AllNullableTypes a, @NonNull AllNullableTypes b) { + return a.equals(b); + } + + @Override + public @NonNull Long getAllNullableTypesHash(@NonNull AllNullableTypes value) { + return (long) value.hashCode(); + } + + @Override + public @NonNull Long getAllNullableTypesWithoutRecursionHash( + @NonNull AllNullableTypesWithoutRecursion value) { + return (long) value.hashCode(); + } + @Override public @Nullable AllNullableTypesWithoutRecursion echoAllNullableTypesWithoutRecursion( @Nullable AllNullableTypesWithoutRecursion everything) { diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/main/java/com/example/alternate_language_test_plugin/CoreTests.java b/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/main/java/com/example/alternate_language_test_plugin/CoreTests.java index 66e0f3516fa4..8b3825849e95 100644 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/main/java/com/example/alternate_language_test_plugin/CoreTests.java +++ b/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/main/java/com/example/alternate_language_test_plugin/CoreTests.java @@ -26,11 +26,167 @@ import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.Objects; /** Generated class from Pigeon. */ @SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression", "serial"}) public class CoreTests { + static boolean pigeonDoubleEquals(double a, double b) { + // Normalize -0.0 to 0.0 and handle NaN equality. + return (a == 0.0 ? 0.0 : a) == (b == 0.0 ? 0.0 : b) || (Double.isNaN(a) && Double.isNaN(b)); + } + + static boolean pigeonFloatEquals(float a, float b) { + // Normalize -0.0 to 0.0 and handle NaN equality. + return (a == 0.0f ? 0.0f : a) == (b == 0.0f ? 0.0f : b) || (Float.isNaN(a) && Float.isNaN(b)); + } + + static int pigeonDoubleHashCode(double d) { + // Normalize -0.0 to 0.0 and handle NaN to ensure consistent hash codes. + if (d == 0.0) { + d = 0.0; + } + long bits = Double.doubleToLongBits(d); + return (int) (bits ^ (bits >>> 32)); + } + + static int pigeonFloatHashCode(float f) { + // Normalize -0.0 to 0.0 and handle NaN to ensure consistent hash codes. + if (f == 0.0f) { + f = 0.0f; + } + return Float.floatToIntBits(f); + } + + static boolean pigeonDeepEquals(Object a, Object b) { + if (a == b) { + return true; + } + if (a == null || b == null) { + return false; + } + if (a instanceof byte[] && b instanceof byte[]) { + return Arrays.equals((byte[]) a, (byte[]) b); + } + if (a instanceof int[] && b instanceof int[]) { + return Arrays.equals((int[]) a, (int[]) b); + } + if (a instanceof long[] && b instanceof long[]) { + return Arrays.equals((long[]) a, (long[]) b); + } + if (a instanceof double[] && b instanceof double[]) { + double[] da = (double[]) a; + double[] db = (double[]) b; + if (da.length != db.length) { + return false; + } + for (int i = 0; i < da.length; i++) { + if (!pigeonDoubleEquals(da[i], db[i])) { + return false; + } + } + return true; + } + if (a instanceof List && b instanceof List) { + List listA = (List) a; + List listB = (List) b; + if (listA.size() != listB.size()) { + return false; + } + for (int i = 0; i < listA.size(); i++) { + if (!pigeonDeepEquals(listA.get(i), listB.get(i))) { + return false; + } + } + return true; + } + if (a instanceof Map && b instanceof Map) { + Map mapA = (Map) a; + Map mapB = (Map) b; + if (mapA.size() != mapB.size()) { + return false; + } + for (Map.Entry entryA : mapA.entrySet()) { + Object keyA = entryA.getKey(); + Object valueA = entryA.getValue(); + boolean found = false; + for (Map.Entry entryB : mapB.entrySet()) { + Object keyB = entryB.getKey(); + if (pigeonDeepEquals(keyA, keyB)) { + Object valueB = entryB.getValue(); + if (pigeonDeepEquals(valueA, valueB)) { + found = true; + break; + } else { + return false; + } + } + } + if (!found) { + return false; + } + } + return true; + } + if (a instanceof Double && b instanceof Double) { + return pigeonDoubleEquals((double) a, (double) b); + } + if (a instanceof Float && b instanceof Float) { + return pigeonFloatEquals((float) a, (float) b); + } + return a.equals(b); + } + + static int pigeonDeepHashCode(Object value) { + if (value == null) { + return 0; + } + if (value instanceof byte[]) { + return Arrays.hashCode((byte[]) value); + } + if (value instanceof int[]) { + return Arrays.hashCode((int[]) value); + } + if (value instanceof long[]) { + return Arrays.hashCode((long[]) value); + } + if (value instanceof double[]) { + double[] da = (double[]) value; + int result = 1; + for (double d : da) { + result = 31 * result + pigeonDoubleHashCode(d); + } + return result; + } + if (value instanceof List) { + int result = 1; + for (Object item : (List) value) { + result = 31 * result + pigeonDeepHashCode(item); + } + return result; + } + if (value instanceof Map) { + int result = 0; + for (Map.Entry entry : ((Map) value).entrySet()) { + result += + ((pigeonDeepHashCode(entry.getKey()) * 31) ^ pigeonDeepHashCode(entry.getValue())); + } + return result; + } + if (value instanceof Object[]) { + int result = 1; + for (Object item : (Object[]) value) { + result = 31 * result + pigeonDeepHashCode(item); + } + return result; + } + if (value instanceof Double) { + return pigeonDoubleHashCode((double) value); + } + if (value instanceof Float) { + return pigeonFloatHashCode((float) value); + } + return value.hashCode(); + } /** Error class for passing custom error details to Flutter via a thrown PlatformException. */ public static class FlutterError extends RuntimeException { @@ -120,12 +276,13 @@ public boolean equals(Object o) { return false; } UnusedClass that = (UnusedClass) o; - return Objects.equals(aField, that.aField); + return pigeonDeepEquals(aField, that.aField); } @Override public int hashCode() { - return Objects.hash(aField); + Object[] fields = new Object[] {getClass(), aField}; + return pigeonDeepHashCode(fields); } public static final class Builder { @@ -542,69 +699,71 @@ public boolean equals(Object o) { return false; } AllTypes that = (AllTypes) o; - return aBool.equals(that.aBool) - && anInt.equals(that.anInt) - && anInt64.equals(that.anInt64) - && aDouble.equals(that.aDouble) - && Arrays.equals(aByteArray, that.aByteArray) - && Arrays.equals(a4ByteArray, that.a4ByteArray) - && Arrays.equals(a8ByteArray, that.a8ByteArray) - && Arrays.equals(aFloatArray, that.aFloatArray) - && anEnum.equals(that.anEnum) - && anotherEnum.equals(that.anotherEnum) - && aString.equals(that.aString) - && anObject.equals(that.anObject) - && list.equals(that.list) - && stringList.equals(that.stringList) - && intList.equals(that.intList) - && doubleList.equals(that.doubleList) - && boolList.equals(that.boolList) - && enumList.equals(that.enumList) - && objectList.equals(that.objectList) - && listList.equals(that.listList) - && mapList.equals(that.mapList) - && map.equals(that.map) - && stringMap.equals(that.stringMap) - && intMap.equals(that.intMap) - && enumMap.equals(that.enumMap) - && objectMap.equals(that.objectMap) - && listMap.equals(that.listMap) - && mapMap.equals(that.mapMap); + return pigeonDeepEquals(aBool, that.aBool) + && pigeonDeepEquals(anInt, that.anInt) + && pigeonDeepEquals(anInt64, that.anInt64) + && pigeonDeepEquals(aDouble, that.aDouble) + && pigeonDeepEquals(aByteArray, that.aByteArray) + && pigeonDeepEquals(a4ByteArray, that.a4ByteArray) + && pigeonDeepEquals(a8ByteArray, that.a8ByteArray) + && pigeonDeepEquals(aFloatArray, that.aFloatArray) + && pigeonDeepEquals(anEnum, that.anEnum) + && pigeonDeepEquals(anotherEnum, that.anotherEnum) + && pigeonDeepEquals(aString, that.aString) + && pigeonDeepEquals(anObject, that.anObject) + && pigeonDeepEquals(list, that.list) + && pigeonDeepEquals(stringList, that.stringList) + && pigeonDeepEquals(intList, that.intList) + && pigeonDeepEquals(doubleList, that.doubleList) + && pigeonDeepEquals(boolList, that.boolList) + && pigeonDeepEquals(enumList, that.enumList) + && pigeonDeepEquals(objectList, that.objectList) + && pigeonDeepEquals(listList, that.listList) + && pigeonDeepEquals(mapList, that.mapList) + && pigeonDeepEquals(map, that.map) + && pigeonDeepEquals(stringMap, that.stringMap) + && pigeonDeepEquals(intMap, that.intMap) + && pigeonDeepEquals(enumMap, that.enumMap) + && pigeonDeepEquals(objectMap, that.objectMap) + && pigeonDeepEquals(listMap, that.listMap) + && pigeonDeepEquals(mapMap, that.mapMap); } @Override public int hashCode() { - int pigeonVar_result = - Objects.hash( - aBool, - anInt, - anInt64, - aDouble, - anEnum, - anotherEnum, - aString, - anObject, - list, - stringList, - intList, - doubleList, - boolList, - enumList, - objectList, - listList, - mapList, - map, - stringMap, - intMap, - enumMap, - objectMap, - listMap, - mapMap); - pigeonVar_result = 31 * pigeonVar_result + Arrays.hashCode(aByteArray); - pigeonVar_result = 31 * pigeonVar_result + Arrays.hashCode(a4ByteArray); - pigeonVar_result = 31 * pigeonVar_result + Arrays.hashCode(a8ByteArray); - pigeonVar_result = 31 * pigeonVar_result + Arrays.hashCode(aFloatArray); - return pigeonVar_result; + Object[] fields = + new Object[] { + getClass(), + aBool, + anInt, + anInt64, + aDouble, + aByteArray, + a4ByteArray, + a8ByteArray, + aFloatArray, + anEnum, + anotherEnum, + aString, + anObject, + list, + stringList, + intList, + doubleList, + boolList, + enumList, + objectList, + listList, + mapList, + map, + stringMap, + intMap, + enumMap, + objectMap, + listMap, + mapMap + }; + return pigeonDeepHashCode(fields); } public static final class Builder { @@ -1288,75 +1447,77 @@ public boolean equals(Object o) { return false; } AllNullableTypes that = (AllNullableTypes) o; - return Objects.equals(aNullableBool, that.aNullableBool) - && Objects.equals(aNullableInt, that.aNullableInt) - && Objects.equals(aNullableInt64, that.aNullableInt64) - && Objects.equals(aNullableDouble, that.aNullableDouble) - && Arrays.equals(aNullableByteArray, that.aNullableByteArray) - && Arrays.equals(aNullable4ByteArray, that.aNullable4ByteArray) - && Arrays.equals(aNullable8ByteArray, that.aNullable8ByteArray) - && Arrays.equals(aNullableFloatArray, that.aNullableFloatArray) - && Objects.equals(aNullableEnum, that.aNullableEnum) - && Objects.equals(anotherNullableEnum, that.anotherNullableEnum) - && Objects.equals(aNullableString, that.aNullableString) - && Objects.equals(aNullableObject, that.aNullableObject) - && Objects.equals(allNullableTypes, that.allNullableTypes) - && Objects.equals(list, that.list) - && Objects.equals(stringList, that.stringList) - && Objects.equals(intList, that.intList) - && Objects.equals(doubleList, that.doubleList) - && Objects.equals(boolList, that.boolList) - && Objects.equals(enumList, that.enumList) - && Objects.equals(objectList, that.objectList) - && Objects.equals(listList, that.listList) - && Objects.equals(mapList, that.mapList) - && Objects.equals(recursiveClassList, that.recursiveClassList) - && Objects.equals(map, that.map) - && Objects.equals(stringMap, that.stringMap) - && Objects.equals(intMap, that.intMap) - && Objects.equals(enumMap, that.enumMap) - && Objects.equals(objectMap, that.objectMap) - && Objects.equals(listMap, that.listMap) - && Objects.equals(mapMap, that.mapMap) - && Objects.equals(recursiveClassMap, that.recursiveClassMap); + return pigeonDeepEquals(aNullableBool, that.aNullableBool) + && pigeonDeepEquals(aNullableInt, that.aNullableInt) + && pigeonDeepEquals(aNullableInt64, that.aNullableInt64) + && pigeonDeepEquals(aNullableDouble, that.aNullableDouble) + && pigeonDeepEquals(aNullableByteArray, that.aNullableByteArray) + && pigeonDeepEquals(aNullable4ByteArray, that.aNullable4ByteArray) + && pigeonDeepEquals(aNullable8ByteArray, that.aNullable8ByteArray) + && pigeonDeepEquals(aNullableFloatArray, that.aNullableFloatArray) + && pigeonDeepEquals(aNullableEnum, that.aNullableEnum) + && pigeonDeepEquals(anotherNullableEnum, that.anotherNullableEnum) + && pigeonDeepEquals(aNullableString, that.aNullableString) + && pigeonDeepEquals(aNullableObject, that.aNullableObject) + && pigeonDeepEquals(allNullableTypes, that.allNullableTypes) + && pigeonDeepEquals(list, that.list) + && pigeonDeepEquals(stringList, that.stringList) + && pigeonDeepEquals(intList, that.intList) + && pigeonDeepEquals(doubleList, that.doubleList) + && pigeonDeepEquals(boolList, that.boolList) + && pigeonDeepEquals(enumList, that.enumList) + && pigeonDeepEquals(objectList, that.objectList) + && pigeonDeepEquals(listList, that.listList) + && pigeonDeepEquals(mapList, that.mapList) + && pigeonDeepEquals(recursiveClassList, that.recursiveClassList) + && pigeonDeepEquals(map, that.map) + && pigeonDeepEquals(stringMap, that.stringMap) + && pigeonDeepEquals(intMap, that.intMap) + && pigeonDeepEquals(enumMap, that.enumMap) + && pigeonDeepEquals(objectMap, that.objectMap) + && pigeonDeepEquals(listMap, that.listMap) + && pigeonDeepEquals(mapMap, that.mapMap) + && pigeonDeepEquals(recursiveClassMap, that.recursiveClassMap); } @Override public int hashCode() { - int pigeonVar_result = - Objects.hash( - aNullableBool, - aNullableInt, - aNullableInt64, - aNullableDouble, - aNullableEnum, - anotherNullableEnum, - aNullableString, - aNullableObject, - allNullableTypes, - list, - stringList, - intList, - doubleList, - boolList, - enumList, - objectList, - listList, - mapList, - recursiveClassList, - map, - stringMap, - intMap, - enumMap, - objectMap, - listMap, - mapMap, - recursiveClassMap); - pigeonVar_result = 31 * pigeonVar_result + Arrays.hashCode(aNullableByteArray); - pigeonVar_result = 31 * pigeonVar_result + Arrays.hashCode(aNullable4ByteArray); - pigeonVar_result = 31 * pigeonVar_result + Arrays.hashCode(aNullable8ByteArray); - pigeonVar_result = 31 * pigeonVar_result + Arrays.hashCode(aNullableFloatArray); - return pigeonVar_result; + Object[] fields = + new Object[] { + getClass(), + aNullableBool, + aNullableInt, + aNullableInt64, + aNullableDouble, + aNullableByteArray, + aNullable4ByteArray, + aNullable8ByteArray, + aNullableFloatArray, + aNullableEnum, + anotherNullableEnum, + aNullableString, + aNullableObject, + allNullableTypes, + list, + stringList, + intList, + doubleList, + boolList, + enumList, + objectList, + listList, + mapList, + recursiveClassList, + map, + stringMap, + intMap, + enumMap, + objectMap, + listMap, + mapMap, + recursiveClassMap + }; + return pigeonDeepHashCode(fields); } public static final class Builder { @@ -2048,69 +2209,71 @@ public boolean equals(Object o) { return false; } AllNullableTypesWithoutRecursion that = (AllNullableTypesWithoutRecursion) o; - return Objects.equals(aNullableBool, that.aNullableBool) - && Objects.equals(aNullableInt, that.aNullableInt) - && Objects.equals(aNullableInt64, that.aNullableInt64) - && Objects.equals(aNullableDouble, that.aNullableDouble) - && Arrays.equals(aNullableByteArray, that.aNullableByteArray) - && Arrays.equals(aNullable4ByteArray, that.aNullable4ByteArray) - && Arrays.equals(aNullable8ByteArray, that.aNullable8ByteArray) - && Arrays.equals(aNullableFloatArray, that.aNullableFloatArray) - && Objects.equals(aNullableEnum, that.aNullableEnum) - && Objects.equals(anotherNullableEnum, that.anotherNullableEnum) - && Objects.equals(aNullableString, that.aNullableString) - && Objects.equals(aNullableObject, that.aNullableObject) - && Objects.equals(list, that.list) - && Objects.equals(stringList, that.stringList) - && Objects.equals(intList, that.intList) - && Objects.equals(doubleList, that.doubleList) - && Objects.equals(boolList, that.boolList) - && Objects.equals(enumList, that.enumList) - && Objects.equals(objectList, that.objectList) - && Objects.equals(listList, that.listList) - && Objects.equals(mapList, that.mapList) - && Objects.equals(map, that.map) - && Objects.equals(stringMap, that.stringMap) - && Objects.equals(intMap, that.intMap) - && Objects.equals(enumMap, that.enumMap) - && Objects.equals(objectMap, that.objectMap) - && Objects.equals(listMap, that.listMap) - && Objects.equals(mapMap, that.mapMap); + return pigeonDeepEquals(aNullableBool, that.aNullableBool) + && pigeonDeepEquals(aNullableInt, that.aNullableInt) + && pigeonDeepEquals(aNullableInt64, that.aNullableInt64) + && pigeonDeepEquals(aNullableDouble, that.aNullableDouble) + && pigeonDeepEquals(aNullableByteArray, that.aNullableByteArray) + && pigeonDeepEquals(aNullable4ByteArray, that.aNullable4ByteArray) + && pigeonDeepEquals(aNullable8ByteArray, that.aNullable8ByteArray) + && pigeonDeepEquals(aNullableFloatArray, that.aNullableFloatArray) + && pigeonDeepEquals(aNullableEnum, that.aNullableEnum) + && pigeonDeepEquals(anotherNullableEnum, that.anotherNullableEnum) + && pigeonDeepEquals(aNullableString, that.aNullableString) + && pigeonDeepEquals(aNullableObject, that.aNullableObject) + && pigeonDeepEquals(list, that.list) + && pigeonDeepEquals(stringList, that.stringList) + && pigeonDeepEquals(intList, that.intList) + && pigeonDeepEquals(doubleList, that.doubleList) + && pigeonDeepEquals(boolList, that.boolList) + && pigeonDeepEquals(enumList, that.enumList) + && pigeonDeepEquals(objectList, that.objectList) + && pigeonDeepEquals(listList, that.listList) + && pigeonDeepEquals(mapList, that.mapList) + && pigeonDeepEquals(map, that.map) + && pigeonDeepEquals(stringMap, that.stringMap) + && pigeonDeepEquals(intMap, that.intMap) + && pigeonDeepEquals(enumMap, that.enumMap) + && pigeonDeepEquals(objectMap, that.objectMap) + && pigeonDeepEquals(listMap, that.listMap) + && pigeonDeepEquals(mapMap, that.mapMap); } @Override public int hashCode() { - int pigeonVar_result = - Objects.hash( - aNullableBool, - aNullableInt, - aNullableInt64, - aNullableDouble, - aNullableEnum, - anotherNullableEnum, - aNullableString, - aNullableObject, - list, - stringList, - intList, - doubleList, - boolList, - enumList, - objectList, - listList, - mapList, - map, - stringMap, - intMap, - enumMap, - objectMap, - listMap, - mapMap); - pigeonVar_result = 31 * pigeonVar_result + Arrays.hashCode(aNullableByteArray); - pigeonVar_result = 31 * pigeonVar_result + Arrays.hashCode(aNullable4ByteArray); - pigeonVar_result = 31 * pigeonVar_result + Arrays.hashCode(aNullable8ByteArray); - pigeonVar_result = 31 * pigeonVar_result + Arrays.hashCode(aNullableFloatArray); - return pigeonVar_result; + Object[] fields = + new Object[] { + getClass(), + aNullableBool, + aNullableInt, + aNullableInt64, + aNullableDouble, + aNullableByteArray, + aNullable4ByteArray, + aNullable8ByteArray, + aNullableFloatArray, + aNullableEnum, + anotherNullableEnum, + aNullableString, + aNullableObject, + list, + stringList, + intList, + doubleList, + boolList, + enumList, + objectList, + listList, + mapList, + map, + stringMap, + intMap, + enumMap, + objectMap, + listMap, + mapMap + }; + return pigeonDeepHashCode(fields); } public static final class Builder { @@ -2573,25 +2736,30 @@ public boolean equals(Object o) { return false; } AllClassesWrapper that = (AllClassesWrapper) o; - return allNullableTypes.equals(that.allNullableTypes) - && Objects.equals(allNullableTypesWithoutRecursion, that.allNullableTypesWithoutRecursion) - && Objects.equals(allTypes, that.allTypes) - && classList.equals(that.classList) - && Objects.equals(nullableClassList, that.nullableClassList) - && classMap.equals(that.classMap) - && Objects.equals(nullableClassMap, that.nullableClassMap); + return pigeonDeepEquals(allNullableTypes, that.allNullableTypes) + && pigeonDeepEquals( + allNullableTypesWithoutRecursion, that.allNullableTypesWithoutRecursion) + && pigeonDeepEquals(allTypes, that.allTypes) + && pigeonDeepEquals(classList, that.classList) + && pigeonDeepEquals(nullableClassList, that.nullableClassList) + && pigeonDeepEquals(classMap, that.classMap) + && pigeonDeepEquals(nullableClassMap, that.nullableClassMap); } @Override public int hashCode() { - return Objects.hash( - allNullableTypes, - allNullableTypesWithoutRecursion, - allTypes, - classList, - nullableClassList, - classMap, - nullableClassMap); + Object[] fields = + new Object[] { + getClass(), + allNullableTypes, + allNullableTypesWithoutRecursion, + allTypes, + classList, + nullableClassList, + classMap, + nullableClassMap + }; + return pigeonDeepHashCode(fields); } public static final class Builder { @@ -2728,12 +2896,13 @@ public boolean equals(Object o) { return false; } TestMessage that = (TestMessage) o; - return Objects.equals(testList, that.testList); + return pigeonDeepEquals(testList, that.testList); } @Override public int hashCode() { - return Objects.hash(testList); + Object[] fields = new Object[] {getClass(), testList}; + return pigeonDeepHashCode(fields); } public static final class Builder { @@ -2959,6 +3128,15 @@ public interface HostIntegrationCoreApi { /** Returns passed in int. */ @NonNull Long echoRequiredInt(@NonNull Long anInt); + /** Returns the result of platform-side equality check. */ + @NonNull + Boolean areAllNullableTypesEqual(@NonNull AllNullableTypes a, @NonNull AllNullableTypes b); + /** Returns the platform-side hash code for the given object. */ + @NonNull + Long getAllNullableTypesHash(@NonNull AllNullableTypes value); + /** Returns the platform-side hash code for the given object. */ + @NonNull + Long getAllNullableTypesWithoutRecursionHash(@NonNull AllNullableTypesWithoutRecursion value); /** Returns the passed object, to test serialization and deserialization. */ @Nullable AllNullableTypes echoAllNullableTypes(@Nullable AllNullableTypes everything); @@ -4120,6 +4298,83 @@ static void setUp( channel.setMessageHandler(null); } } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, + "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.areAllNullableTypesEqual" + + messageChannelSuffix, + getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList<>(); + ArrayList args = (ArrayList) message; + AllNullableTypes aArg = (AllNullableTypes) args.get(0); + AllNullableTypes bArg = (AllNullableTypes) args.get(1); + try { + Boolean output = api.areAllNullableTypesEqual(aArg, bArg); + wrapped.add(0, output); + } catch (Throwable exception) { + wrapped = wrapError(exception); + } + reply.reply(wrapped); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, + "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.getAllNullableTypesHash" + + messageChannelSuffix, + getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList<>(); + ArrayList args = (ArrayList) message; + AllNullableTypes valueArg = (AllNullableTypes) args.get(0); + try { + Long output = api.getAllNullableTypesHash(valueArg); + wrapped.add(0, output); + } catch (Throwable exception) { + wrapped = wrapError(exception); + } + reply.reply(wrapped); + }); + } else { + channel.setMessageHandler(null); + } + } + { + BasicMessageChannel channel = + new BasicMessageChannel<>( + binaryMessenger, + "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.getAllNullableTypesWithoutRecursionHash" + + messageChannelSuffix, + getCodec()); + if (api != null) { + channel.setMessageHandler( + (message, reply) -> { + ArrayList wrapped = new ArrayList<>(); + ArrayList args = (ArrayList) message; + AllNullableTypesWithoutRecursion valueArg = + (AllNullableTypesWithoutRecursion) args.get(0); + try { + Long output = api.getAllNullableTypesWithoutRecursionHash(valueArg); + wrapped.add(0, output); + } catch (Throwable exception) { + wrapped = wrapError(exception); + } + reply.reply(wrapped); + }); + } else { + channel.setMessageHandler(null); + } + } { BasicMessageChannel channel = new BasicMessageChannel<>( diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/AllDatatypesTest.java b/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/AllDatatypesTest.java index 1fb1e451dbbb..5671cc465163 100644 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/AllDatatypesTest.java +++ b/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/AllDatatypesTest.java @@ -266,4 +266,86 @@ public void error(Throwable error) { }); assertTrue(didCall[0]); } + + @Test + public void equalityWithNaN() { + AllNullableTypes withNaN = + new AllNullableTypes.Builder().setANullableDouble(Double.NaN).build(); + AllNullableTypes withAnotherNaN = + new AllNullableTypes.Builder().setANullableDouble(Double.NaN).build(); + assertEquals(withNaN, withAnotherNaN); + assertEquals(withNaN.hashCode(), withAnotherNaN.hashCode()); + } + + @Test + public void crossTypeEquality() { + AllNullableTypes a = new AllNullableTypes.Builder().setANullableInt(1L).build(); + CoreTests.AllNullableTypesWithoutRecursion b = + new CoreTests.AllNullableTypesWithoutRecursion.Builder().setANullableInt(1L).build(); + assertNotEquals(a, b); + assertNotEquals(b, a); + } + + @Test + public void zeroEquality() { + AllNullableTypes a = new AllNullableTypes.Builder().setANullableDouble(0.0).build(); + AllNullableTypes b = new AllNullableTypes.Builder().setANullableDouble(-0.0).build(); + + assertEquals(a, b); + assertEquals(a.hashCode(), b.hashCode()); + } + + @Test + public void nestedByteArrayEquality() { + byte[] data = new byte[] {1, 2, 3}; + List list1 = new ArrayList<>(); + list1.add(data); + AllNullableTypes a = new AllNullableTypes.Builder().setList(list1).build(); + + List list2 = new ArrayList<>(); + list2.add(new byte[] {1, 2, 3}); + AllNullableTypes b = new AllNullableTypes.Builder().setList(list2).build(); + + assertEquals(a, b); + assertEquals(a.hashCode(), b.hashCode()); + } + + @Test + public void nestedZeroListEquality() { + List list1 = new ArrayList<>(); + list1.add(0.0); + AllNullableTypes a = new AllNullableTypes.Builder().setDoubleList(list1).build(); + + List list2 = new ArrayList<>(); + list2.add(-0.0); + AllNullableTypes b = new AllNullableTypes.Builder().setDoubleList(list2).build(); + + assertEquals(a, b); + assertEquals(a.hashCode(), b.hashCode()); + } + + @Test + public void zeroMapKeyEquality() { + Map map1 = new HashMap<>(); + map1.put(0.0, "a"); + AllNullableTypes a = new AllNullableTypes.Builder().setMap(map1).build(); + + Map map2 = new HashMap<>(); + map2.put(-0.0, "a"); + AllNullableTypes b = new AllNullableTypes.Builder().setMap(map2).build(); + + assertEquals(a, b); + assertEquals(a.hashCode(), b.hashCode()); + } + + @Test + public void nestedZeroArrayEquality() { + AllNullableTypes a = + new AllNullableTypes.Builder().setANullableFloatArray(new double[] {0.0}).build(); + AllNullableTypes b = + new AllNullableTypes.Builder().setANullableFloatArray(new double[] {-0.0}).build(); + + assertEquals(a, b); + assertEquals(a.hashCode(), b.hashCode()); + } } diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/darwin/alternate_language_test_plugin/Sources/alternate_language_test_plugin/AlternateLanguageTestPlugin.m b/packages/pigeon/platform_tests/alternate_language_test_plugin/darwin/alternate_language_test_plugin/Sources/alternate_language_test_plugin/AlternateLanguageTestPlugin.m index 1d494ba618ed..fdd0a0563ae5 100644 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/darwin/alternate_language_test_plugin/Sources/alternate_language_test_plugin/AlternateLanguageTestPlugin.m +++ b/packages/pigeon/platform_tests/alternate_language_test_plugin/darwin/alternate_language_test_plugin/Sources/alternate_language_test_plugin/AlternateLanguageTestPlugin.m @@ -201,6 +201,23 @@ - (nullable NSNumber *)echoRequiredInt:(NSInteger)anInt return @(anInt); } +- (nullable NSNumber *)areAllNullableTypesEqualA:(FLTAllNullableTypes *)a + b:(FLTAllNullableTypes *)b + error:(FlutterError *_Nullable *_Nonnull)error { + return @([a isEqual:b]); +} + +- (nullable NSNumber *)getAllNullableTypesHashValue:(FLTAllNullableTypes *)value + error:(FlutterError *_Nullable *_Nonnull)error { + return @([value hash]); +} + +- (nullable NSNumber *) + getAllNullableTypesWithoutRecursionHashValue:(FLTAllNullableTypesWithoutRecursion *)value + error:(FlutterError *_Nullable *_Nonnull)error { + return @([value hash]); +} + - (nullable NSString *)extractNestedNullableStringFrom:(FLTAllClassesWrapper *)wrapper error:(FlutterError *_Nullable *_Nonnull)error { return wrapper.allNullableTypes.aNullableString; diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/darwin/alternate_language_test_plugin/Sources/alternate_language_test_plugin/CoreTests.gen.m b/packages/pigeon/platform_tests/alternate_language_test_plugin/darwin/alternate_language_test_plugin/Sources/alternate_language_test_plugin/CoreTests.gen.m index 5ca6a3781e5c..7c114f8fa47b 100644 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/darwin/alternate_language_test_plugin/Sources/alternate_language_test_plugin/CoreTests.gen.m +++ b/packages/pigeon/platform_tests/alternate_language_test_plugin/darwin/alternate_language_test_plugin/Sources/alternate_language_test_plugin/CoreTests.gen.m @@ -8,14 +8,101 @@ #import "./include/alternate_language_test_plugin/CoreTests.gen.h" #if TARGET_OS_OSX -#import +@import FlutterMacOS; #else -#import +@import Flutter; #endif -#if !__has_feature(objc_arc) -#error File requires ARC to be enabled. -#endif +static BOOL __attribute__((unused)) FLTPigeonDeepEquals(id _Nullable a, id _Nullable b) { + if (a == b) { + return YES; + } + if (a == nil) { + return b == [NSNull null]; + } + if (b == nil) { + return a == [NSNull null]; + } + if ([a isKindOfClass:[NSNumber class]] && [b isKindOfClass:[NSNumber class]]) { + return + [a isEqual:b] || (isnan([(NSNumber *)a doubleValue]) && isnan([(NSNumber *)b doubleValue])); + } + if ([a isKindOfClass:[NSArray class]] && [b isKindOfClass:[NSArray class]]) { + NSArray *arrayA = (NSArray *)a; + NSArray *arrayB = (NSArray *)b; + if (arrayA.count != arrayB.count) { + return NO; + } + for (NSUInteger i = 0; i < arrayA.count; i++) { + if (!FLTPigeonDeepEquals(arrayA[i], arrayB[i])) { + return NO; + } + } + return YES; + } + if ([a isKindOfClass:[NSDictionary class]] && [b isKindOfClass:[NSDictionary class]]) { + NSDictionary *dictA = (NSDictionary *)a; + NSDictionary *dictB = (NSDictionary *)b; + if (dictA.count != dictB.count) { + return NO; + } + for (id keyA in dictA) { + id valueA = dictA[keyA]; + BOOL found = NO; + for (id keyB in dictB) { + if (FLTPigeonDeepEquals(keyA, keyB)) { + id valueB = dictB[keyB]; + if (FLTPigeonDeepEquals(valueA, valueB)) { + found = YES; + break; + } else { + return NO; + } + } + } + if (!found) { + return NO; + } + } + return YES; + } + return [a isEqual:b]; +} + +static NSUInteger __attribute__((unused)) FLTPigeonDeepHash(id _Nullable value) { + if (value == nil || value == (id)[NSNull null]) { + return 0; + } + if ([value isKindOfClass:[NSNumber class]]) { + NSNumber *n = (NSNumber *)value; + double d = n.doubleValue; + if (isnan(d)) { + // Normalize NaN to a consistent hash. + return (NSUInteger)0x7FF8000000000000; + } + if (d == 0.0) { + // Normalize -0.0 to 0.0 so they have the same hash code. + d = 0.0; + } + return @(d).hash; + } + if ([value isKindOfClass:[NSArray class]]) { + NSUInteger result = 1; + for (id item in (NSArray *)value) { + result = result * 31 + FLTPigeonDeepHash(item); + } + return result; + } + if ([value isKindOfClass:[NSDictionary class]]) { + NSUInteger result = 0; + NSDictionary *dict = (NSDictionary *)value; + for (id key in dict) { + result += ((FLTPigeonDeepHash(key) * 31) ^ FLTPigeonDeepHash(dict[key])); + } + return result; + } + return [value hash]; +} static NSArray *wrapResult(id result, FlutterError *error) { if (error) { @@ -115,6 +202,22 @@ + (nullable FLTUnusedClass *)nullableFromList:(NSArray *)list { self.aField ?: [NSNull null], ]; } +- (BOOL)isEqual:(id)object { + if (self == object) { + return YES; + } + if (![object isKindOfClass:[self class]]) { + return NO; + } + FLTUnusedClass *other = (FLTUnusedClass *)object; + return FLTPigeonDeepEquals(self.aField, other.aField); +} + +- (NSUInteger)hash { + NSUInteger result = [self class].hash; + result = result * 31 + FLTPigeonDeepHash(self.aField); + return result; +} @end @implementation FLTAllTypes @@ -246,6 +349,74 @@ + (nullable FLTAllTypes *)nullableFromList:(NSArray *)list { self.mapMap ?: [NSNull null], ]; } +- (BOOL)isEqual:(id)object { + if (self == object) { + return YES; + } + if (![object isKindOfClass:[self class]]) { + return NO; + } + FLTAllTypes *other = (FLTAllTypes *)object; + return self.aBool == other.aBool && self.anInt == other.anInt && self.anInt64 == other.anInt64 && + (self.aDouble == other.aDouble || (isnan(self.aDouble) && isnan(other.aDouble))) && + FLTPigeonDeepEquals(self.aByteArray, other.aByteArray) && + FLTPigeonDeepEquals(self.a4ByteArray, other.a4ByteArray) && + FLTPigeonDeepEquals(self.a8ByteArray, other.a8ByteArray) && + FLTPigeonDeepEquals(self.aFloatArray, other.aFloatArray) && self.anEnum == other.anEnum && + self.anotherEnum == other.anotherEnum && + FLTPigeonDeepEquals(self.aString, other.aString) && + FLTPigeonDeepEquals(self.anObject, other.anObject) && + FLTPigeonDeepEquals(self.list, other.list) && + FLTPigeonDeepEquals(self.stringList, other.stringList) && + FLTPigeonDeepEquals(self.intList, other.intList) && + FLTPigeonDeepEquals(self.doubleList, other.doubleList) && + FLTPigeonDeepEquals(self.boolList, other.boolList) && + FLTPigeonDeepEquals(self.enumList, other.enumList) && + FLTPigeonDeepEquals(self.objectList, other.objectList) && + FLTPigeonDeepEquals(self.listList, other.listList) && + FLTPigeonDeepEquals(self.mapList, other.mapList) && + FLTPigeonDeepEquals(self.map, other.map) && + FLTPigeonDeepEquals(self.stringMap, other.stringMap) && + FLTPigeonDeepEquals(self.intMap, other.intMap) && + FLTPigeonDeepEquals(self.enumMap, other.enumMap) && + FLTPigeonDeepEquals(self.objectMap, other.objectMap) && + FLTPigeonDeepEquals(self.listMap, other.listMap) && + FLTPigeonDeepEquals(self.mapMap, other.mapMap); +} + +- (NSUInteger)hash { + NSUInteger result = [self class].hash; + result = result * 31 + @(self.aBool).hash; + result = result * 31 + @(self.anInt).hash; + result = result * 31 + @(self.anInt64).hash; + result = + result * 31 + (isnan(self.aDouble) ? (NSUInteger)0x7FF8000000000000 : @(self.aDouble).hash); + result = result * 31 + FLTPigeonDeepHash(self.aByteArray); + result = result * 31 + FLTPigeonDeepHash(self.a4ByteArray); + result = result * 31 + FLTPigeonDeepHash(self.a8ByteArray); + result = result * 31 + FLTPigeonDeepHash(self.aFloatArray); + result = result * 31 + @(self.anEnum).hash; + result = result * 31 + @(self.anotherEnum).hash; + result = result * 31 + FLTPigeonDeepHash(self.aString); + result = result * 31 + FLTPigeonDeepHash(self.anObject); + result = result * 31 + FLTPigeonDeepHash(self.list); + result = result * 31 + FLTPigeonDeepHash(self.stringList); + result = result * 31 + FLTPigeonDeepHash(self.intList); + result = result * 31 + FLTPigeonDeepHash(self.doubleList); + result = result * 31 + FLTPigeonDeepHash(self.boolList); + result = result * 31 + FLTPigeonDeepHash(self.enumList); + result = result * 31 + FLTPigeonDeepHash(self.objectList); + result = result * 31 + FLTPigeonDeepHash(self.listList); + result = result * 31 + FLTPigeonDeepHash(self.mapList); + result = result * 31 + FLTPigeonDeepHash(self.map); + result = result * 31 + FLTPigeonDeepHash(self.stringMap); + result = result * 31 + FLTPigeonDeepHash(self.intMap); + result = result * 31 + FLTPigeonDeepHash(self.enumMap); + result = result * 31 + FLTPigeonDeepHash(self.objectMap); + result = result * 31 + FLTPigeonDeepHash(self.listMap); + result = result * 31 + FLTPigeonDeepHash(self.mapMap); + return result; +} @end @implementation FLTAllNullableTypes @@ -389,6 +560,82 @@ + (nullable FLTAllNullableTypes *)nullableFromList:(NSArray *)list { self.recursiveClassMap ?: [NSNull null], ]; } +- (BOOL)isEqual:(id)object { + if (self == object) { + return YES; + } + if (![object isKindOfClass:[self class]]) { + return NO; + } + FLTAllNullableTypes *other = (FLTAllNullableTypes *)object; + return FLTPigeonDeepEquals(self.aNullableBool, other.aNullableBool) && + FLTPigeonDeepEquals(self.aNullableInt, other.aNullableInt) && + FLTPigeonDeepEquals(self.aNullableInt64, other.aNullableInt64) && + FLTPigeonDeepEquals(self.aNullableDouble, other.aNullableDouble) && + FLTPigeonDeepEquals(self.aNullableByteArray, other.aNullableByteArray) && + FLTPigeonDeepEquals(self.aNullable4ByteArray, other.aNullable4ByteArray) && + FLTPigeonDeepEquals(self.aNullable8ByteArray, other.aNullable8ByteArray) && + FLTPigeonDeepEquals(self.aNullableFloatArray, other.aNullableFloatArray) && + FLTPigeonDeepEquals(self.aNullableEnum, other.aNullableEnum) && + FLTPigeonDeepEquals(self.anotherNullableEnum, other.anotherNullableEnum) && + FLTPigeonDeepEquals(self.aNullableString, other.aNullableString) && + FLTPigeonDeepEquals(self.aNullableObject, other.aNullableObject) && + FLTPigeonDeepEquals(self.allNullableTypes, other.allNullableTypes) && + FLTPigeonDeepEquals(self.list, other.list) && + FLTPigeonDeepEquals(self.stringList, other.stringList) && + FLTPigeonDeepEquals(self.intList, other.intList) && + FLTPigeonDeepEquals(self.doubleList, other.doubleList) && + FLTPigeonDeepEquals(self.boolList, other.boolList) && + FLTPigeonDeepEquals(self.enumList, other.enumList) && + FLTPigeonDeepEquals(self.objectList, other.objectList) && + FLTPigeonDeepEquals(self.listList, other.listList) && + FLTPigeonDeepEquals(self.mapList, other.mapList) && + FLTPigeonDeepEquals(self.recursiveClassList, other.recursiveClassList) && + FLTPigeonDeepEquals(self.map, other.map) && + FLTPigeonDeepEquals(self.stringMap, other.stringMap) && + FLTPigeonDeepEquals(self.intMap, other.intMap) && + FLTPigeonDeepEquals(self.enumMap, other.enumMap) && + FLTPigeonDeepEquals(self.objectMap, other.objectMap) && + FLTPigeonDeepEquals(self.listMap, other.listMap) && + FLTPigeonDeepEquals(self.mapMap, other.mapMap) && + FLTPigeonDeepEquals(self.recursiveClassMap, other.recursiveClassMap); +} + +- (NSUInteger)hash { + NSUInteger result = [self class].hash; + result = result * 31 + FLTPigeonDeepHash(self.aNullableBool); + result = result * 31 + FLTPigeonDeepHash(self.aNullableInt); + result = result * 31 + FLTPigeonDeepHash(self.aNullableInt64); + result = result * 31 + FLTPigeonDeepHash(self.aNullableDouble); + result = result * 31 + FLTPigeonDeepHash(self.aNullableByteArray); + result = result * 31 + FLTPigeonDeepHash(self.aNullable4ByteArray); + result = result * 31 + FLTPigeonDeepHash(self.aNullable8ByteArray); + result = result * 31 + FLTPigeonDeepHash(self.aNullableFloatArray); + result = result * 31 + FLTPigeonDeepHash(self.aNullableEnum); + result = result * 31 + FLTPigeonDeepHash(self.anotherNullableEnum); + result = result * 31 + FLTPigeonDeepHash(self.aNullableString); + result = result * 31 + FLTPigeonDeepHash(self.aNullableObject); + result = result * 31 + FLTPigeonDeepHash(self.allNullableTypes); + result = result * 31 + FLTPigeonDeepHash(self.list); + result = result * 31 + FLTPigeonDeepHash(self.stringList); + result = result * 31 + FLTPigeonDeepHash(self.intList); + result = result * 31 + FLTPigeonDeepHash(self.doubleList); + result = result * 31 + FLTPigeonDeepHash(self.boolList); + result = result * 31 + FLTPigeonDeepHash(self.enumList); + result = result * 31 + FLTPigeonDeepHash(self.objectList); + result = result * 31 + FLTPigeonDeepHash(self.listList); + result = result * 31 + FLTPigeonDeepHash(self.mapList); + result = result * 31 + FLTPigeonDeepHash(self.recursiveClassList); + result = result * 31 + FLTPigeonDeepHash(self.map); + result = result * 31 + FLTPigeonDeepHash(self.stringMap); + result = result * 31 + FLTPigeonDeepHash(self.intMap); + result = result * 31 + FLTPigeonDeepHash(self.enumMap); + result = result * 31 + FLTPigeonDeepHash(self.objectMap); + result = result * 31 + FLTPigeonDeepHash(self.listMap); + result = result * 31 + FLTPigeonDeepHash(self.mapMap); + result = result * 31 + FLTPigeonDeepHash(self.recursiveClassMap); + return result; +} @end @implementation FLTAllNullableTypesWithoutRecursion @@ -521,6 +768,76 @@ + (nullable FLTAllNullableTypesWithoutRecursion *)nullableFromList:(NSArray self.mapMap ?: [NSNull null], ]; } +- (BOOL)isEqual:(id)object { + if (self == object) { + return YES; + } + if (![object isKindOfClass:[self class]]) { + return NO; + } + FLTAllNullableTypesWithoutRecursion *other = (FLTAllNullableTypesWithoutRecursion *)object; + return FLTPigeonDeepEquals(self.aNullableBool, other.aNullableBool) && + FLTPigeonDeepEquals(self.aNullableInt, other.aNullableInt) && + FLTPigeonDeepEquals(self.aNullableInt64, other.aNullableInt64) && + FLTPigeonDeepEquals(self.aNullableDouble, other.aNullableDouble) && + FLTPigeonDeepEquals(self.aNullableByteArray, other.aNullableByteArray) && + FLTPigeonDeepEquals(self.aNullable4ByteArray, other.aNullable4ByteArray) && + FLTPigeonDeepEquals(self.aNullable8ByteArray, other.aNullable8ByteArray) && + FLTPigeonDeepEquals(self.aNullableFloatArray, other.aNullableFloatArray) && + FLTPigeonDeepEquals(self.aNullableEnum, other.aNullableEnum) && + FLTPigeonDeepEquals(self.anotherNullableEnum, other.anotherNullableEnum) && + FLTPigeonDeepEquals(self.aNullableString, other.aNullableString) && + FLTPigeonDeepEquals(self.aNullableObject, other.aNullableObject) && + FLTPigeonDeepEquals(self.list, other.list) && + FLTPigeonDeepEquals(self.stringList, other.stringList) && + FLTPigeonDeepEquals(self.intList, other.intList) && + FLTPigeonDeepEquals(self.doubleList, other.doubleList) && + FLTPigeonDeepEquals(self.boolList, other.boolList) && + FLTPigeonDeepEquals(self.enumList, other.enumList) && + FLTPigeonDeepEquals(self.objectList, other.objectList) && + FLTPigeonDeepEquals(self.listList, other.listList) && + FLTPigeonDeepEquals(self.mapList, other.mapList) && + FLTPigeonDeepEquals(self.map, other.map) && + FLTPigeonDeepEquals(self.stringMap, other.stringMap) && + FLTPigeonDeepEquals(self.intMap, other.intMap) && + FLTPigeonDeepEquals(self.enumMap, other.enumMap) && + FLTPigeonDeepEquals(self.objectMap, other.objectMap) && + FLTPigeonDeepEquals(self.listMap, other.listMap) && + FLTPigeonDeepEquals(self.mapMap, other.mapMap); +} + +- (NSUInteger)hash { + NSUInteger result = [self class].hash; + result = result * 31 + FLTPigeonDeepHash(self.aNullableBool); + result = result * 31 + FLTPigeonDeepHash(self.aNullableInt); + result = result * 31 + FLTPigeonDeepHash(self.aNullableInt64); + result = result * 31 + FLTPigeonDeepHash(self.aNullableDouble); + result = result * 31 + FLTPigeonDeepHash(self.aNullableByteArray); + result = result * 31 + FLTPigeonDeepHash(self.aNullable4ByteArray); + result = result * 31 + FLTPigeonDeepHash(self.aNullable8ByteArray); + result = result * 31 + FLTPigeonDeepHash(self.aNullableFloatArray); + result = result * 31 + FLTPigeonDeepHash(self.aNullableEnum); + result = result * 31 + FLTPigeonDeepHash(self.anotherNullableEnum); + result = result * 31 + FLTPigeonDeepHash(self.aNullableString); + result = result * 31 + FLTPigeonDeepHash(self.aNullableObject); + result = result * 31 + FLTPigeonDeepHash(self.list); + result = result * 31 + FLTPigeonDeepHash(self.stringList); + result = result * 31 + FLTPigeonDeepHash(self.intList); + result = result * 31 + FLTPigeonDeepHash(self.doubleList); + result = result * 31 + FLTPigeonDeepHash(self.boolList); + result = result * 31 + FLTPigeonDeepHash(self.enumList); + result = result * 31 + FLTPigeonDeepHash(self.objectList); + result = result * 31 + FLTPigeonDeepHash(self.listList); + result = result * 31 + FLTPigeonDeepHash(self.mapList); + result = result * 31 + FLTPigeonDeepHash(self.map); + result = result * 31 + FLTPigeonDeepHash(self.stringMap); + result = result * 31 + FLTPigeonDeepHash(self.intMap); + result = result * 31 + FLTPigeonDeepHash(self.enumMap); + result = result * 31 + FLTPigeonDeepHash(self.objectMap); + result = result * 31 + FLTPigeonDeepHash(self.listMap); + result = result * 31 + FLTPigeonDeepHash(self.mapMap); + return result; +} @end @implementation FLTAllClassesWrapper @@ -571,6 +888,35 @@ + (nullable FLTAllClassesWrapper *)nullableFromList:(NSArray *)list { self.nullableClassMap ?: [NSNull null], ]; } +- (BOOL)isEqual:(id)object { + if (self == object) { + return YES; + } + if (![object isKindOfClass:[self class]]) { + return NO; + } + FLTAllClassesWrapper *other = (FLTAllClassesWrapper *)object; + return FLTPigeonDeepEquals(self.allNullableTypes, other.allNullableTypes) && + FLTPigeonDeepEquals(self.allNullableTypesWithoutRecursion, + other.allNullableTypesWithoutRecursion) && + FLTPigeonDeepEquals(self.allTypes, other.allTypes) && + FLTPigeonDeepEquals(self.classList, other.classList) && + FLTPigeonDeepEquals(self.nullableClassList, other.nullableClassList) && + FLTPigeonDeepEquals(self.classMap, other.classMap) && + FLTPigeonDeepEquals(self.nullableClassMap, other.nullableClassMap); +} + +- (NSUInteger)hash { + NSUInteger result = [self class].hash; + result = result * 31 + FLTPigeonDeepHash(self.allNullableTypes); + result = result * 31 + FLTPigeonDeepHash(self.allNullableTypesWithoutRecursion); + result = result * 31 + FLTPigeonDeepHash(self.allTypes); + result = result * 31 + FLTPigeonDeepHash(self.classList); + result = result * 31 + FLTPigeonDeepHash(self.nullableClassList); + result = result * 31 + FLTPigeonDeepHash(self.classMap); + result = result * 31 + FLTPigeonDeepHash(self.nullableClassMap); + return result; +} @end @implementation FLTTestMessage @@ -592,6 +938,22 @@ + (nullable FLTTestMessage *)nullableFromList:(NSArray *)list { self.testList ?: [NSNull null], ]; } +- (BOOL)isEqual:(id)object { + if (self == object) { + return YES; + } + if (![object isKindOfClass:[self class]]) { + return NO; + } + FLTTestMessage *other = (FLTTestMessage *)object; + return FLTPigeonDeepEquals(self.testList, other.testList); +} + +- (NSUInteger)hash { + NSUInteger result = [self class].hash; + result = result * 31 + FLTPigeonDeepHash(self.testList); + return result; +} @end @interface FLTCoreTestsPigeonCodecReader : FlutterStandardReader @@ -1478,6 +1840,88 @@ void SetUpFLTHostIntegrationCoreApiWithSuffix(id binaryM [channel setMessageHandler:nil]; } } + /// Returns the result of platform-side equality check. + { + FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] + initWithName:[NSString + stringWithFormat:@"%@%@", + @"dev.flutter.pigeon.pigeon_integration_tests." + @"HostIntegrationCoreApi.areAllNullableTypesEqual", + messageChannelSuffix] + binaryMessenger:binaryMessenger + codec:FLTGetCoreTestsCodec()]; + if (api) { + NSCAssert([api respondsToSelector:@selector(areAllNullableTypesEqualA:b:error:)], + @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " + @"@selector(areAllNullableTypesEqualA:b:error:)", + api); + [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { + NSArray *args = message; + FLTAllNullableTypes *arg_a = GetNullableObjectAtIndex(args, 0); + FLTAllNullableTypes *arg_b = GetNullableObjectAtIndex(args, 1); + FlutterError *error; + NSNumber *output = [api areAllNullableTypesEqualA:arg_a b:arg_b error:&error]; + callback(wrapResult(output, error)); + }]; + } else { + [channel setMessageHandler:nil]; + } + } + /// Returns the platform-side hash code for the given object. + { + FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] + initWithName:[NSString + stringWithFormat:@"%@%@", + @"dev.flutter.pigeon.pigeon_integration_tests." + @"HostIntegrationCoreApi.getAllNullableTypesHash", + messageChannelSuffix] + binaryMessenger:binaryMessenger + codec:FLTGetCoreTestsCodec()]; + if (api) { + NSCAssert([api respondsToSelector:@selector(getAllNullableTypesHashValue:error:)], + @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " + @"@selector(getAllNullableTypesHashValue:error:)", + api); + [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { + NSArray *args = message; + FLTAllNullableTypes *arg_value = GetNullableObjectAtIndex(args, 0); + FlutterError *error; + NSNumber *output = [api getAllNullableTypesHashValue:arg_value error:&error]; + callback(wrapResult(output, error)); + }]; + } else { + [channel setMessageHandler:nil]; + } + } + /// Returns the platform-side hash code for the given object. + { + FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] + initWithName:[NSString + stringWithFormat: + @"%@%@", + @"dev.flutter.pigeon.pigeon_integration_tests." + @"HostIntegrationCoreApi.getAllNullableTypesWithoutRecursionHash", + messageChannelSuffix] + binaryMessenger:binaryMessenger + codec:FLTGetCoreTestsCodec()]; + if (api) { + NSCAssert([api respondsToSelector:@selector(getAllNullableTypesWithoutRecursionHashValue: + error:)], + @"FLTHostIntegrationCoreApi api (%@) doesn't respond to " + @"@selector(getAllNullableTypesWithoutRecursionHashValue:error:)", + api); + [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { + NSArray *args = message; + FLTAllNullableTypesWithoutRecursion *arg_value = GetNullableObjectAtIndex(args, 0); + FlutterError *error; + NSNumber *output = [api getAllNullableTypesWithoutRecursionHashValue:arg_value + error:&error]; + callback(wrapResult(output, error)); + }]; + } else { + [channel setMessageHandler:nil]; + } + } /// Returns the passed object, to test serialization and deserialization. { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/darwin/alternate_language_test_plugin/Sources/alternate_language_test_plugin/include/alternate_language_test_plugin/AlternateLanguageTestPlugin.h b/packages/pigeon/platform_tests/alternate_language_test_plugin/darwin/alternate_language_test_plugin/Sources/alternate_language_test_plugin/include/alternate_language_test_plugin/AlternateLanguageTestPlugin.h index 99490f3d3033..4cc25a15e70d 100644 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/darwin/alternate_language_test_plugin/Sources/alternate_language_test_plugin/include/alternate_language_test_plugin/AlternateLanguageTestPlugin.h +++ b/packages/pigeon/platform_tests/alternate_language_test_plugin/darwin/alternate_language_test_plugin/Sources/alternate_language_test_plugin/include/alternate_language_test_plugin/AlternateLanguageTestPlugin.h @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include + #if TARGET_OS_OSX #import #else diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/darwin/alternate_language_test_plugin/Sources/alternate_language_test_plugin/include/alternate_language_test_plugin/CoreTests.gen.h b/packages/pigeon/platform_tests/alternate_language_test_plugin/darwin/alternate_language_test_plugin/Sources/alternate_language_test_plugin/include/alternate_language_test_plugin/CoreTests.gen.h index 91472bc12e32..2b620a11104a 100644 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/darwin/alternate_language_test_plugin/Sources/alternate_language_test_plugin/include/alternate_language_test_plugin/CoreTests.gen.h +++ b/packages/pigeon/platform_tests/alternate_language_test_plugin/darwin/alternate_language_test_plugin/Sources/alternate_language_test_plugin/include/alternate_language_test_plugin/CoreTests.gen.h @@ -5,7 +5,7 @@ // Autogenerated from Pigeon, do not edit directly. // See also: https://pub.dev/packages/pigeon -#import +@import Foundation; @protocol FlutterBinaryMessenger; @protocol FlutterMessageCodec; @@ -438,6 +438,23 @@ NSObject *FLTGetCoreTestsCodec(void); /// @return `nil` only when `error != nil`. - (nullable NSNumber *)echoRequiredInt:(NSInteger)anInt error:(FlutterError *_Nullable *_Nonnull)error; +/// Returns the result of platform-side equality check. +/// +/// @return `nil` only when `error != nil`. +- (nullable NSNumber *)areAllNullableTypesEqualA:(FLTAllNullableTypes *)a + b:(FLTAllNullableTypes *)b + error:(FlutterError *_Nullable *_Nonnull)error; +/// Returns the platform-side hash code for the given object. +/// +/// @return `nil` only when `error != nil`. +- (nullable NSNumber *)getAllNullableTypesHashValue:(FLTAllNullableTypes *)value + error:(FlutterError *_Nullable *_Nonnull)error; +/// Returns the platform-side hash code for the given object. +/// +/// @return `nil` only when `error != nil`. +- (nullable NSNumber *) + getAllNullableTypesWithoutRecursionHashValue:(FLTAllNullableTypesWithoutRecursion *)value + error:(FlutterError *_Nullable *_Nonnull)error; /// Returns the passed object, to test serialization and deserialization. - (nullable FLTAllNullableTypes *)echoAllNullableTypes:(nullable FLTAllNullableTypes *)everything error:(FlutterError *_Nullable *_Nonnull)error; diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/android/settings.gradle b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/android/settings.gradle index 7be5709da0ca..b83203f03197 100644 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/android/settings.gradle +++ b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/android/settings.gradle @@ -18,10 +18,10 @@ 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.11.0" apply false - id "org.jetbrains.kotlin.android" version "2.2.0" apply false - id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1" + id "dev.flutter.flutter-plugin-loader" version "1.0.0" + id "com.android.application" version "8.11.1" apply false + id "org.jetbrains.kotlin.android" version "2.2.20" apply false + id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1" } include ":app" diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/Flutter/AppFrameworkInfo.plist b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/Flutter/AppFrameworkInfo.plist index 7c5696400627..391a902b2beb 100644 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/Flutter/AppFrameworkInfo.plist +++ b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/Flutter/AppFrameworkInfo.plist @@ -20,7 +20,5 @@ ???? CFBundleVersion 1.0 - MinimumOSVersion - 12.0 diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/Flutter/Debug.xcconfig b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/Flutter/Debug.xcconfig index ec97fc6f3021..592ceee85b89 100644 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/Flutter/Debug.xcconfig +++ b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/Flutter/Debug.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/Flutter/Release.xcconfig b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/Flutter/Release.xcconfig index c4855bfe2000..592ceee85b89 100644 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/Flutter/Release.xcconfig +++ b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/Flutter/Release.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/Podfile b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/Podfile deleted file mode 100644 index 92473fdf5b67..000000000000 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/Podfile +++ /dev/null @@ -1,46 +0,0 @@ -# Uncomment this line to define a global platform for your project -# platform :ios, '12.0' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_ios_podfile_setup - -target 'Runner' do - flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) - - target 'RunnerTests' do - inherit! :search_paths - end -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_ios_build_settings(target) - - target.build_configurations.each do |config| - config.build_settings['GCC_TREAT_WARNINGS_AS_ERRORS'] = 'YES' - end - end -end diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/Runner.xcodeproj/project.pbxproj b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/Runner.xcodeproj/project.pbxproj index 25d767028d45..9ec8521a194a 100644 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/Runner.xcodeproj/project.pbxproj +++ b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/Runner.xcodeproj/project.pbxproj @@ -22,14 +22,12 @@ 33A341B0291EBA9100D34E0F /* PrimitiveTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 33A341A4291EBA9100D34E0F /* PrimitiveTest.m */; }; 33AA1662291EB8B600ECBEEB /* RunnerTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 33AA1661291EB8B600ECBEEB /* RunnerTests.m */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; - 704994D29C27E76CD86C70BB /* libPods-RunnerTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 066DE82583FFABE4243776FB /* libPods-RunnerTests.a */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; 978B8F6F1D3862AE00F588F7 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */; }; 97C146F31CF9000F007C117D /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 97C146F21CF9000F007C117D /* main.m */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; - EB2133B34553CD36D4AE374F /* libPods-Runner.a in Frameworks */ = {isa = PBXBuildFile; fileRef = F87F49FAD891F66A75D95E85 /* libPods-Runner.a */; }; - 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -56,9 +54,6 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 02A70E05D812113F13F5A217 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; - 066DE82583FFABE4243776FB /* libPods-RunnerTests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-RunnerTests.a"; sourceTree = BUILT_PRODUCTS_DIR; }; - 078F27A33C9DB47686C00E70 /* 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 = ""; }; 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; 33A34196291EBA9000D34E0F /* AsyncHandlersTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AsyncHandlersTest.m; sourceTree = ""; }; @@ -79,9 +74,9 @@ 33AA165F291EB8B600ECBEEB /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 33AA1661291EB8B600ECBEEB /* RunnerTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = RunnerTests.m; sourceTree = ""; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; - 561E2904E07F35F0B04F5B46 /* 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 = ""; }; - 6113B2770ED5A74828978171 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; - 62B4FD6165884218124CB1E9 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; + 784666492D4C4C64000A1A5F /* FlutterFramework */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterFramework; path = Flutter/ephemeral/Packages/.packages/FlutterFramework; sourceTree = ""; }; + 78DABEA22ED26510000E7860 /* alternate_language_test_plugin */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = alternate_language_test_plugin; path = ../../darwin/alternate_language_test_plugin; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; 7AFFD8ED1D35381100E5BB4D /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; 7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; @@ -93,8 +88,6 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - C47E6C31D80944C08FAD78CC /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; - F87F49FAD891F66A75D95E85 /* libPods-Runner.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-Runner.a"; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -102,7 +95,6 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 704994D29C27E76CD86C70BB /* libPods-RunnerTests.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -111,22 +103,12 @@ buildActionMask = 2147483647; files = ( 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, - EB2133B34553CD36D4AE374F /* libPods-Runner.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 00DD93B7FA51A2141F86E724 /* Frameworks */ = { - isa = PBXGroup; - children = ( - F87F49FAD891F66A75D95E85 /* libPods-Runner.a */, - 066DE82583FFABE4243776FB /* libPods-RunnerTests.a */, - ); - name = Frameworks; - sourceTree = ""; - }; 33AA1660291EB8B600ECBEEB /* RunnerTests */ = { isa = PBXGroup; children = ( @@ -153,12 +135,6 @@ 7ADF8AD6006543AA8B1E20C1 /* Pods */ = { isa = PBXGroup; children = ( - 02A70E05D812113F13F5A217 /* Pods-Runner.debug.xcconfig */, - 6113B2770ED5A74828978171 /* Pods-Runner.release.xcconfig */, - 62B4FD6165884218124CB1E9 /* Pods-Runner.profile.xcconfig */, - 078F27A33C9DB47686C00E70 /* Pods-RunnerTests.debug.xcconfig */, - 561E2904E07F35F0B04F5B46 /* Pods-RunnerTests.release.xcconfig */, - C47E6C31D80944C08FAD78CC /* Pods-RunnerTests.profile.xcconfig */, ); path = Pods; sourceTree = ""; @@ -166,6 +142,9 @@ 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( + 78DABEA22ED26510000E7860 /* alternate_language_test_plugin */, + 784666492D4C4C64000A1A5F /* FlutterFramework */, + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, 9740EEB21CF90195004384FC /* Debug.xcconfig */, 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, @@ -182,7 +161,6 @@ 33AA1660291EB8B600ECBEEB /* RunnerTests */, 97C146EF1CF9000F007C117D /* Products */, 7ADF8AD6006543AA8B1E20C1 /* Pods */, - 00DD93B7FA51A2141F86E724 /* Frameworks */, ); sourceTree = ""; }; @@ -226,7 +204,6 @@ isa = PBXNativeTarget; buildConfigurationList = 33AA1668291EB8B600ECBEEB /* Build configuration list for PBXNativeTarget "RunnerTests" */; buildPhases = ( - 81D50B6E064849557BD0D347 /* [CP] Check Pods Manifest.lock */, 33AA165B291EB8B600ECBEEB /* Sources */, 33AA165C291EB8B600ECBEEB /* Frameworks */, 33AA165D291EB8B600ECBEEB /* Resources */, @@ -242,13 +219,9 @@ productType = "com.apple.product-type.bundle.unit-test"; }; 97C146ED1CF9000F007C117D /* Runner */ = { - packageProductDependencies = ( - 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, - ); isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - F4137F1E25211755D7761631 /* [CP] Check Pods Manifest.lock */, 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, @@ -261,6 +234,9 @@ dependencies = ( ); name = Runner; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); productName = Runner; productReference = 97C146EE1CF9000F007C117D /* Runner.app */; productType = "com.apple.product-type.application"; @@ -269,9 +245,6 @@ /* Begin PBXProject section */ 97C146E61CF9000F007C117D /* Project object */ = { - packageReferences = ( - 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */, - ); isa = PBXProject; attributes = { LastUpgradeCheck = 1510; @@ -295,6 +268,9 @@ Base, ); mainGroup = 97C146E51CF9000F007C117D; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */, + ); productRefGroup = 97C146EF1CF9000F007C117D /* Products */; projectDirPath = ""; projectRoot = ""; @@ -343,28 +319,6 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; }; - 81D50B6E064849557BD0D347 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; 9740EEB61CF901F6004384FC /* Run Script */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; @@ -380,28 +334,6 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; }; - F4137F1E25211755D7761631 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -506,7 +438,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -535,7 +467,6 @@ }; 33AA1665291EB8B600ECBEEB /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 078F27A33C9DB47686C00E70 /* Pods-RunnerTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; @@ -550,7 +481,6 @@ }; 33AA1666291EB8B600ECBEEB /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 561E2904E07F35F0B04F5B46 /* Pods-RunnerTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; @@ -565,7 +495,6 @@ }; 33AA1667291EB8B600ECBEEB /* Profile */ = { isa = XCBuildConfiguration; - baseConfigurationReference = C47E6C31D80944C08FAD78CC /* Pods-RunnerTests.profile.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; @@ -625,7 +554,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -674,7 +603,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -753,12 +682,14 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + /* Begin XCLocalSwiftPackageReference section */ - 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage" */ = { + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */ = { isa = XCLocalSwiftPackageReference; relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; }; /* End XCLocalSwiftPackageReference section */ + /* Begin XCSwiftPackageProductDependency section */ 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { isa = XCSwiftPackageProductDependency; diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/AllDatatypesTest.m b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/AllDatatypesTest.m index ddef818e0c5a..4e5b5b196f5a 100644 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/AllDatatypesTest.m +++ b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/AllDatatypesTest.m @@ -114,8 +114,125 @@ - (void)testAllEquals { [self waitForExpectations:@[ expectation ] timeout:1.0]; } -- (void)unusedClassesExist { - XCTAssert([[FLTUnusedClass alloc] init] != nil); +- (void)testEquality { + FLTAllNullableTypes *everything1 = [[FLTAllNullableTypes alloc] init]; + everything1.aNullableBool = @NO; + everything1.aNullableInt = @(1); + everything1.aNullableString = @"123"; + + FLTAllNullableTypes *everything2 = [[FLTAllNullableTypes alloc] init]; + everything2.aNullableBool = @NO; + everything2.aNullableInt = @(1); + everything2.aNullableString = @"123"; + + FLTAllNullableTypes *everything3 = [[FLTAllNullableTypes alloc] init]; + everything3.aNullableBool = @YES; + + XCTAssertEqualObjects(everything1, everything2); + XCTAssertNotEqualObjects(everything1, everything3); + XCTAssertEqual(everything1.hash, everything2.hash); +} + +- (void)testNaNEquality { + FLTAllNullableTypes *everything1 = [[FLTAllNullableTypes alloc] init]; + everything1.aNullableDouble = @(NAN); + + FLTAllNullableTypes *everything2 = [[FLTAllNullableTypes alloc] init]; + everything2.aNullableDouble = @(NAN); + + XCTAssertEqualObjects(everything1, everything2); + XCTAssertEqual(everything1.hash, everything2.hash); +} + +- (void)testCrossTypeEquality { + FLTAllNullableTypes *a = [[FLTAllNullableTypes alloc] init]; + a.aNullableInt = @(1); + + FLTAllNullableTypesWithoutRecursion *b = [[FLTAllNullableTypesWithoutRecursion alloc] init]; + b.aNullableInt = @(1); + + XCTAssertNotEqualObjects(a, b); + XCTAssertNotEqualObjects(b, a); +} + +- (void)testZeroEquality { + FLTAllNullableTypes *a = [[FLTAllNullableTypes alloc] init]; + a.aNullableDouble = @(0.0); + + FLTAllNullableTypes *b = [[FLTAllNullableTypes alloc] init]; + b.aNullableDouble = @(-0.0); + + XCTAssertEqualObjects(a, b); + XCTAssertEqual(a.hash, b.hash); +} + +- (void)testNestedNaNEquality { + FLTAllNullableTypes *a = [[FLTAllNullableTypes alloc] init]; + a.aNullableDouble = @(nan("")); + a.doubleList = @[ @(nan("")) ]; + + FLTAllNullableTypes *b = [[FLTAllNullableTypes alloc] init]; + b.aNullableDouble = @(nan("")); + b.doubleList = @[ @(nan("")) ]; + + // If this fails, Objective-C needs a deepEquals helper too. + XCTAssertEqualObjects(a, b); + XCTAssertEqual(a.hash, b.hash); +} + +- (void)testNestedZeroListEquality { + FLTAllNullableTypes *a = [[FLTAllNullableTypes alloc] init]; + a.doubleList = @[ @(0.0) ]; + + FLTAllNullableTypes *b = [[FLTAllNullableTypes alloc] init]; + b.doubleList = @[ @(-0.0) ]; + + XCTAssertEqualObjects(a, b); + XCTAssertEqual(a.hash, b.hash); +} + +- (void)testZeroMapKeyEquality { + FLTAllNullableTypes *a = [[FLTAllNullableTypes alloc] init]; + a.map = @{@(0.0) : @"a"}; + + FLTAllNullableTypes *b = [[FLTAllNullableTypes alloc] init]; + b.map = @{@(-0.0) : @"a"}; + + XCTAssertEqualObjects(a, b); + XCTAssertEqual(a.hash, b.hash); +} + +- (void)testZeroMapValueEquality { + FLTAllNullableTypes *a = [[FLTAllNullableTypes alloc] init]; + a.map = @{@"a" : @(0.0)}; + + FLTAllNullableTypes *b = [[FLTAllNullableTypes alloc] init]; + b.map = @{@"a" : @(-0.0)}; + + XCTAssertEqualObjects(a, b); + XCTAssertEqual(a.hash, b.hash); +} + +- (void)testNSNullListEquality { + FLTAllNullableTypes *a = [[FLTAllNullableTypes alloc] init]; + a.list = @[ [NSNull null] ]; + + FLTAllNullableTypes *b = [[FLTAllNullableTypes alloc] init]; + b.list = @[ [NSNull null] ]; + + XCTAssertEqualObjects(a, b); + XCTAssertEqual(a.hash, b.hash); +} + +- (void)testNSNullPropertyEquality { + FLTAllNullableTypes *a = [[FLTAllNullableTypes alloc] init]; + a.aNullableObject = [NSNull null]; + + FLTAllNullableTypes *b = [[FLTAllNullableTypes alloc] init]; + b.aNullableObject = nil; + + XCTAssertEqualObjects(a, b); + XCTAssertEqual(a.hash, b.hash); } @end diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/NonNullFieldsTest.m b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/NonNullFieldsTest.m index 573bb994f91c..cd0369996a01 100644 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/NonNullFieldsTest.m +++ b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/NonNullFieldsTest.m @@ -22,4 +22,14 @@ - (void)testMake { XCTAssertEqualObjects(@"hello", request.query); } +- (void)testEquality { + NonNullFieldSearchRequest *request1 = [NonNullFieldSearchRequest makeWithQuery:@"hello"]; + NonNullFieldSearchRequest *request2 = [NonNullFieldSearchRequest makeWithQuery:@"hello"]; + NonNullFieldSearchRequest *request3 = [NonNullFieldSearchRequest makeWithQuery:@"world"]; + + XCTAssertEqualObjects(request1, request2); + XCTAssertNotEqualObjects(request1, request3); + XCTAssertEqual(request1.hash, request2.hash); +} + @end diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/macos/Flutter/Flutter-Debug.xcconfig b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/macos/Flutter/Flutter-Debug.xcconfig index 4b81f9b2d200..c2efd0b608ba 100644 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/macos/Flutter/Flutter-Debug.xcconfig +++ b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/macos/Flutter/Flutter-Debug.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/macos/Flutter/Flutter-Release.xcconfig b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/macos/Flutter/Flutter-Release.xcconfig index 5caa9d1579e4..c2efd0b608ba 100644 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/macos/Flutter/Flutter-Release.xcconfig +++ b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/macos/Flutter/Flutter-Release.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/macos/Podfile b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/macos/Podfile deleted file mode 100644 index 29c8eb3294cb..000000000000 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/macos/Podfile +++ /dev/null @@ -1,42 +0,0 @@ -platform :osx, '10.14' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\"" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_macos_podfile_setup - -target 'Runner' do - use_frameworks! - - flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__)) - target 'RunnerTests' do - inherit! :search_paths - end -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_macos_build_settings(target) - end -end diff --git a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/macos/Runner.xcodeproj/project.pbxproj b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/macos/Runner.xcodeproj/project.pbxproj index 4a79415c598a..edd0d84d497d 100644 --- a/packages/pigeon/platform_tests/alternate_language_test_plugin/example/macos/Runner.xcodeproj/project.pbxproj +++ b/packages/pigeon/platform_tests/alternate_language_test_plugin/example/macos/Runner.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 54; + objectVersion = 60; objects = { /* Begin PBXAggregateTarget section */ @@ -21,8 +21,6 @@ /* End PBXAggregateTarget section */ /* Begin PBXBuildFile section */ - 0D7AA04F867B850C58216739 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CF8BB4081B46FB8120727E26 /* Pods_Runner.framework */; }; - 175F934430D0CAB10EA34579 /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 682C75DDB5CD4EB8D08360C5 /* Pods_RunnerTests.framework */; }; 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; @@ -79,16 +77,11 @@ 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; - 5EE3C0398E9AC1B8C35AE87D /* 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 = ""; }; - 682C75DDB5CD4EB8D08360C5 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 7671709AF50BB50842EA8B2B /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; + 784666492D4C4C64000A1A5F /* FlutterFramework */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterFramework; path = ephemeral/Packages/.packages/FlutterFramework; sourceTree = ""; }; + 78DABEA22ED26510000E7860 /* alternate_language_test_plugin */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = alternate_language_test_plugin; path = ../../../darwin/alternate_language_test_plugin; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; - 7B755EC1B70C6DE5D62ECE5B /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; - CF8BB4081B46FB8120727E26 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - D2B4CC0DCD712A73FC4805C2 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; - DAFBE1E70BF8E058B1A22B17 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; - EC8E2B4AD109E092CD6B9C41 /* 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 = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -96,7 +89,6 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 175F934430D0CAB10EA34579 /* Pods_RunnerTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -105,7 +97,6 @@ buildActionMask = 2147483647; files = ( 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, - 0D7AA04F867B850C58216739 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -115,14 +106,7 @@ 1EC62CB395CE8E1EC824E078 /* Pods */ = { isa = PBXGroup; children = ( - D2B4CC0DCD712A73FC4805C2 /* Pods-Runner.debug.xcconfig */, - 7671709AF50BB50842EA8B2B /* Pods-Runner.release.xcconfig */, - DAFBE1E70BF8E058B1A22B17 /* Pods-Runner.profile.xcconfig */, - 5EE3C0398E9AC1B8C35AE87D /* Pods-RunnerTests.debug.xcconfig */, - EC8E2B4AD109E092CD6B9C41 /* Pods-RunnerTests.release.xcconfig */, - 7B755EC1B70C6DE5D62ECE5B /* Pods-RunnerTests.profile.xcconfig */, - ); - name = Pods; + ); path = Pods; sourceTree = ""; }; @@ -152,7 +136,6 @@ 33CEB47122A05771004F2AC0 /* Flutter */, 331C80D6294CF71000263BE5 /* RunnerTests */, 33CC10EE2044A3C60003C045 /* Products */, - D73912EC22F37F3D000D13A0 /* Frameworks */, 1EC62CB395CE8E1EC824E078 /* Pods */, ); sourceTree = ""; @@ -180,6 +163,9 @@ 33CEB47122A05771004F2AC0 /* Flutter */ = { isa = PBXGroup; children = ( + 78DABEA22ED26510000E7860 /* alternate_language_test_plugin */, + 784666492D4C4C64000A1A5F /* FlutterFramework */, + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, @@ -201,15 +187,6 @@ path = Runner; sourceTree = ""; }; - D73912EC22F37F3D000D13A0 /* Frameworks */ = { - isa = PBXGroup; - children = ( - CF8BB4081B46FB8120727E26 /* Pods_Runner.framework */, - 682C75DDB5CD4EB8D08360C5 /* Pods_RunnerTests.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -217,7 +194,6 @@ isa = PBXNativeTarget; buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; buildPhases = ( - D1118CDCC1A944FBF64A562E /* [CP] Check Pods Manifest.lock */, 331C80D1294CF70F00263BE5 /* Sources */, 331C80D2294CF70F00263BE5 /* Frameworks */, 331C80D3294CF70F00263BE5 /* Resources */, @@ -236,7 +212,6 @@ isa = PBXNativeTarget; buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - 6922B9504013AEB23F67302D /* [CP] Check Pods Manifest.lock */, 33CC10E92044A3C60003C045 /* Sources */, 33CC10EA2044A3C60003C045 /* Frameworks */, 33CC10EB2044A3C60003C045 /* Resources */, @@ -367,50 +342,6 @@ shellPath = /bin/sh; shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; }; - 6922B9504013AEB23F67302D /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - D1118CDCC1A944FBF64A562E /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -462,7 +393,6 @@ /* Begin XCBuildConfiguration section */ 331C80DB294CF71000263BE5 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 5EE3C0398E9AC1B8C35AE87D /* Pods-RunnerTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; @@ -477,7 +407,6 @@ }; 331C80DC294CF71000263BE5 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = EC8E2B4AD109E092CD6B9C41 /* Pods-RunnerTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; @@ -492,7 +421,6 @@ }; 331C80DD294CF71000263BE5 /* Profile */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 7B755EC1B70C6DE5D62ECE5B /* Pods-RunnerTests.profile.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; @@ -543,7 +471,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; + MACOSX_DEPLOYMENT_TARGET = 10.15; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; @@ -622,7 +550,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; + MACOSX_DEPLOYMENT_TARGET = 10.15; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = macosx; @@ -669,7 +597,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; + MACOSX_DEPLOYMENT_TARGET = 10.15; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/integration_tests.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/integration_tests.dart index 416a524673c1..9ed43123a701 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/integration_tests.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/integration_tests.dart @@ -47,7 +47,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { group('Host sync API tests', () { testWidgets('basic void->void call works', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); expect(api.noop(), completes); }); @@ -55,7 +55,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('all datatypes serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final AllTypes echoObject = await api.echoAllTypes(genericAllTypes); expect(echoObject, genericAllTypes); @@ -64,7 +64,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('all nullable datatypes serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final AllNullableTypes? echoObject = await api.echoAllNullableTypes( recursiveAllNullableTypes, @@ -76,9 +76,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('all null datatypes serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - final AllNullableTypes allTypesNull = AllNullableTypes(); + final allTypesNull = AllNullableTypes(); final AllNullableTypes? echoNullFilledClass = await api .echoAllNullableTypes(allTypesNull); @@ -88,11 +88,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'Classes with list of null serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - final AllNullableTypes listTypes = AllNullableTypes( - list: ['String', null], - ); + final listTypes = AllNullableTypes(list: ['String', null]); final AllNullableTypes? echoNullFilledClass = await api .echoAllNullableTypes(listTypes); @@ -104,9 +102,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'Classes with map of null serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - final AllNullableTypes listTypes = AllNullableTypes( + final listTypes = AllNullableTypes( map: {'String': 'string', 'null': null}, ); @@ -120,7 +118,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'all nullable datatypes without recursion serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final AllNullableTypesWithoutRecursion? echoObject = await api .echoAllNullableTypesWithoutRecursion( @@ -134,10 +132,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'all null datatypes without recursion serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - final AllNullableTypesWithoutRecursion allTypesNull = - AllNullableTypesWithoutRecursion(); + final allTypesNull = AllNullableTypesWithoutRecursion(); final AllNullableTypesWithoutRecursion? echoNullFilledClass = await api .echoAllNullableTypesWithoutRecursion(allTypesNull); @@ -148,10 +145,11 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'Classes without recursion with list of null serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - final AllNullableTypesWithoutRecursion listTypes = - AllNullableTypesWithoutRecursion(list: ['String', null]); + final listTypes = AllNullableTypesWithoutRecursion( + list: ['String', null], + ); final AllNullableTypesWithoutRecursion? echoNullFilledClass = await api .echoAllNullableTypesWithoutRecursion(listTypes); @@ -163,12 +161,11 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'Classes without recursion with map of null serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - final AllNullableTypesWithoutRecursion listTypes = - AllNullableTypesWithoutRecursion( - map: {'String': 'string', 'null': null}, - ); + final listTypes = AllNullableTypesWithoutRecursion( + map: {'String': 'string', 'null': null}, + ); final AllNullableTypesWithoutRecursion? echoNullFilledClass = await api .echoAllNullableTypesWithoutRecursion(listTypes); @@ -178,7 +175,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { ); testWidgets('errors are returned correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); expect(() async { await api.throwError(); @@ -188,7 +185,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('errors are returned from void methods correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); expect(() async { await api.throwErrorFromVoid(); @@ -198,7 +195,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('flutter errors are returned correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); expect( () => api.throwFlutterError(), @@ -213,7 +210,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }); testWidgets('nested objects can be sent correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final AllClassesWrapper classWrapper = classWrapperMaker(); final String? receivedString = await api.extractNestedNullableString( classWrapper, @@ -224,9 +221,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nested objects can be received correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - const String sentString = 'Some string'; + const sentString = 'Some string'; final AllClassesWrapper receivedObject = await api .createNestedNullableString(sentString); expect(receivedObject.allNullableTypes.aNullableString, sentString); @@ -235,7 +232,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nested classes can serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final AllClassesWrapper classWrapper = classWrapperMaker(); final AllClassesWrapper receivedClassWrapper = await api.echoClassWrapper( @@ -247,7 +244,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nested null classes can serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final AllClassesWrapper classWrapper = classWrapperMaker(); classWrapper.allTypes = null; @@ -261,9 +258,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'Arguments of multiple types serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - const String aNullableString = 'this is a String'; - const bool aNullableBool = false; + final api = HostIntegrationCoreApi(); + const aNullableString = 'this is a String'; + const aNullableBool = false; const int aNullableInt = regularInt; final AllNullableTypes echoObject = await api.sendMultipleNullableTypes( @@ -280,7 +277,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'Arguments of multiple null types serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final AllNullableTypes echoNullFilledClass = await api .sendMultipleNullableTypes(null, null, null); @@ -293,9 +290,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'Arguments of multiple types serialize and deserialize correctly (WithoutRecursion)', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - const String aNullableString = 'this is a String'; - const bool aNullableBool = false; + final api = HostIntegrationCoreApi(); + const aNullableString = 'this is a String'; + const aNullableBool = false; const int aNullableInt = regularInt; final AllNullableTypesWithoutRecursion echoObject = await api @@ -313,7 +310,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'Arguments of multiple null types serialize and deserialize correctly (WithoutRecursion)', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final AllNullableTypesWithoutRecursion echoNullFilledClass = await api .sendMultipleNullableTypesWithoutRecursion(null, null, null); @@ -326,7 +323,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('Int serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const int sentInt = regularInt; final int receivedInt = await api.echoInt(sentInt); expect(receivedInt, sentInt); @@ -335,7 +332,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('Int64 serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const int sentInt = biggerThanBigInt; final int receivedInt = await api.echoInt(sentInt); @@ -345,9 +342,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('Doubles serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - const double sentDouble = 2.0694; + const sentDouble = 2.0694; final double receivedDouble = await api.echoDouble(sentDouble); expect(receivedDouble, sentDouble); }); @@ -355,9 +352,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('booleans serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - for (final bool sentBool in [true, false]) { + for (final sentBool in [true, false]) { final bool receivedBool = await api.echoBool(sentBool); expect(receivedBool, sentBool); } @@ -366,8 +363,8 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('strings serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - const String sentString = 'default'; + final api = HostIntegrationCoreApi(); + const sentString = 'default'; final String receivedString = await api.echoString(sentString); expect(receivedString, sentString); }); @@ -375,20 +372,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('Uint8List serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List data = [ - 102, - 111, - 114, - 116, - 121, - 45, - 116, - 119, - 111, - 0, - ]; - final Uint8List sentUint8List = Uint8List.fromList(data); + final api = HostIntegrationCoreApi(); + final data = [102, 111, 114, 116, 121, 45, 116, 119, 111, 0]; + final sentUint8List = Uint8List.fromList(data); final Uint8List receivedUint8List = await api.echoUint8List( sentUint8List, ); @@ -398,7 +384,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('generic Objects serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const Object sentString = "I'm a computer"; final Object receivedString = await api.echoObject(sentString); expect(receivedString, sentString); @@ -412,7 +398,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List echoObject = await api.echoList(list); expect(listEquals(echoObject, list), true); @@ -421,7 +407,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('enum lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List echoObject = await api.echoEnumList(enumList); expect(listEquals(echoObject, enumList), true); @@ -430,7 +416,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('class lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List echoObject = await api.echoClassList( allNullableTypesList, @@ -443,7 +429,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('NonNull enum lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List echoObject = await api.echoNonNullEnumList( nonNullEnumList, @@ -454,7 +440,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('NonNull class lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List echoObject = await api.echoNonNullClassList( nonNullAllNullableTypesList, @@ -467,7 +453,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api.echoMap(map); expect(mapEquals(echoObject, map), true); }); @@ -475,7 +461,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('string maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api.echoStringMap( stringMap, ); @@ -485,7 +471,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('int maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api.echoIntMap(intMap); expect(mapEquals(echoObject, intMap), true); }); @@ -493,7 +479,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('enum maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api.echoEnumMap(enumMap); expect(mapEquals(echoObject, enumMap), true); }); @@ -501,7 +487,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('class maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api.echoClassMap( allNullableTypesMap, ); @@ -514,7 +500,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('NonNull string maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api.echoNonNullStringMap( nonNullStringMap, ); @@ -524,7 +510,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('NonNull int maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api.echoNonNullIntMap( nonNullIntMap, ); @@ -534,7 +520,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('NonNull enum maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api.echoNonNullEnumMap( nonNullEnumMap, ); @@ -544,7 +530,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('NonNull class maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api .echoNonNullClassMap(nonNullAllNullableTypesMap); for (final MapEntry entry in echoObject.entries) { @@ -555,7 +541,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('enums serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.two; final AnEnum receivedEnum = await api.echoEnum(sentEnum); @@ -565,7 +551,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('enums serialize and deserialize correctly (again)', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnotherEnum sentEnum = AnotherEnum.justInCase; final AnotherEnum receivedEnum = await api.echoAnotherEnum(sentEnum); @@ -575,7 +561,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('multi word enums serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.fortyTwo; final AnEnum receivedEnum = await api.echoEnum(sentEnum); @@ -583,7 +569,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }); testWidgets('required named parameter', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); // This number corresponds with the default value of this method. const int sentInt = regularInt; final int receivedInt = await api.echoRequiredInt(anInt: sentInt); @@ -591,18 +577,18 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }); testWidgets('optional default parameter no arg', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); // This number corresponds with the default value of this method. - const double sentDouble = 3.14; + const sentDouble = 3.14; final double receivedDouble = await api.echoOptionalDefaultDouble(); expect(receivedDouble, sentDouble); }); testWidgets('optional default parameter with arg', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - const double sentDouble = 3.15; + const sentDouble = 3.15; final double receivedDouble = await api.echoOptionalDefaultDouble( sentDouble, ); @@ -610,17 +596,17 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }); testWidgets('named default parameter no arg', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); // This string corresponds with the default value of this method. - const String sentString = 'default'; + const sentString = 'default'; final String receivedString = await api.echoNamedDefaultString(); expect(receivedString, sentString); }); testWidgets('named default parameter with arg', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); // This string corresponds with the default value of this method. - const String sentString = 'notDefault'; + const sentString = 'notDefault'; final String receivedString = await api.echoNamedDefaultString( aString: sentString, ); @@ -630,7 +616,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('Nullable Int serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const int sentInt = regularInt; final int? receivedInt = await api.echoNullableInt(sentInt); @@ -640,7 +626,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('Nullable Int64 serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const int sentInt = biggerThanBigInt; final int? receivedInt = await api.echoNullableInt(sentInt); @@ -650,7 +636,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('Null Ints serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final int? receivedNullInt = await api.echoNullableInt(null); expect(receivedNullInt, null); @@ -659,9 +645,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('Nullable Doubles serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - const double sentDouble = 2.0694; + const sentDouble = 2.0694; final double? receivedDouble = await api.echoNullableDouble(sentDouble); expect(receivedDouble, sentDouble); }); @@ -669,7 +655,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('Null Doubles serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final double? receivedNullDouble = await api.echoNullableDouble(null); expect(receivedNullDouble, null); @@ -678,9 +664,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('Nullable booleans serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - for (final bool? sentBool in [true, false]) { + for (final sentBool in [true, false]) { final bool? receivedBool = await api.echoNullableBool(sentBool); expect(receivedBool, sentBool); } @@ -689,7 +675,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('Null booleans serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const bool? sentBool = null; final bool? receivedBool = await api.echoNullableBool(sentBool); @@ -699,8 +685,8 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('Nullable strings serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - const String sentString = "I'm a computer"; + final api = HostIntegrationCoreApi(); + const sentString = "I'm a computer"; final String? receivedString = await api.echoNullableString(sentString); expect(receivedString, sentString); }); @@ -708,7 +694,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('Null strings serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final String? receivedNullString = await api.echoNullableString(null); expect(receivedNullString, null); @@ -717,20 +703,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('Nullable Uint8List serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List data = [ - 102, - 111, - 114, - 116, - 121, - 45, - 116, - 119, - 111, - 0, - ]; - final Uint8List sentUint8List = Uint8List.fromList(data); + final api = HostIntegrationCoreApi(); + final data = [102, 111, 114, 116, 121, 45, 116, 119, 111, 0]; + final sentUint8List = Uint8List.fromList(data); final Uint8List? receivedUint8List = await api.echoNullableUint8List( sentUint8List, ); @@ -740,7 +715,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('Null Uint8List serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Uint8List? receivedNullUint8List = await api.echoNullableUint8List( null, @@ -751,7 +726,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'generic nullable Objects serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const Object sentString = "I'm a computer"; final Object? receivedString = await api.echoNullableObject(sentString); expect(receivedString, sentString); @@ -766,7 +741,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('Null generic Objects serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Object? receivedNullObject = await api.echoNullableObject(null); expect(receivedNullObject, null); @@ -775,7 +750,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List? echoObject = await api.echoNullableList(list); expect(listEquals(echoObject, list), true); @@ -784,7 +759,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable enum lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List? echoObject = await api.echoNullableEnumList( enumList, @@ -795,7 +770,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List? echoObject = await api .echoNullableClassList(allNullableTypesList); @@ -807,7 +782,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'nullable NonNull enum lists serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List? echoObject = await api.echoNullableNonNullEnumList( nonNullEnumList, @@ -819,7 +794,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable NonNull lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List? echoObject = await api .echoNullableClassList(nonNullAllNullableTypesList); @@ -831,7 +806,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api.echoNullableMap(map); expect(mapEquals(echoObject, map), true); }); @@ -839,7 +814,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable string maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api.echoNullableStringMap( stringMap, ); @@ -849,7 +824,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable int maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api.echoNullableIntMap(intMap); expect(mapEquals(echoObject, intMap), true); }); @@ -857,7 +832,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable enum maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api.echoNullableEnumMap( enumMap, ); @@ -867,7 +842,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable class maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api .echoNullableClassMap(allNullableTypesMap); for (final MapEntry entry @@ -879,7 +854,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'nullable NonNull string maps serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api .echoNullableNonNullStringMap(nonNullStringMap); expect(mapEquals(echoObject, nonNullStringMap), true); @@ -889,7 +864,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'nullable NonNull int maps serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api.echoNullableNonNullIntMap( nonNullIntMap, ); @@ -900,7 +875,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'nullable NonNull enum maps serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api .echoNullableNonNullEnumMap(nonNullEnumMap); expect(mapEquals(echoObject, nonNullEnumMap), true); @@ -910,7 +885,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'nullable NonNull class maps serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api .echoNullableNonNullClassMap(nonNullAllNullableTypesMap); for (final MapEntry entry @@ -923,7 +898,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable enums serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.three; final AnEnum? echoEnum = await api.echoNullableEnum(sentEnum); @@ -933,7 +908,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable enums serialize and deserialize correctly (again)', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnotherEnum sentEnum = AnotherEnum.justInCase; final AnotherEnum? echoEnum = await api.echoAnotherNullableEnum(sentEnum); @@ -943,7 +918,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'multi word nullable enums serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.fourHundredTwentyTwo; final AnEnum? echoEnum = await api.echoNullableEnum(sentEnum); @@ -954,7 +929,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List? echoObject = await api.echoNullableList(null); expect(listEquals(echoObject, null), true); @@ -963,7 +938,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api.echoNullableMap(null); expect(mapEquals(echoObject, null), true); @@ -972,7 +947,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null string maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api.echoNullableStringMap( null, @@ -983,7 +958,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null int maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api.echoNullableIntMap(null); expect(mapEquals(echoObject, null), true); @@ -992,7 +967,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null enums serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnEnum? sentEnum = null; final AnEnum? echoEnum = await api.echoNullableEnum(sentEnum); @@ -1002,7 +977,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null enums serialize and deserialize correctly (again)', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnotherEnum? sentEnum = null; final AnotherEnum? echoEnum = await api.echoAnotherNullableEnum(sentEnum); @@ -1012,7 +987,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null classes serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final AllNullableTypes? echoObject = await api.echoAllNullableTypes(null); @@ -1020,7 +995,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }); testWidgets('optional nullable parameter', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const int sentInt = regularInt; final int? receivedInt = await api.echoOptionalNullableInt(sentInt); @@ -1028,15 +1003,15 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }); testWidgets('Null optional nullable parameter', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final int? receivedNullInt = await api.echoOptionalNullableInt(); expect(receivedNullInt, null); }); testWidgets('named nullable parameter', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - const String sentString = "I'm a computer"; + final api = HostIntegrationCoreApi(); + const sentString = "I'm a computer"; final String? receivedString = await api.echoNamedNullableString( aNullableString: sentString, ); @@ -1044,16 +1019,181 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }); testWidgets('Null named nullable parameter', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final String? receivedNullString = await api.echoNamedNullableString(); expect(receivedNullString, null); }); + + testWidgets('Signed zero equality', (WidgetTester _) async { + final api = HostIntegrationCoreApi(); + + final a = AllNullableTypes(aNullableDouble: 0.0); + final b = AllNullableTypes(aNullableDouble: -0.0); + + expect(await api.areAllNullableTypesEqual(a, b), isTrue); + }); + + testWidgets('Signed zero hashing', (WidgetTester _) async { + final api = HostIntegrationCoreApi(); + + final a = AllNullableTypes(aNullableDouble: 0.0); + final b = AllNullableTypes(aNullableDouble: -0.0); + + final int hashA = await api.getAllNullableTypesHash(a); + final int hashB = await api.getAllNullableTypesHash(b); + expect( + hashA, + hashB, + reason: 'Hash codes for 0.0 and -0.0 should be equal', + ); + }); + + testWidgets('NaN equality', (WidgetTester _) async { + final api = HostIntegrationCoreApi(); + + final a = AllNullableTypes(aNullableDouble: double.nan); + final b = AllNullableTypes(aNullableDouble: double.nan); + + expect(await api.areAllNullableTypesEqual(a, b), isTrue); + }); + + testWidgets('NaN hashing', (WidgetTester _) async { + final api = HostIntegrationCoreApi(); + + final a = AllNullableTypes(aNullableDouble: double.nan); + final b = AllNullableTypes(aNullableDouble: double.nan); + + final int hashA = await api.getAllNullableTypesHash(a); + final int hashB = await api.getAllNullableTypesHash(b); + expect(hashA, hashB, reason: 'Hash codes for two NaNs should be equal'); + }); + + testWidgets('Collection equality with signed zero and NaN', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); + + final a = AllNullableTypes( + doubleList: [0.0, double.nan], + stringMap: {'k': 'v', 'n': null}, + ); + final b = AllNullableTypes( + doubleList: [-0.0, double.nan], + stringMap: {'n': null, 'k': 'v'}, + ); + + expect(await api.areAllNullableTypesEqual(a, b), isTrue); + }); + + testWidgets('Collection hashing with signed zero and NaN', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); + + final a = AllNullableTypes( + doubleList: [0.0, double.nan], + stringMap: {'k': 'v', 'n': null}, + ); + final b = AllNullableTypes( + doubleList: [-0.0, double.nan], + stringMap: {'n': null, 'k': 'v'}, + ); + + expect( + await api.getAllNullableTypesHash(a), + await api.getAllNullableTypesHash(b), + ); + }); + + testWidgets('Collection hashing with null/NSNull', (WidgetTester _) async { + final api = HostIntegrationCoreApi(); + + final a = AllNullableTypes( + list: [null], + stringMap: {'k': null}, + ); + final b = AllNullableTypes( + list: [null], + stringMap: {'k': null}, + ); + + // Verify cross-platform equivalence via identical hash values. + expect( + await api.getAllNullableTypesHash(a), + await api.getAllNullableTypesHash(b), + ); + expect(await api.areAllNullableTypesEqual(a, b), isTrue); + }); + + testWidgets('Map equality with signed zero keys and values', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); + + final a = AllNullableTypes(map: {0.0: 'a', 'b': 0.0}); + final b = AllNullableTypes(map: {-0.0: 'a', 'b': -0.0}); + + expect(await api.areAllNullableTypesEqual(a, b), isTrue); + }); + + testWidgets('Map hashing with signed zero keys and values', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); + + final a = AllNullableTypes(map: {0.0: 'a', 'b': 0.0}); + final b = AllNullableTypes(map: {-0.0: 'a', 'b': -0.0}); + + expect( + await api.getAllNullableTypesHash(a), + await api.getAllNullableTypesHash(b), + ); + }); + + testWidgets('Map equality with null values and different keys', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); + + final a = AllNullableTypes(intMap: {1: null}); + final b = AllNullableTypes(intMap: {2: null}); + + expect(await api.areAllNullableTypesEqual(a, b), isFalse); + }); + + testWidgets('Deeply nested equality', (WidgetTester _) async { + final api = HostIntegrationCoreApi(); + + final a = AllNullableTypes( + allNullableTypes: AllNullableTypes(aNullableDouble: 0.0), + ); + final b = AllNullableTypes( + allNullableTypes: AllNullableTypes(aNullableDouble: -0.0), + ); + + expect(await api.areAllNullableTypesEqual(a, b), isTrue); + }); + + testWidgets('Hashing inequality across types with same values', ( + WidgetTester _, + ) async { + final api = HostIntegrationCoreApi(); + final a = AllNullableTypes(aNullableInt: 42); + final b = AllNullableTypesWithoutRecursion(aNullableInt: 42); + + expect(a.hashCode, isNot(b.hashCode)); + + expect( + await api.getAllNullableTypesHash(a), + isNot(await api.getAllNullableTypesWithoutRecursionHash(b)), + ); + }); }); group('Host async API tests', () { testWidgets('basic void->void call works', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); expect(api.noopAsync(), completes); }); @@ -1061,7 +1201,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('async errors are returned from non void methods correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); expect(() async { await api.throwAsyncError(); @@ -1071,7 +1211,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('async errors are returned from void methods correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); expect(() async { await api.throwAsyncErrorFromVoid(); @@ -1081,7 +1221,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'async flutter errors are returned from non void methods correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); expect( () => api.throwAsyncFlutterError(), @@ -1099,7 +1239,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('all datatypes async serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final AllTypes echoObject = await api.echoAsyncAllTypes(genericAllTypes); @@ -1109,7 +1249,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'all nullable async datatypes serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final AllNullableTypes? echoObject = await api .echoAsyncNullableAllNullableTypes(recursiveAllNullableTypes); @@ -1121,9 +1261,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'all null datatypes async serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - final AllNullableTypes allTypesNull = AllNullableTypes(); + final allTypesNull = AllNullableTypes(); final AllNullableTypes? echoNullFilledClass = await api .echoAsyncNullableAllNullableTypes(allTypesNull); @@ -1134,7 +1274,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'all nullable async datatypes without recursion serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final AllNullableTypesWithoutRecursion? echoObject = await api .echoAsyncNullableAllNullableTypesWithoutRecursion( @@ -1148,10 +1288,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'all null datatypes without recursion async serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - final AllNullableTypesWithoutRecursion allTypesNull = - AllNullableTypesWithoutRecursion(); + final allTypesNull = AllNullableTypesWithoutRecursion(); final AllNullableTypesWithoutRecursion? echoNullFilledClass = await api .echoAsyncNullableAllNullableTypesWithoutRecursion(allTypesNull); @@ -1162,7 +1301,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('Int async serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const int sentInt = regularInt; final int receivedInt = await api.echoAsyncInt(sentInt); @@ -1172,7 +1311,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('Int64 async serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const int sentInt = biggerThanBigInt; final int receivedInt = await api.echoAsyncInt(sentInt); @@ -1182,9 +1321,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('Doubles async serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - const double sentDouble = 2.0694; + const sentDouble = 2.0694; final double receivedDouble = await api.echoAsyncDouble(sentDouble); expect(receivedDouble, sentDouble); }); @@ -1192,9 +1331,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('booleans async serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - for (final bool sentBool in [true, false]) { + for (final sentBool in [true, false]) { final bool receivedBool = await api.echoAsyncBool(sentBool); expect(receivedBool, sentBool); } @@ -1203,9 +1342,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('strings async serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - const String sentObject = 'Hello, asynchronously!'; + const sentObject = 'Hello, asynchronously!'; final String echoObject = await api.echoAsyncString(sentObject); expect(echoObject, sentObject); @@ -1214,20 +1353,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('Uint8List async serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List data = [ - 102, - 111, - 114, - 116, - 121, - 45, - 116, - 119, - 111, - 0, - ]; - final Uint8List sentUint8List = Uint8List.fromList(data); + final api = HostIntegrationCoreApi(); + final data = [102, 111, 114, 116, 121, 45, 116, 119, 111, 0]; + final sentUint8List = Uint8List.fromList(data); final Uint8List receivedUint8List = await api.echoAsyncUint8List( sentUint8List, ); @@ -1237,7 +1365,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('generic Objects async serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const Object sentString = "I'm a computer"; final Object receivedString = await api.echoAsyncObject(sentString); expect(receivedString, sentString); @@ -1251,7 +1379,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List echoObject = await api.echoAsyncList(list); expect(listEquals(echoObject, list), true); @@ -1260,7 +1388,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('enum lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List echoObject = await api.echoAsyncEnumList(enumList); expect(listEquals(echoObject, enumList), true); @@ -1269,7 +1397,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('class lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List echoObject = await api.echoAsyncClassList( allNullableTypesList, @@ -1282,7 +1410,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api.echoAsyncMap(map); expect(mapEquals(echoObject, map), true); }); @@ -1290,7 +1418,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('string maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api.echoAsyncStringMap( stringMap, ); @@ -1300,7 +1428,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('int maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api.echoAsyncIntMap(intMap); expect(mapEquals(echoObject, intMap), true); }); @@ -1308,7 +1436,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('enum maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api.echoAsyncEnumMap( enumMap, ); @@ -1318,7 +1446,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('class maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api .echoAsyncClassMap(allNullableTypesMap); for (final MapEntry entry @@ -1330,7 +1458,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('enums serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.three; final AnEnum echoEnum = await api.echoAsyncEnum(sentEnum); @@ -1340,7 +1468,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('enums serialize and deserialize correctly (again)', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnotherEnum sentEnum = AnotherEnum.justInCase; final AnotherEnum echoEnum = await api.echoAnotherAsyncEnum(sentEnum); @@ -1350,7 +1478,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('multi word enums serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.fourHundredTwentyTwo; final AnEnum echoEnum = await api.echoAsyncEnum(sentEnum); @@ -1360,7 +1488,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable Int async serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const int sentInt = regularInt; final int? receivedInt = await api.echoAsyncNullableInt(sentInt); @@ -1370,7 +1498,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable Int64 async serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const int sentInt = biggerThanBigInt; final int? receivedInt = await api.echoAsyncNullableInt(sentInt); @@ -1380,9 +1508,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable Doubles async serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - const double sentDouble = 2.0694; + const sentDouble = 2.0694; final double? receivedDouble = await api.echoAsyncNullableDouble( sentDouble, ); @@ -1392,9 +1520,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable booleans async serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - for (final bool sentBool in [true, false]) { + for (final sentBool in [true, false]) { final bool? receivedBool = await api.echoAsyncNullableBool(sentBool); expect(receivedBool, sentBool); } @@ -1403,9 +1531,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable strings async serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - const String sentObject = 'Hello, asynchronously!'; + const sentObject = 'Hello, asynchronously!'; final String? echoObject = await api.echoAsyncNullableString(sentObject); expect(echoObject, sentObject); @@ -1414,20 +1542,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'nullable Uint8List async serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List data = [ - 102, - 111, - 114, - 116, - 121, - 45, - 116, - 119, - 111, - 0, - ]; - final Uint8List sentUint8List = Uint8List.fromList(data); + final api = HostIntegrationCoreApi(); + final data = [102, 111, 114, 116, 121, 45, 116, 119, 111, 0]; + final sentUint8List = Uint8List.fromList(data); final Uint8List? receivedUint8List = await api .echoAsyncNullableUint8List(sentUint8List); expect(receivedUint8List, sentUint8List); @@ -1437,7 +1554,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'nullable generic Objects async serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const Object sentString = "I'm a computer"; final Object? receivedString = await api.echoAsyncNullableObject( sentString, @@ -1454,7 +1571,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List? echoObject = await api.echoAsyncNullableList(list); expect(listEquals(echoObject, list), true); @@ -1463,7 +1580,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable enum lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List? echoObject = await api.echoAsyncNullableEnumList( enumList, @@ -1474,7 +1591,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable class lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List? echoObject = await api .echoAsyncNullableClassList(allNullableTypesList); @@ -1486,7 +1603,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api.echoAsyncNullableMap( map, ); @@ -1496,7 +1613,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable string maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api .echoAsyncNullableStringMap(stringMap); expect(mapEquals(echoObject, stringMap), true); @@ -1505,7 +1622,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable int maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api.echoAsyncNullableIntMap( intMap, ); @@ -1515,7 +1632,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable enum maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api .echoAsyncNullableEnumMap(enumMap); expect(mapEquals(echoObject, enumMap), true); @@ -1524,7 +1641,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable class maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api .echoAsyncNullableClassMap(allNullableTypesMap); for (final MapEntry entry @@ -1536,7 +1653,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable enums serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.three; final AnEnum? echoEnum = await api.echoAsyncNullableEnum(sentEnum); @@ -1546,7 +1663,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable enums serialize and deserialize correctly (again)', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnotherEnum sentEnum = AnotherEnum.justInCase; final AnotherEnum? echoEnum = await api.echoAnotherAsyncNullableEnum( @@ -1558,7 +1675,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable enums serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.fortyTwo; final AnEnum? echoEnum = await api.echoAsyncNullableEnum(sentEnum); @@ -1568,7 +1685,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null Ints async serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final int? receivedInt = await api.echoAsyncNullableInt(null); expect(receivedInt, null); @@ -1577,7 +1694,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null Doubles async serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final double? receivedDouble = await api.echoAsyncNullableDouble(null); expect(receivedDouble, null); @@ -1586,7 +1703,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null booleans async serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final bool? receivedBool = await api.echoAsyncNullableBool(null); expect(receivedBool, null); @@ -1595,7 +1712,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null strings async serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final String? echoObject = await api.echoAsyncNullableString(null); expect(echoObject, null); @@ -1604,7 +1721,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null Uint8List async serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Uint8List? receivedUint8List = await api.echoAsyncNullableUint8List( null, @@ -1615,7 +1732,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'null generic Objects async serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Object? receivedString = await api.echoAsyncNullableObject(null); expect(receivedString, null); }, @@ -1624,7 +1741,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List? echoObject = await api.echoAsyncNullableList(null); expect(listEquals(echoObject, null), true); @@ -1633,7 +1750,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api.echoAsyncNullableMap( null, @@ -1644,7 +1761,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null string maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api .echoAsyncNullableStringMap(null); @@ -1654,7 +1771,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null int maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api.echoAsyncNullableIntMap( null, @@ -1665,7 +1782,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null enums serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnEnum? sentEnum = null; final AnEnum? echoEnum = await api.echoAsyncNullableEnum(null); @@ -1675,7 +1792,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null enums serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnotherEnum? sentEnum = null; final AnotherEnum? echoEnum = await api.echoAnotherAsyncNullableEnum( @@ -1689,13 +1806,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('echo string succeeds with suffix with multiple instances', ( _, ) async { - final HostSmallApi apiWithSuffixOne = HostSmallApi( - messageChannelSuffix: 'suffixOne', - ); - final HostSmallApi apiWithSuffixTwo = HostSmallApi( - messageChannelSuffix: 'suffixTwo', - ); - const String sentString = "I'm a computer"; + final apiWithSuffixOne = HostSmallApi(messageChannelSuffix: 'suffixOne'); + final apiWithSuffixTwo = HostSmallApi(messageChannelSuffix: 'suffixTwo'); + const sentString = "I'm a computer"; final String echoStringOne = await apiWithSuffixOne.echo(sentString); final String echoStringTwo = await apiWithSuffixTwo.echo(sentString); expect(sentString, echoStringOne); @@ -1707,13 +1820,13 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { ) async { // The only way to get the channel name back is to throw an exception. // These APIs have no corresponding APIs on the host platforms. - final HostSmallApi apiWithSuffixOne = HostSmallApi( + final apiWithSuffixOne = HostSmallApi( messageChannelSuffix: 'suffixWithNoHost', ); - final HostSmallApi apiWithSuffixTwo = HostSmallApi( + final apiWithSuffixTwo = HostSmallApi( messageChannelSuffix: 'suffixWithoutHost', ); - const String sentString = "I'm a computer"; + const sentString = "I'm a computer"; try { await apiWithSuffixOne.echo(sentString); } on PlatformException catch (e) { @@ -1737,7 +1850,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }); testWidgets('basic void->void call works', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); expect(api.callFlutterNoop(), completes); }); @@ -1745,7 +1858,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('errors are returned from non void methods correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); expect(() async { await api.callFlutterThrowError(); @@ -1755,7 +1868,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('errors are returned from void methods correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); expect(() async { await api.callFlutterThrowErrorFromVoid(); @@ -1765,7 +1878,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('all datatypes serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final AllTypes echoObject = await api.callFlutterEchoAllTypes( genericAllTypes, @@ -1777,9 +1890,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'Arguments of multiple types serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - const String aNullableString = 'this is a String'; - const bool aNullableBool = false; + final api = HostIntegrationCoreApi(); + const aNullableString = 'this is a String'; + const aNullableBool = false; const int aNullableInt = regularInt; final AllNullableTypes compositeObject = await api @@ -1797,7 +1910,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'Arguments of multiple null types serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final AllNullableTypes compositeObject = await api .callFlutterSendMultipleNullableTypes(null, null, null); @@ -1810,9 +1923,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'Arguments of multiple types serialize and deserialize correctly (WithoutRecursion)', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - const String aNullableString = 'this is a String'; - const bool aNullableBool = false; + final api = HostIntegrationCoreApi(); + const aNullableString = 'this is a String'; + const aNullableBool = false; const int aNullableInt = regularInt; final AllNullableTypesWithoutRecursion compositeObject = await api @@ -1830,7 +1943,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'Arguments of multiple null types serialize and deserialize correctly (WithoutRecursion)', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final AllNullableTypesWithoutRecursion compositeObject = await api .callFlutterSendMultipleNullableTypesWithoutRecursion( @@ -1847,9 +1960,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('booleans serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - for (final bool sentObject in [true, false]) { + for (final sentObject in [true, false]) { final bool echoObject = await api.callFlutterEchoBool(sentObject); expect(echoObject, sentObject); } @@ -1858,7 +1971,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('ints serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const int sentObject = regularInt; final int echoObject = await api.callFlutterEchoInt(sentObject); @@ -1868,9 +1981,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('doubles serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - const double sentObject = 2.0694; + const sentObject = 2.0694; final double echoObject = await api.callFlutterEchoDouble(sentObject); expect(echoObject, sentObject); }); @@ -1878,9 +1991,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('strings serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - const String sentObject = 'Hello Dart!'; + const sentObject = 'Hello Dart!'; final String echoObject = await api.callFlutterEchoString(sentObject); expect(echoObject, sentObject); }); @@ -1888,21 +2001,10 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('Uint8Lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - final List data = [ - 102, - 111, - 114, - 116, - 121, - 45, - 116, - 119, - 111, - 0, - ]; - final Uint8List sentObject = Uint8List.fromList(data); + final data = [102, 111, 114, 116, 121, 45, 116, 119, 111, 0]; + final sentObject = Uint8List.fromList(data); final Uint8List echoObject = await api.callFlutterEchoUint8List( sentObject, ); @@ -1912,7 +2014,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List echoObject = await api.callFlutterEchoList(list); expect(listEquals(echoObject, list), true); @@ -1921,7 +2023,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('enum lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List echoObject = await api.callFlutterEchoEnumList( enumList, @@ -1932,7 +2034,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('class lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List echoObject = await api .callFlutterEchoClassList(allNullableTypesList); @@ -1944,7 +2046,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('NonNull enum lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List echoObject = await api.callFlutterEchoNonNullEnumList( nonNullEnumList, @@ -1955,7 +2057,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('NonNull class lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List echoObject = await api .callFlutterEchoNonNullClassList(nonNullAllNullableTypesList); @@ -1967,7 +2069,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api.callFlutterEchoMap( map, ); @@ -1977,7 +2079,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('string maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api .callFlutterEchoStringMap(stringMap); expect(mapEquals(echoObject, stringMap), true); @@ -1986,7 +2088,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('int maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api.callFlutterEchoIntMap( intMap, ); @@ -1996,7 +2098,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('enum maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api.callFlutterEchoEnumMap( enumMap, ); @@ -2006,7 +2108,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('class maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api .callFlutterEchoClassMap(allNullableTypesMap); for (final MapEntry entry @@ -2018,7 +2120,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('NonNull string maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api .callFlutterEchoNonNullStringMap(nonNullStringMap); expect(mapEquals(echoObject, nonNullStringMap), true); @@ -2027,7 +2129,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('NonNull int maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api.callFlutterEchoNonNullIntMap( nonNullIntMap, ); @@ -2037,7 +2139,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('NonNull enum maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api .callFlutterEchoNonNullEnumMap(nonNullEnumMap); expect(mapEquals(echoObject, nonNullEnumMap), true); @@ -2046,7 +2148,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('NonNull class maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map echoObject = await api .callFlutterEchoNonNullClassMap(nonNullAllNullableTypesMap); for (final MapEntry entry in echoObject.entries) { @@ -2057,7 +2159,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('enums serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.three; final AnEnum echoEnum = await api.callFlutterEchoEnum(sentEnum); @@ -2067,7 +2169,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('enums serialize and deserialize correctly (again)', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnotherEnum sentEnum = AnotherEnum.justInCase; final AnotherEnum echoEnum = await api.callFlutterEchoAnotherEnum( @@ -2079,7 +2181,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('multi word enums serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.fortyTwo; final AnEnum echoEnum = await api.callFlutterEchoEnum(sentEnum); @@ -2089,9 +2191,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable booleans serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - for (final bool? sentObject in [true, false]) { + for (final sentObject in [true, false]) { final bool? echoObject = await api.callFlutterEchoNullableBool( sentObject, ); @@ -2102,7 +2204,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null booleans serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const bool? sentObject = null; final bool? echoObject = await api.callFlutterEchoNullableBool( @@ -2114,7 +2216,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable ints serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const int sentObject = regularInt; final int? echoObject = await api.callFlutterEchoNullableInt(sentObject); @@ -2124,7 +2226,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable big ints serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const int sentObject = biggerThanBigInt; final int? echoObject = await api.callFlutterEchoNullableInt(sentObject); @@ -2134,7 +2236,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null ints serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final int? echoObject = await api.callFlutterEchoNullableInt(null); expect(echoObject, null); @@ -2143,9 +2245,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable doubles serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - const double sentObject = 2.0694; + const sentObject = 2.0694; final double? echoObject = await api.callFlutterEchoNullableDouble( sentObject, ); @@ -2155,7 +2257,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null doubles serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final double? echoObject = await api.callFlutterEchoNullableDouble(null); expect(echoObject, null); @@ -2164,9 +2266,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable strings serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); - const String sentObject = "I'm a computer"; + const sentObject = "I'm a computer"; final String? echoObject = await api.callFlutterEchoNullableString( sentObject, ); @@ -2176,7 +2278,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null strings serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final String? echoObject = await api.callFlutterEchoNullableString(null); expect(echoObject, null); @@ -2185,20 +2287,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable Uint8Lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - final List data = [ - 102, - 111, - 114, - 116, - 121, - 45, - 116, - 119, - 111, - 0, - ]; - final Uint8List sentObject = Uint8List.fromList(data); + final api = HostIntegrationCoreApi(); + final data = [102, 111, 114, 116, 121, 45, 116, 119, 111, 0]; + final sentObject = Uint8List.fromList(data); final Uint8List? echoObject = await api.callFlutterEchoNullableUint8List( sentObject, ); @@ -2208,7 +2299,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null Uint8Lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Uint8List? echoObject = await api.callFlutterEchoNullableUint8List( null, @@ -2219,7 +2310,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List? echoObject = await api.callFlutterEchoNullableList( list, @@ -2230,7 +2321,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable enum lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List? echoObject = await api .callFlutterEchoNullableEnumList(enumList); @@ -2240,7 +2331,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable class lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List? echoObject = await api .callFlutterEchoNullableClassList(allNullableTypesList); @@ -2252,7 +2343,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'nullable NonNull enum lists serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List? echoObject = await api .callFlutterEchoNullableNonNullEnumList(nonNullEnumList); @@ -2263,7 +2354,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'nullable NonNull class lists serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List? echoObject = await api .callFlutterEchoNullableNonNullClassList( @@ -2279,7 +2370,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null lists serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final List? echoObject = await api.callFlutterEchoNullableList( null, @@ -2290,7 +2381,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api .callFlutterEchoNullableMap(map); expect(mapEquals(echoObject, map), true); @@ -2299,7 +2390,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api .callFlutterEchoNullableMap(null); @@ -2309,7 +2400,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable string maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api .callFlutterEchoNullableStringMap(stringMap); expect(mapEquals(echoObject, stringMap), true); @@ -2318,7 +2409,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable int maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api .callFlutterEchoNullableIntMap(intMap); expect(mapEquals(echoObject, intMap), true); @@ -2327,7 +2418,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable enum maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api .callFlutterEchoNullableEnumMap(enumMap); expect(mapEquals(echoObject, enumMap), true); @@ -2336,7 +2427,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable class maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api .callFlutterEchoNullableClassMap(allNullableTypesMap); for (final MapEntry entry @@ -2348,7 +2439,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'nullable NonNull string maps serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api .callFlutterEchoNullableNonNullStringMap(nonNullStringMap); expect(mapEquals(echoObject, nonNullStringMap), true); @@ -2358,7 +2449,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'nullable NonNull int maps serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api .callFlutterEchoNullableNonNullIntMap(nonNullIntMap); expect(mapEquals(echoObject, nonNullIntMap), true); @@ -2368,7 +2459,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'nullable NonNull enum maps serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api .callFlutterEchoNullableNonNullEnumMap(nonNullEnumMap); expect(mapEquals(echoObject, nonNullEnumMap), true); @@ -2378,7 +2469,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'nullable NonNull class maps serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api .callFlutterEchoNullableNonNullClassMap(nonNullAllNullableTypesMap); for (final MapEntry entry @@ -2391,7 +2482,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null maps serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); final Map? echoObject = await api .callFlutterEchoNullableIntMap(null); @@ -2401,7 +2492,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable enums serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.three; final AnEnum? echoEnum = await api.callFlutterEchoNullableEnum(sentEnum); @@ -2411,7 +2502,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('nullable enums serialize and deserialize correctly (again)', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnotherEnum sentEnum = AnotherEnum.justInCase; final AnotherEnum? echoEnum = await api @@ -2422,7 +2513,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'multi word nullable enums serialize and deserialize correctly', (WidgetTester _) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnEnum sentEnum = AnEnum.fourHundredTwentyTwo; final AnEnum? echoEnum = await api.callFlutterEchoNullableEnum( @@ -2435,7 +2526,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null enums serialize and deserialize correctly', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnEnum? sentEnum = null; final AnEnum? echoEnum = await api.callFlutterEchoNullableEnum(sentEnum); @@ -2445,7 +2536,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('null enums serialize and deserialize correctly (again)', ( WidgetTester _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); const AnotherEnum? sentEnum = null; final AnotherEnum? echoEnum = await api @@ -2460,7 +2551,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { } testWidgets('named constructor', (_) async { - final ProxyApiTestClass instance = ProxyApiTestClass.namedConstructor( + final instance = ProxyApiTestClass.namedConstructor( aBool: true, anInt: 0, aDouble: 0.0, @@ -2528,35 +2619,35 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('echoInt', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); - const int value = 0; + const value = 0; expect(await api.echoInt(value), value); }); testWidgets('echoDouble', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); - const double value = 0.0; + const value = 0.0; expect(await api.echoDouble(value), value); }); testWidgets('echoBool', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); - const bool value = true; + const value = true; expect(await api.echoBool(value), value); }); testWidgets('echoString', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); - const String value = 'string'; + const value = 'string'; expect(await api.echoString(value), value); }); testWidgets('echoUint8List', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); - final Uint8List value = Uint8List(0); + final value = Uint8List(0); expect(await api.echoUint8List(value), value); }); @@ -2577,7 +2668,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('echoProxyApiList', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); - final List value = [ + final value = [ _createGenericProxyApiTestClass(), _createGenericProxyApiTestClass(), ]; @@ -2587,14 +2678,14 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('echoMap', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); - const Map value = {'apple': 'pie'}; + const value = {'apple': 'pie'}; expect(await api.echoMap(value), value); }); testWidgets('echoProxyApiMap', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); - final Map value = { + final value = { '42': _createGenericProxyApiTestClass(), }; expect(await api.echoProxyApiMap(value), value); @@ -2610,7 +2701,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('echoProxyApi', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); - final ProxyApiSuperClass value = ProxyApiSuperClass(); + final value = ProxyApiSuperClass(); expect(await api.echoProxyApi(value), value); }); @@ -2678,7 +2769,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); expect(await api.echoNullableProxyApi(null), null); - final ProxyApiSuperClass proxyApi = ProxyApiSuperClass(); + final proxyApi = ProxyApiSuperClass(); expect(await api.echoNullableProxyApi(proxyApi), proxyApi); }); @@ -2690,35 +2781,35 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('echoAsyncInt', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); - const int value = 0; + const value = 0; expect(await api.echoAsyncInt(value), value); }); testWidgets('echoAsyncDouble', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); - const double value = 0.0; + const value = 0.0; expect(await api.echoAsyncDouble(value), value); }); testWidgets('echoAsyncBool', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); - const bool value = false; + const value = false; expect(await api.echoAsyncBool(value), value); }); testWidgets('echoAsyncString', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); - const String value = 'ping'; + const value = 'ping'; expect(await api.echoAsyncString(value), value); }); testWidgets('echoAsyncUint8List', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); - final Uint8List value = Uint8List(0); + final value = Uint8List(0); expect(await api.echoAsyncUint8List(value), value); }); @@ -2732,16 +2823,14 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('echoAsyncList', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); - const List value = ['apple', 'pie']; + const value = ['apple', 'pie']; expect(await api.echoAsyncList(value), value); }); testWidgets('echoAsyncMap', (_) async { final ProxyApiTestClass api = _createGenericProxyApiTestClass(); - final Map value = { - 'something': ProxyApiSuperClass(), - }; + final value = {'something': ProxyApiSuperClass()}; expect(await api.echoAsyncMap(value), value); }); @@ -2849,7 +2938,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }); testWidgets('echoStaticString', (_) async { - const String value = 'static string'; + const value = 'static string'; expect(await ProxyApiTestClass.echoStaticString(value), value); }); @@ -2858,7 +2947,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }); testWidgets('callFlutterNoop', (_) async { - bool called = false; + var called = false; final ProxyApiTestClass api = _createGenericProxyApiTestClass( flutterNoop: (ProxyApiTestClass instance) async { called = true; @@ -2912,7 +3001,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { flutterEchoBool: (_, bool aBool) => aBool, ); - const bool value = true; + const value = true; expect(await api.callFlutterEchoBool(value), value); }); @@ -2921,7 +3010,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { flutterEchoInt: (_, int anInt) => anInt, ); - const int value = 0; + const value = 0; expect(await api.callFlutterEchoInt(value), value); }); @@ -2930,7 +3019,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { flutterEchoDouble: (_, double aDouble) => aDouble, ); - const double value = 0.0; + const value = 0.0; expect(await api.callFlutterEchoDouble(value), value); }); @@ -2939,7 +3028,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { flutterEchoString: (_, String aString) => aString, ); - const String value = 'a string'; + const value = 'a string'; expect(await api.callFlutterEchoString(value), value); }); @@ -2948,7 +3037,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { flutterEchoUint8List: (_, Uint8List aUint8List) => aUint8List, ); - final Uint8List value = Uint8List(0); + final value = Uint8List(0); expect(await api.callFlutterEchoUint8List(value), value); }); @@ -2957,7 +3046,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { flutterEchoList: (_, List aList) => aList, ); - final List value = [0, 0.0, true, ProxyApiSuperClass()]; + final value = [0, 0.0, true, ProxyApiSuperClass()]; expect(await api.callFlutterEchoList(value), value); }); @@ -2977,7 +3066,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { flutterEchoMap: (_, Map aMap) => aMap, ); - final Map value = {'a String': 4}; + final value = {'a String': 4}; expect(await api.callFlutterEchoMap(value), value); }); @@ -2987,10 +3076,9 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { aMap, ); - final Map value = - { - 'a String': _createGenericProxyApiTestClass(), - }; + final value = { + 'a String': _createGenericProxyApiTestClass(), + }; expect(await api.callFlutterEchoProxyApiMap(value), value); }); @@ -3008,7 +3096,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { flutterEchoProxyApi: (_, ProxyApiSuperClass aProxyApi) => aProxyApi, ); - final ProxyApiSuperClass value = ProxyApiSuperClass(); + final value = ProxyApiSuperClass(); expect(await api.callFlutterEchoProxyApi(value), value); }); @@ -3093,12 +3181,12 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { expect(await api.callFlutterEchoNullableProxyApi(null), null); - final ProxyApiSuperClass proxyApi = ProxyApiSuperClass(); + final proxyApi = ProxyApiSuperClass(); expect(await api.callFlutterEchoNullableProxyApi(proxyApi), proxyApi); }); testWidgets('callFlutterNoopAsync', (_) async { - bool called = false; + var called = false; final ProxyApiTestClass api = _createGenericProxyApiTestClass( flutterNoopAsync: (ProxyApiTestClass instance) async { called = true; @@ -3114,7 +3202,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { flutterEchoAsyncString: (_, String aString) async => aString, ); - const String value = 'a string'; + const value = 'a string'; expect(await api.callFlutterEchoAsyncString(value), value); }); }); @@ -3134,8 +3222,8 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets('echo string succeeds with suffix with multiple instances', ( _, ) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); - const String sentObject = "I'm a computer"; + final api = HostIntegrationCoreApi(); + const sentObject = "I'm a computer"; final String echoObject = await api.callFlutterSmallApiEchoString( sentObject, ); @@ -3144,19 +3232,19 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { }); testWidgets('Unused data class still generate', (_) async { - final UnusedClass unused = UnusedClass(); + final unused = UnusedClass(); expect(unused, unused); }); /// Task queues testWidgets('non-task-queue handlers run on a the main thread', (_) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); expect(await api.defaultIsMainThread(), true); }); testWidgets('task queue handlers run on a background thread', (_) async { - final HostIntegrationCoreApi api = HostIntegrationCoreApi(); + final api = HostIntegrationCoreApi(); // Currently only Android and iOS have task queue support. See // https://github.com/flutter/flutter/issues/93945 // Rather than skip the test, this changes the expectation, so that there @@ -3172,7 +3260,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { /// Event channels - const List eventChannelSupported = [ + const eventChannelSupported = [ TargetGenerator.kotlin, TargetGenerator.swift, ]; @@ -3182,7 +3270,7 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { (_) async { final Stream events = streamInts(); final List listEvents = await events.toList(); - for (final int value in listEvents) { + for (final value in listEvents) { expect(listEvents[value], value); } }, @@ -3192,8 +3280,8 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'event channel handles extended sealed classes', (_) async { - final Completer completer = Completer(); - int count = 0; + final completer = Completer(); + var count = 0; final Stream events = streamEvents(); events.listen((PlatformEvent event) { switch (event) { @@ -3236,8 +3324,8 @@ void runPigeonIntegrationTests(TargetGenerator targetGenerator) { testWidgets( 'event channels handle multiple instances', (_) async { - final Completer completer1 = Completer(); - final Completer completer2 = Completer(); + final completer1 = Completer(); + final completer2 = Completer(); final Stream events1 = streamConsistentNumbers(instanceName: '1'); final Stream events2 = streamConsistentNumbers(instanceName: '2'); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/background_platform_channels.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/background_platform_channels.gen.dart index 5f82202deb15..d6e49a4b33b3 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/background_platform_channels.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/background_platform_channels.gen.dart @@ -58,21 +58,19 @@ class BackgroundApi2Host { final String pigeonVar_messageChannelSuffix; Future add(int x, int y) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.BackgroundApi2Host.add$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [ [x, y], ], ); - final List? pigeonVar_replyList = - await pigeonVar_sendFuture as List?; + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; if (pigeonVar_replyList == null) { throw _createConnectionError(pigeonVar_channelName); } else if (pigeonVar_replyList.length > 1) { diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/core_tests.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/core_tests.gen.dart index d7b4d841b247..c3e553e368c6 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/core_tests.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/core_tests.gen.dart @@ -4,19 +4,38 @@ // // Autogenerated from Pigeon, 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 +// ignore_for_file: unused_import, unused_shown_name +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, omit_obvious_local_variable_types, unnecessary_import, no_leading_underscores_for_local_identifiers import 'dart:async'; -import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; +import 'dart:typed_data' show Float64List, Int32List, Int64List; -import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; +import 'package:meta/meta.dart' show immutable, protected, visibleForTesting; -PlatformException _createConnectionError(String channelName) { - return PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel: "$channelName".', - ); +Object? _extractReplyValueOrThrow( + List? replyList, + String channelName, { + required bool isNullValid, +}) { + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel: "$channelName".', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (!isNullValid && (replyList.isNotEmpty && replyList[0] == null)) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } + return replyList.firstOrNull; } List wrapResponse({ @@ -34,6 +53,15 @@ List wrapResponse({ } bool _deepEquals(Object? a, Object? b) { + if (identical(a, b)) { + return true; + } + if (a is double && b is double) { + if (a.isNaN && b.isNaN) { + return true; + } + return a == b; + } if (a is List && b is List) { return a.length == b.length && a.indexed.every( @@ -41,16 +69,52 @@ bool _deepEquals(Object? a, Object? b) { ); } if (a is Map && b is Map) { - return a.length == b.length && - a.entries.every( - (MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key]), - ); + if (a.length != b.length) { + return false; + } + for (final MapEntry entryA in a.entries) { + bool found = false; + for (final MapEntry entryB in b.entries) { + if (_deepEquals(entryA.key, entryB.key)) { + if (_deepEquals(entryA.value, entryB.value)) { + found = true; + break; + } else { + return false; + } + } + } + if (!found) { + return false; + } + } + return true; } return a == b; } +int _deepHash(Object? value) { + if (value is List) { + return Object.hashAll(value.map(_deepHash)); + } + if (value is Map) { + int result = 0; + for (final MapEntry entry in value.entries) { + result += (_deepHash(entry.key) * 31) ^ _deepHash(entry.value); + } + return result; + } + if (value is double && value.isNaN) { + // Normalize NaN to a consistent hash. + return 0x7FF8000000000000.hashCode; + } + if (value is double && value == 0.0) { + // Normalize -0.0 to 0.0 so they have the same hash code. + return 0.0.hashCode; + } + return value.hashCode; +} + enum AnEnum { one, two, three, fortyTwo, fourHundredTwentyTwo } enum AnotherEnum { justInCase } @@ -82,12 +146,12 @@ class UnusedClass { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(aField, other.aField); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } /// A class containing all supported types. @@ -232,22 +296,22 @@ class AllTypes { aString: result[10]! as String, anObject: result[11]!, list: result[12]! as List, - stringList: (result[13] as List?)!.cast(), - intList: (result[14] as List?)!.cast(), - doubleList: (result[15] as List?)!.cast(), - boolList: (result[16] as List?)!.cast(), - enumList: (result[17] as List?)!.cast(), - objectList: (result[18] as List?)!.cast(), - listList: (result[19] as List?)!.cast>(), - mapList: (result[20] as List?)!.cast>(), + stringList: (result[13]! as List).cast(), + intList: (result[14]! as List).cast(), + doubleList: (result[15]! as List).cast(), + boolList: (result[16]! as List).cast(), + enumList: (result[17]! as List).cast(), + objectList: (result[18]! as List).cast(), + listList: (result[19]! as List).cast>(), + mapList: (result[20]! as List).cast>(), map: result[21]! as Map, - stringMap: (result[22] as Map?)!.cast(), - intMap: (result[23] as Map?)!.cast(), - enumMap: (result[24] as Map?)!.cast(), - objectMap: (result[25] as Map?)!.cast(), - listMap: (result[26] as Map?)! + stringMap: (result[22]! as Map).cast(), + intMap: (result[23]! as Map).cast(), + enumMap: (result[24]! as Map).cast(), + objectMap: (result[25]! as Map).cast(), + listMap: (result[26]! as Map) .cast>(), - mapMap: (result[27] as Map?)! + mapMap: (result[27]! as Map) .cast>(), ); } @@ -261,12 +325,39 @@ class AllTypes { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(aBool, other.aBool) && + _deepEquals(anInt, other.anInt) && + _deepEquals(anInt64, other.anInt64) && + _deepEquals(aDouble, other.aDouble) && + _deepEquals(aByteArray, other.aByteArray) && + _deepEquals(a4ByteArray, other.a4ByteArray) && + _deepEquals(a8ByteArray, other.a8ByteArray) && + _deepEquals(aFloatArray, other.aFloatArray) && + _deepEquals(anEnum, other.anEnum) && + _deepEquals(anotherEnum, other.anotherEnum) && + _deepEquals(aString, other.aString) && + _deepEquals(anObject, other.anObject) && + _deepEquals(list, other.list) && + _deepEquals(stringList, other.stringList) && + _deepEquals(intList, other.intList) && + _deepEquals(doubleList, other.doubleList) && + _deepEquals(boolList, other.boolList) && + _deepEquals(enumList, other.enumList) && + _deepEquals(objectList, other.objectList) && + _deepEquals(listList, other.listList) && + _deepEquals(mapList, other.mapList) && + _deepEquals(map, other.map) && + _deepEquals(stringMap, other.stringMap) && + _deepEquals(intMap, other.intMap) && + _deepEquals(enumMap, other.enumMap) && + _deepEquals(objectMap, other.objectMap) && + _deepEquals(listMap, other.listMap) && + _deepEquals(mapMap, other.mapMap); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } /// A class containing all supported nullable types. @@ -429,7 +520,7 @@ class AllNullableTypes { doubleList: (result[16] as List?)?.cast(), boolList: (result[17] as List?)?.cast(), enumList: (result[18] as List?)?.cast(), - objectList: (result[19] as List?)?.cast(), + objectList: result[19] as List?, listList: (result[20] as List?)?.cast?>(), mapList: (result[21] as List?)?.cast?>(), recursiveClassList: (result[22] as List?) @@ -439,8 +530,7 @@ class AllNullableTypes { ?.cast(), intMap: (result[25] as Map?)?.cast(), enumMap: (result[26] as Map?)?.cast(), - objectMap: (result[27] as Map?) - ?.cast(), + objectMap: result[27] as Map?, listMap: (result[28] as Map?) ?.cast?>(), mapMap: (result[29] as Map?) @@ -459,12 +549,42 @@ class AllNullableTypes { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(aNullableBool, other.aNullableBool) && + _deepEquals(aNullableInt, other.aNullableInt) && + _deepEquals(aNullableInt64, other.aNullableInt64) && + _deepEquals(aNullableDouble, other.aNullableDouble) && + _deepEquals(aNullableByteArray, other.aNullableByteArray) && + _deepEquals(aNullable4ByteArray, other.aNullable4ByteArray) && + _deepEquals(aNullable8ByteArray, other.aNullable8ByteArray) && + _deepEquals(aNullableFloatArray, other.aNullableFloatArray) && + _deepEquals(aNullableEnum, other.aNullableEnum) && + _deepEquals(anotherNullableEnum, other.anotherNullableEnum) && + _deepEquals(aNullableString, other.aNullableString) && + _deepEquals(aNullableObject, other.aNullableObject) && + _deepEquals(allNullableTypes, other.allNullableTypes) && + _deepEquals(list, other.list) && + _deepEquals(stringList, other.stringList) && + _deepEquals(intList, other.intList) && + _deepEquals(doubleList, other.doubleList) && + _deepEquals(boolList, other.boolList) && + _deepEquals(enumList, other.enumList) && + _deepEquals(objectList, other.objectList) && + _deepEquals(listList, other.listList) && + _deepEquals(mapList, other.mapList) && + _deepEquals(recursiveClassList, other.recursiveClassList) && + _deepEquals(map, other.map) && + _deepEquals(stringMap, other.stringMap) && + _deepEquals(intMap, other.intMap) && + _deepEquals(enumMap, other.enumMap) && + _deepEquals(objectMap, other.objectMap) && + _deepEquals(listMap, other.listMap) && + _deepEquals(mapMap, other.mapMap) && + _deepEquals(recursiveClassMap, other.recursiveClassMap); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } /// The primary purpose for this class is to ensure coverage of Swift structs @@ -616,7 +736,7 @@ class AllNullableTypesWithoutRecursion { doubleList: (result[15] as List?)?.cast(), boolList: (result[16] as List?)?.cast(), enumList: (result[17] as List?)?.cast(), - objectList: (result[18] as List?)?.cast(), + objectList: result[18] as List?, listList: (result[19] as List?)?.cast?>(), mapList: (result[20] as List?)?.cast?>(), map: result[21] as Map?, @@ -624,8 +744,7 @@ class AllNullableTypesWithoutRecursion { ?.cast(), intMap: (result[23] as Map?)?.cast(), enumMap: (result[24] as Map?)?.cast(), - objectMap: (result[25] as Map?) - ?.cast(), + objectMap: result[25] as Map?, listMap: (result[26] as Map?) ?.cast?>(), mapMap: (result[27] as Map?) @@ -643,12 +762,39 @@ class AllNullableTypesWithoutRecursion { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(aNullableBool, other.aNullableBool) && + _deepEquals(aNullableInt, other.aNullableInt) && + _deepEquals(aNullableInt64, other.aNullableInt64) && + _deepEquals(aNullableDouble, other.aNullableDouble) && + _deepEquals(aNullableByteArray, other.aNullableByteArray) && + _deepEquals(aNullable4ByteArray, other.aNullable4ByteArray) && + _deepEquals(aNullable8ByteArray, other.aNullable8ByteArray) && + _deepEquals(aNullableFloatArray, other.aNullableFloatArray) && + _deepEquals(aNullableEnum, other.aNullableEnum) && + _deepEquals(anotherNullableEnum, other.anotherNullableEnum) && + _deepEquals(aNullableString, other.aNullableString) && + _deepEquals(aNullableObject, other.aNullableObject) && + _deepEquals(list, other.list) && + _deepEquals(stringList, other.stringList) && + _deepEquals(intList, other.intList) && + _deepEquals(doubleList, other.doubleList) && + _deepEquals(boolList, other.boolList) && + _deepEquals(enumList, other.enumList) && + _deepEquals(objectList, other.objectList) && + _deepEquals(listList, other.listList) && + _deepEquals(mapList, other.mapList) && + _deepEquals(map, other.map) && + _deepEquals(stringMap, other.stringMap) && + _deepEquals(intMap, other.intMap) && + _deepEquals(enumMap, other.enumMap) && + _deepEquals(objectMap, other.objectMap) && + _deepEquals(listMap, other.listMap) && + _deepEquals(mapMap, other.mapMap); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } /// A class for testing nested class handling. @@ -704,10 +850,10 @@ class AllClassesWrapper { allNullableTypesWithoutRecursion: result[1] as AllNullableTypesWithoutRecursion?, allTypes: result[2] as AllTypes?, - classList: (result[3] as List?)!.cast(), + classList: (result[3]! as List).cast(), nullableClassList: (result[4] as List?) ?.cast(), - classMap: (result[5] as Map?)!.cast(), + classMap: (result[5]! as Map).cast(), nullableClassMap: (result[6] as Map?) ?.cast(), ); @@ -722,12 +868,21 @@ class AllClassesWrapper { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(allNullableTypes, other.allNullableTypes) && + _deepEquals( + allNullableTypesWithoutRecursion, + other.allNullableTypesWithoutRecursion, + ) && + _deepEquals(allTypes, other.allTypes) && + _deepEquals(classList, other.classList) && + _deepEquals(nullableClassList, other.nullableClassList) && + _deepEquals(classMap, other.classMap) && + _deepEquals(nullableClassMap, other.nullableClassMap); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } /// A data class containing a List, used in unit tests. @@ -758,12 +913,12 @@ class TestMessage { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(testList, other.testList); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } class _PigeonCodec extends StandardMessageCodec { @@ -806,10 +961,10 @@ class _PigeonCodec extends StandardMessageCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 129: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : AnEnum.values[value]; case 130: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : AnotherEnum.values[value]; case 131: return UnusedClass.decode(readValue(buffer)!); @@ -851,1054 +1006,791 @@ class HostIntegrationCoreApi { /// A no-op function taking no arguments and returning no value, to sanity /// test basic calling. Future noop() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.noop$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); } /// Returns the passed object, to test serialization and deserialization. Future echoAllTypes(AllTypes everything) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAllTypes$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [everything], ); - 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 AllTypes?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as AllTypes; } /// Returns an error, to test error handling. Future throwError() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwError$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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 pigeonVar_replyList[0]; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue; } /// Returns an error from a void function, to test error handling. Future throwErrorFromVoid() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwErrorFromVoid$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); } /// Returns a Flutter error, to test error handling. Future throwFlutterError() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwFlutterError$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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 pigeonVar_replyList[0]; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue; } /// Returns passed in int. Future echoInt(int anInt) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoInt$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [anInt], ); - 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 int?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as int; } /// Returns passed in double. Future echoDouble(double aDouble) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoDouble$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aDouble], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as double; } /// Returns the passed in boolean. Future echoBool(bool aBool) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoBool$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aBool], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as bool; } /// Returns the passed in string. Future echoString(String aString) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoString$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aString], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as String; } /// Returns the passed in Uint8List. Future echoUint8List(Uint8List aUint8List) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoUint8List$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aUint8List], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as Uint8List; } /// Returns the passed in generic Object. Future echoObject(Object anObject) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoObject$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [anObject], ); - 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]!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue!; } /// Returns the passed list, to test serialization and deserialization. Future> echoList(List list) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [list], ); - 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 List?)!.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as List; } /// Returns the passed list, to test serialization and deserialization. Future> echoEnumList(List enumList) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoEnumList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [enumList], ); - 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 List?)!.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as List).cast(); } /// Returns the passed list, to test serialization and deserialization. Future> echoClassList( List classList, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoClassList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [classList], ); - 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 List?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as List).cast(); } /// Returns the passed list, to test serialization and deserialization. Future> echoNonNullEnumList(List enumList) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNonNullEnumList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [enumList], ); - 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 List?)!.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as List).cast(); } /// Returns the passed list, to test serialization and deserialization. Future> echoNonNullClassList( List classList, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNonNullClassList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [classList], ); - 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 List?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as List).cast(); } /// Returns the passed map, to test serialization and deserialization. Future> echoMap(Map map) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [map], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as Map; } /// Returns the passed map, to test serialization and deserialization. Future> echoStringMap( Map stringMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoStringMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [stringMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map) + .cast(); } /// Returns the passed map, to test serialization and deserialization. Future> echoIntMap(Map intMap) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoIntMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [intMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map).cast(); } /// Returns the passed map, to test serialization and deserialization. Future> echoEnumMap( Map enumMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoEnumMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [enumMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map) + .cast(); } /// Returns the passed map, to test serialization and deserialization. Future> echoClassMap( Map classMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoClassMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [classMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map) + .cast(); } /// Returns the passed map, to test serialization and deserialization. Future> echoNonNullStringMap( Map stringMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNonNullStringMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [stringMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map) + .cast(); } /// Returns the passed map, to test serialization and deserialization. Future> echoNonNullIntMap(Map intMap) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNonNullIntMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [intMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map).cast(); } /// Returns the passed map, to test serialization and deserialization. Future> echoNonNullEnumMap( Map enumMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNonNullEnumMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [enumMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map) + .cast(); } /// Returns the passed map, to test serialization and deserialization. Future> echoNonNullClassMap( Map classMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNonNullClassMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [classMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map) + .cast(); } /// Returns the passed class to test nested class serialization and deserialization. Future echoClassWrapper(AllClassesWrapper wrapper) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoClassWrapper$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [wrapper], ); - 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 AllClassesWrapper?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as AllClassesWrapper; } /// Returns the passed enum to test serialization and deserialization. Future echoEnum(AnEnum anEnum) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoEnum$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [anEnum], ); - 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 AnEnum?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as AnEnum; } /// Returns the passed enum to test serialization and deserialization. Future echoAnotherEnum(AnotherEnum anotherEnum) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAnotherEnum$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [anotherEnum], ); - 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 AnotherEnum?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as AnotherEnum; } /// Returns the default string. Future echoNamedDefaultString({String aString = 'default'}) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNamedDefaultString$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aString], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as String; } /// Returns passed in double. Future echoOptionalDefaultDouble([double aDouble = 3.14]) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoOptionalDefaultDouble$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aDouble], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as double; } /// Returns passed in int. Future echoRequiredInt({required int anInt}) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoRequiredInt$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [anInt], ); - 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 int?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as int; + } + + /// Returns the result of platform-side equality check. + Future areAllNullableTypesEqual( + AllNullableTypes a, + AllNullableTypes b, + ) async { + final pigeonVar_channelName = + 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.areAllNullableTypesEqual$pigeonVar_messageChannelSuffix'; + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [a, b], + ); + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as bool; + } + + /// Returns the platform-side hash code for the given object. + Future getAllNullableTypesHash(AllNullableTypes value) async { + final pigeonVar_channelName = + 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.getAllNullableTypesHash$pigeonVar_messageChannelSuffix'; + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [value], + ); + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as int; + } + + /// Returns the platform-side hash code for the given object. + Future getAllNullableTypesWithoutRecursionHash( + AllNullableTypesWithoutRecursion value, + ) async { + final pigeonVar_channelName = + 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.getAllNullableTypesWithoutRecursionHash$pigeonVar_messageChannelSuffix'; + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [value], + ); + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as int; } /// Returns the passed object, to test serialization and deserialization. Future echoAllNullableTypes( AllNullableTypes? everything, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAllNullableTypes$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [everything], ); - 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 AllNullableTypes?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as AllNullableTypes?; } /// Returns the passed object, to test serialization and deserialization. @@ -1906,59 +1798,47 @@ class HostIntegrationCoreApi { echoAllNullableTypesWithoutRecursion( AllNullableTypesWithoutRecursion? everything, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAllNullableTypesWithoutRecursion$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [everything], ); - 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 AllNullableTypesWithoutRecursion?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as AllNullableTypesWithoutRecursion?; } /// Returns the inner `aString` value from the wrapped object, to test /// sending of nested objects. Future extractNestedNullableString(AllClassesWrapper wrapper) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.extractNestedNullableString$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [wrapper], ); - 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 String?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as String?; } /// Returns the inner `aString` value from the wrapped object, to test @@ -1966,35 +1846,24 @@ class HostIntegrationCoreApi { Future createNestedNullableString( String? nullableString, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.createNestedNullableString$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [nullableString], ); - 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 AllClassesWrapper?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as AllClassesWrapper; } /// Returns passed in arguments of multiple types. @@ -2003,35 +1872,24 @@ class HostIntegrationCoreApi { int? aNullableInt, String? aNullableString, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.sendMultipleNullableTypes$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aNullableBool, aNullableInt, aNullableString], ); - 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 AllNullableTypes?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as AllNullableTypes; } /// Returns passed in arguments of multiple types. @@ -2041,1450 +1899,1068 @@ class HostIntegrationCoreApi { int? aNullableInt, String? aNullableString, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.sendMultipleNullableTypesWithoutRecursion$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aNullableBool, aNullableInt, aNullableString], ); - 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 AllNullableTypesWithoutRecursion?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as AllNullableTypesWithoutRecursion; } /// Returns passed in int. Future echoNullableInt(int? aNullableInt) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableInt$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aNullableInt], ); - 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?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as int?; } /// Returns passed in double. Future echoNullableDouble(double? aNullableDouble) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableDouble$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aNullableDouble], ); - 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 double?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as double?; } /// Returns the passed in boolean. Future echoNullableBool(bool? aNullableBool) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableBool$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aNullableBool], ); - 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 bool?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as bool?; } /// Returns the passed in string. Future echoNullableString(String? aNullableString) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableString$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aNullableString], ); - 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 String?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as String?; } /// Returns the passed in Uint8List. Future echoNullableUint8List( Uint8List? aNullableUint8List, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableUint8List$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aNullableUint8List], ); - 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?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as Uint8List?; } /// Returns the passed in generic Object. Future echoNullableObject(Object? aNullableObject) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableObject$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aNullableObject], ); - 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]; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue; } /// Returns the passed list, to test serialization and deserialization. Future?> echoNullableList(List? aNullableList) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aNullableList], ); - 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(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as List?; } /// Returns the passed list, to test serialization and deserialization. Future?> echoNullableEnumList(List? enumList) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableEnumList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [enumList], ); - 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(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as List?)?.cast(); } /// Returns the passed list, to test serialization and deserialization. Future?> echoNullableClassList( List? classList, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableClassList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [classList], ); - 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(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as List?)?.cast(); } /// Returns the passed list, to test serialization and deserialization. Future?> echoNullableNonNullEnumList( List? enumList, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableNonNullEnumList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [enumList], ); - 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(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as List?)?.cast(); } /// Returns the passed list, to test serialization and deserialization. Future?> echoNullableNonNullClassList( List? classList, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableNonNullClassList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [classList], ); - 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(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as List?)?.cast(); } /// Returns the passed map, to test serialization and deserialization. Future?> echoNullableMap( Map? map, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [map], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as Map?; } /// Returns the passed map, to test serialization and deserialization. Future?> echoNullableStringMap( Map? stringMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableStringMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [stringMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?) + ?.cast(); } /// Returns the passed map, to test serialization and deserialization. Future?> echoNullableIntMap(Map? intMap) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableIntMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [intMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?)?.cast(); } /// Returns the passed map, to test serialization and deserialization. Future?> echoNullableEnumMap( Map? enumMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableEnumMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [enumMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?) + ?.cast(); } /// Returns the passed map, to test serialization and deserialization. Future?> echoNullableClassMap( Map? classMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableClassMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [classMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?) + ?.cast(); } /// Returns the passed map, to test serialization and deserialization. Future?> echoNullableNonNullStringMap( Map? stringMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableNonNullStringMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [stringMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?) + ?.cast(); } /// Returns the passed map, to test serialization and deserialization. Future?> echoNullableNonNullIntMap( Map? intMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableNonNullIntMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [intMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?)?.cast(); } /// Returns the passed map, to test serialization and deserialization. Future?> echoNullableNonNullEnumMap( Map? enumMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableNonNullEnumMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [enumMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?) + ?.cast(); } /// Returns the passed map, to test serialization and deserialization. Future?> echoNullableNonNullClassMap( Map? classMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableNonNullClassMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [classMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?) + ?.cast(); } Future echoNullableEnum(AnEnum? anEnum) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNullableEnum$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [anEnum], ); - 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 AnEnum?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as AnEnum?; } Future echoAnotherNullableEnum(AnotherEnum? anotherEnum) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAnotherNullableEnum$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [anotherEnum], ); - 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 AnotherEnum?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as AnotherEnum?; } /// Returns passed in int. Future echoOptionalNullableInt([int? aNullableInt]) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoOptionalNullableInt$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aNullableInt], ); - 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?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as int?; } /// Returns the passed in string. Future echoNamedNullableString({String? aNullableString}) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoNamedNullableString$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aNullableString], ); - 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 String?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as String?; } /// A no-op function taking no arguments and returning no value, to sanity /// test basic asynchronous calling. Future noopAsync() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.noopAsync$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); } /// Returns passed in int asynchronously. Future echoAsyncInt(int anInt) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncInt$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [anInt], ); - 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 int?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as int; } /// Returns passed in double asynchronously. Future echoAsyncDouble(double aDouble) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncDouble$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aDouble], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as double; } /// Returns the passed in boolean asynchronously. Future echoAsyncBool(bool aBool) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncBool$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aBool], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as bool; } /// Returns the passed string asynchronously. Future echoAsyncString(String aString) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncString$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aString], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as String; } /// Returns the passed in Uint8List asynchronously. Future echoAsyncUint8List(Uint8List aUint8List) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncUint8List$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aUint8List], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as Uint8List; } /// Returns the passed in generic Object asynchronously. Future echoAsyncObject(Object anObject) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncObject$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [anObject], ); - 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]!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue!; } /// Returns the passed list, to test asynchronous serialization and deserialization. Future> echoAsyncList(List list) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [list], ); - 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 List?)!.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as List; } /// Returns the passed list, to test asynchronous serialization and deserialization. Future> echoAsyncEnumList(List enumList) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncEnumList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [enumList], ); - 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 List?)!.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as List).cast(); } /// Returns the passed list, to test asynchronous serialization and deserialization. Future> echoAsyncClassList( List classList, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncClassList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [classList], ); - 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 List?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as List).cast(); } /// Returns the passed map, to test asynchronous serialization and deserialization. Future> echoAsyncMap(Map map) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [map], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as Map; } /// Returns the passed map, to test asynchronous serialization and deserialization. Future> echoAsyncStringMap( Map stringMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncStringMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [stringMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map) + .cast(); } /// Returns the passed map, to test asynchronous serialization and deserialization. Future> echoAsyncIntMap(Map intMap) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncIntMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [intMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map).cast(); } /// Returns the passed map, to test asynchronous serialization and deserialization. Future> echoAsyncEnumMap( Map enumMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncEnumMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [enumMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map) + .cast(); } /// Returns the passed map, to test asynchronous serialization and deserialization. Future> echoAsyncClassMap( Map classMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncClassMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [classMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map) + .cast(); } /// Returns the passed enum, to test asynchronous serialization and deserialization. Future echoAsyncEnum(AnEnum anEnum) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncEnum$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [anEnum], ); - 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 AnEnum?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as AnEnum; } /// Returns the passed enum, to test asynchronous serialization and deserialization. Future echoAnotherAsyncEnum(AnotherEnum anotherEnum) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAnotherAsyncEnum$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [anotherEnum], ); - 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 AnotherEnum?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as AnotherEnum; } /// Responds with an error from an async function returning a value. Future throwAsyncError() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwAsyncError$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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 pigeonVar_replyList[0]; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue; } /// Responds with an error from an async void function. Future throwAsyncErrorFromVoid() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwAsyncErrorFromVoid$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); } /// Responds with a Flutter error from an async function returning a value. Future throwAsyncFlutterError() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.throwAsyncFlutterError$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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 pigeonVar_replyList[0]; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue; } /// Returns the passed object, to test async serialization and deserialization. Future echoAsyncAllTypes(AllTypes everything) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncAllTypes$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [everything], ); - 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 AllTypes?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as AllTypes; } /// Returns the passed object, to test serialization and deserialization. Future echoAsyncNullableAllNullableTypes( AllNullableTypes? everything, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableAllNullableTypes$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [everything], ); - 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 AllNullableTypes?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as AllNullableTypes?; } /// Returns the passed object, to test serialization and deserialization. @@ -3492,700 +2968,536 @@ class HostIntegrationCoreApi { echoAsyncNullableAllNullableTypesWithoutRecursion( AllNullableTypesWithoutRecursion? everything, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableAllNullableTypesWithoutRecursion$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [everything], ); - 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 AllNullableTypesWithoutRecursion?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as AllNullableTypesWithoutRecursion?; } /// Returns passed in int asynchronously. Future echoAsyncNullableInt(int? anInt) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableInt$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [anInt], ); - 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?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as int?; } /// Returns passed in double asynchronously. Future echoAsyncNullableDouble(double? aDouble) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableDouble$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aDouble], ); - 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 double?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as double?; } /// Returns the passed in boolean asynchronously. Future echoAsyncNullableBool(bool? aBool) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableBool$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aBool], ); - 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 bool?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as bool?; } /// Returns the passed string asynchronously. Future echoAsyncNullableString(String? aString) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableString$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aString], ); - 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 String?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as String?; } /// Returns the passed in Uint8List asynchronously. Future echoAsyncNullableUint8List(Uint8List? aUint8List) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableUint8List$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aUint8List], ); - 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?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as Uint8List?; } /// Returns the passed in generic Object asynchronously. Future echoAsyncNullableObject(Object? anObject) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableObject$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [anObject], ); - 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]; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue; } /// Returns the passed list, to test asynchronous serialization and deserialization. Future?> echoAsyncNullableList(List? list) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [list], ); - 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(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as List?; } /// Returns the passed list, to test asynchronous serialization and deserialization. Future?> echoAsyncNullableEnumList( List? enumList, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableEnumList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [enumList], ); - 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(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as List?)?.cast(); } /// Returns the passed list, to test asynchronous serialization and deserialization. Future?> echoAsyncNullableClassList( List? classList, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableClassList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [classList], ); - 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(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as List?)?.cast(); } /// Returns the passed map, to test asynchronous serialization and deserialization. Future?> echoAsyncNullableMap( Map? map, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [map], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as Map?; } /// Returns the passed map, to test asynchronous serialization and deserialization. Future?> echoAsyncNullableStringMap( Map? stringMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableStringMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [stringMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?) + ?.cast(); } /// Returns the passed map, to test asynchronous serialization and deserialization. Future?> echoAsyncNullableIntMap( Map? intMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableIntMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [intMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?)?.cast(); } /// Returns the passed map, to test asynchronous serialization and deserialization. Future?> echoAsyncNullableEnumMap( Map? enumMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableEnumMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [enumMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?) + ?.cast(); } /// Returns the passed map, to test asynchronous serialization and deserialization. Future?> echoAsyncNullableClassMap( Map? classMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableClassMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [classMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?) + ?.cast(); } /// Returns the passed enum, to test asynchronous serialization and deserialization. Future echoAsyncNullableEnum(AnEnum? anEnum) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAsyncNullableEnum$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [anEnum], ); - 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 AnEnum?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as AnEnum?; } /// Returns the passed enum, to test asynchronous serialization and deserialization. Future echoAnotherAsyncNullableEnum( AnotherEnum? anotherEnum, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.echoAnotherAsyncNullableEnum$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [anotherEnum], ); - 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 AnotherEnum?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as AnotherEnum?; } /// Returns true if the handler is run on a main thread, which should be /// true since there is no TaskQueue annotation. Future defaultIsMainThread() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.defaultIsMainThread$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as bool; } /// Returns true if the handler is run on a non-main thread, which should be /// true for any platform with TaskQueue support. Future taskQueueIsBackgroundThread() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.taskQueueIsBackgroundThread$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as bool; } Future callFlutterNoop() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterNoop$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); } Future callFlutterThrowError() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterThrowError$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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 pigeonVar_replyList[0]; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue; } Future callFlutterThrowErrorFromVoid() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterThrowErrorFromVoid$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); } Future callFlutterEchoAllTypes(AllTypes everything) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoAllTypes$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [everything], ); - 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 AllTypes?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as AllTypes; } Future callFlutterEchoAllNullableTypes( AllNullableTypes? everything, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoAllNullableTypes$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [everything], ); - 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 AllNullableTypes?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as AllNullableTypes?; } Future callFlutterSendMultipleNullableTypes( @@ -4193,65 +3505,48 @@ class HostIntegrationCoreApi { int? aNullableInt, String? aNullableString, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterSendMultipleNullableTypes$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aNullableBool, aNullableInt, aNullableString], ); - 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 AllNullableTypes?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as AllNullableTypes; } Future callFlutterEchoAllNullableTypesWithoutRecursion( AllNullableTypesWithoutRecursion? everything, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoAllNullableTypesWithoutRecursion$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [everything], ); - 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 AllNullableTypesWithoutRecursion?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as AllNullableTypesWithoutRecursion?; } Future @@ -4260,1382 +3555,993 @@ class HostIntegrationCoreApi { int? aNullableInt, String? aNullableString, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterSendMultipleNullableTypesWithoutRecursion$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aNullableBool, aNullableInt, aNullableString], ); - 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 AllNullableTypesWithoutRecursion?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as AllNullableTypesWithoutRecursion; } Future callFlutterEchoBool(bool aBool) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoBool$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aBool], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as bool; } Future callFlutterEchoInt(int anInt) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoInt$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [anInt], ); - 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 int?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as int; } Future callFlutterEchoDouble(double aDouble) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoDouble$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aDouble], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as double; } Future callFlutterEchoString(String aString) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoString$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aString], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as String; } Future callFlutterEchoUint8List(Uint8List list) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoUint8List$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [list], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as Uint8List; } Future> callFlutterEchoList(List list) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [list], ); - 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 List?)!.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as List; } Future> callFlutterEchoEnumList(List enumList) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoEnumList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [enumList], ); - 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 List?)!.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as List).cast(); } Future> callFlutterEchoClassList( List classList, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoClassList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [classList], ); - 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 List?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as List).cast(); } Future> callFlutterEchoNonNullEnumList( List enumList, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNonNullEnumList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [enumList], ); - 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 List?)!.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as List).cast(); } Future> callFlutterEchoNonNullClassList( List classList, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNonNullClassList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [classList], ); - 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 List?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as List).cast(); } Future> callFlutterEchoMap( Map map, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [map], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as Map; } Future> callFlutterEchoStringMap( Map stringMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoStringMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [stringMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map) + .cast(); } Future> callFlutterEchoIntMap(Map intMap) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoIntMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [intMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map).cast(); } Future> callFlutterEchoEnumMap( Map enumMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoEnumMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [enumMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map) + .cast(); } Future> callFlutterEchoClassMap( Map classMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoClassMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [classMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map) + .cast(); } Future> callFlutterEchoNonNullStringMap( Map stringMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNonNullStringMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [stringMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map) + .cast(); } Future> callFlutterEchoNonNullIntMap( Map intMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNonNullIntMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [intMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map).cast(); } Future> callFlutterEchoNonNullEnumMap( Map enumMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNonNullEnumMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [enumMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map) + .cast(); } Future> callFlutterEchoNonNullClassMap( Map classMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNonNullClassMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [classMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map) + .cast(); } Future callFlutterEchoEnum(AnEnum anEnum) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoEnum$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [anEnum], ); - 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 AnEnum?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as AnEnum; } Future callFlutterEchoAnotherEnum( AnotherEnum anotherEnum, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoAnotherEnum$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [anotherEnum], ); - 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 AnotherEnum?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as AnotherEnum; } Future callFlutterEchoNullableBool(bool? aBool) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableBool$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aBool], ); - 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 bool?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as bool?; } Future callFlutterEchoNullableInt(int? anInt) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableInt$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [anInt], ); - 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?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as int?; } Future callFlutterEchoNullableDouble(double? aDouble) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableDouble$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aDouble], ); - 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 double?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as double?; } Future callFlutterEchoNullableString(String? aString) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableString$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aString], ); - 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 String?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as String?; } Future callFlutterEchoNullableUint8List(Uint8List? list) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableUint8List$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [list], ); - 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?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as Uint8List?; } Future?> callFlutterEchoNullableList( List? list, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [list], ); - 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(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as List?; } Future?> callFlutterEchoNullableEnumList( List? enumList, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableEnumList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [enumList], ); - 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(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as List?)?.cast(); } Future?> callFlutterEchoNullableClassList( List? classList, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableClassList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [classList], ); - 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(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as List?)?.cast(); } Future?> callFlutterEchoNullableNonNullEnumList( List? enumList, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableNonNullEnumList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [enumList], ); - 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(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as List?)?.cast(); } Future?> callFlutterEchoNullableNonNullClassList( List? classList, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableNonNullClassList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [classList], ); - 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(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as List?)?.cast(); } Future?> callFlutterEchoNullableMap( Map? map, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [map], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as Map?; } Future?> callFlutterEchoNullableStringMap( Map? stringMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableStringMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [stringMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?) + ?.cast(); } Future?> callFlutterEchoNullableIntMap( Map? intMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableIntMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [intMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?)?.cast(); } Future?> callFlutterEchoNullableEnumMap( Map? enumMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableEnumMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [enumMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?) + ?.cast(); } Future?> callFlutterEchoNullableClassMap( Map? classMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableClassMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [classMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?) + ?.cast(); } Future?> callFlutterEchoNullableNonNullStringMap( Map? stringMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableNonNullStringMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [stringMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?) + ?.cast(); } Future?> callFlutterEchoNullableNonNullIntMap( Map? intMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableNonNullIntMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [intMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?)?.cast(); } Future?> callFlutterEchoNullableNonNullEnumMap( Map? enumMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableNonNullEnumMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [enumMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?) + ?.cast(); } Future?> callFlutterEchoNullableNonNullClassMap( Map? classMap, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableNonNullClassMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [classMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?) + ?.cast(); } Future callFlutterEchoNullableEnum(AnEnum? anEnum) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoNullableEnum$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [anEnum], ); - 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 AnEnum?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as AnEnum?; } Future callFlutterEchoAnotherNullableEnum( AnotherEnum? anotherEnum, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterEchoAnotherNullableEnum$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [anotherEnum], ); - 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 AnotherEnum?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as AnotherEnum?; } Future callFlutterSmallApiEchoString(String aString) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.callFlutterSmallApiEchoString$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aString], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as String; } } @@ -5841,8 +4747,7 @@ abstract class FlutterIntegrationCoreApi { ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.noop$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -5865,8 +4770,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.throwError$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -5889,8 +4793,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.throwErrorFromVoid$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -5913,8 +4816,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllTypes$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -5923,18 +4825,10 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllTypes was null.', - ); - final List args = (message as List?)!; - final AllTypes? arg_everything = (args[0] as AllTypes?); - assert( - arg_everything != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllTypes was null, expected non-null AllTypes.', - ); + final List args = message! as List; + final AllTypes arg_everything = args[0]! as AllTypes; try { - final AllTypes output = api.echoAllTypes(arg_everything!); + final AllTypes output = api.echoAllTypes(arg_everything); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -5947,8 +4841,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllNullableTypes$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -5957,13 +4850,8 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllNullableTypes was null.', - ); - final List args = (message as List?)!; - final AllNullableTypes? arg_everything = - (args[0] as AllNullableTypes?); + final List args = message! as List; + final AllNullableTypes? arg_everything = args[0] as AllNullableTypes?; try { final AllNullableTypes? output = api.echoAllNullableTypes( arg_everything, @@ -5980,8 +4868,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.sendMultipleNullableTypes$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -5990,14 +4877,10 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.sendMultipleNullableTypes was null.', - ); - final List args = (message as List?)!; - final bool? arg_aNullableBool = (args[0] as bool?); - final int? arg_aNullableInt = (args[1] as int?); - final String? arg_aNullableString = (args[2] as String?); + final List args = message! as List; + final bool? arg_aNullableBool = args[0] as bool?; + final int? arg_aNullableInt = args[1] as int?; + final String? arg_aNullableString = args[2] as String?; try { final AllNullableTypes output = api.sendMultipleNullableTypes( arg_aNullableBool, @@ -6016,8 +4899,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllNullableTypesWithoutRecursion$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6026,13 +4908,9 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAllNullableTypesWithoutRecursion was null.', - ); - final List args = (message as List?)!; + final List args = message! as List; final AllNullableTypesWithoutRecursion? arg_everything = - (args[0] as AllNullableTypesWithoutRecursion?); + args[0] as AllNullableTypesWithoutRecursion?; try { final AllNullableTypesWithoutRecursion? output = api .echoAllNullableTypesWithoutRecursion(arg_everything); @@ -6048,8 +4926,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.sendMultipleNullableTypesWithoutRecursion$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6058,14 +4935,10 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.sendMultipleNullableTypesWithoutRecursion was null.', - ); - final List args = (message as List?)!; - final bool? arg_aNullableBool = (args[0] as bool?); - final int? arg_aNullableInt = (args[1] as int?); - final String? arg_aNullableString = (args[2] as String?); + final List args = message! as List; + final bool? arg_aNullableBool = args[0] as bool?; + final int? arg_aNullableInt = args[1] as int?; + final String? arg_aNullableString = args[2] as String?; try { final AllNullableTypesWithoutRecursion output = api .sendMultipleNullableTypesWithoutRecursion( @@ -6085,8 +4958,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoBool$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6095,18 +4967,10 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoBool was null.', - ); - final List args = (message as List?)!; - final bool? arg_aBool = (args[0] as bool?); - assert( - arg_aBool != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoBool was null, expected non-null bool.', - ); + final List args = message! as List; + final bool arg_aBool = args[0]! as bool; try { - final bool output = api.echoBool(arg_aBool!); + final bool output = api.echoBool(arg_aBool); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6119,8 +4983,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoInt$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6129,18 +4992,10 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoInt was null.', - ); - final List args = (message as List?)!; - final int? arg_anInt = (args[0] as int?); - assert( - arg_anInt != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoInt was null, expected non-null int.', - ); + final List args = message! as List; + final int arg_anInt = args[0]! as int; try { - final int output = api.echoInt(arg_anInt!); + final int output = api.echoInt(arg_anInt); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6153,8 +5008,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoDouble$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6163,18 +5017,10 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoDouble was null.', - ); - final List args = (message as List?)!; - final double? arg_aDouble = (args[0] as double?); - assert( - arg_aDouble != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoDouble was null, expected non-null double.', - ); + final List args = message! as List; + final double arg_aDouble = args[0]! as double; try { - final double output = api.echoDouble(arg_aDouble!); + final double output = api.echoDouble(arg_aDouble); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6187,8 +5033,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoString$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6197,18 +5042,10 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoString was null.', - ); - final List args = (message as List?)!; - final String? arg_aString = (args[0] as String?); - assert( - arg_aString != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoString was null, expected non-null String.', - ); + final List args = message! as List; + final String arg_aString = args[0]! as String; try { - final String output = api.echoString(arg_aString!); + final String output = api.echoString(arg_aString); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6221,8 +5058,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoUint8List$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6231,18 +5067,10 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoUint8List was null.', - ); - final List args = (message as List?)!; - final Uint8List? arg_list = (args[0] as Uint8List?); - assert( - arg_list != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoUint8List was null, expected non-null Uint8List.', - ); + final List args = message! as List; + final Uint8List arg_list = args[0]! as Uint8List; try { - final Uint8List output = api.echoUint8List(arg_list!); + final Uint8List output = api.echoUint8List(arg_list); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6255,8 +5083,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoList$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6265,19 +5092,10 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoList was null.', - ); - final List args = (message as List?)!; - final List? arg_list = (args[0] as List?) - ?.cast(); - assert( - arg_list != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoList was null, expected non-null List.', - ); + final List args = message! as List; + final List arg_list = args[0]! as List; try { - final List output = api.echoList(arg_list!); + final List output = api.echoList(arg_list); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6290,8 +5108,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnumList$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6300,19 +5117,11 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnumList was null.', - ); - final List args = (message as List?)!; - final List? arg_enumList = (args[0] as List?) - ?.cast(); - assert( - arg_enumList != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnumList was null, expected non-null List.', - ); + final List args = message! as List; + final List arg_enumList = (args[0]! as List) + .cast(); try { - final List output = api.echoEnumList(arg_enumList!); + final List output = api.echoEnumList(arg_enumList); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6325,8 +5134,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoClassList$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6335,20 +5143,12 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoClassList was null.', - ); - final List args = (message as List?)!; - final List? arg_classList = - (args[0] as List?)?.cast(); - assert( - arg_classList != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoClassList was null, expected non-null List.', - ); + final List args = message! as List; + final List arg_classList = + (args[0]! as List).cast(); try { final List output = api.echoClassList( - arg_classList!, + arg_classList, ); return wrapResponse(result: output); } on PlatformException catch (e) { @@ -6362,8 +5162,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullEnumList$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6372,19 +5171,11 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullEnumList was null.', - ); - final List args = (message as List?)!; - final List? arg_enumList = (args[0] as List?) - ?.cast(); - assert( - arg_enumList != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullEnumList was null, expected non-null List.', - ); + final List args = message! as List; + final List arg_enumList = (args[0]! as List) + .cast(); try { - final List output = api.echoNonNullEnumList(arg_enumList!); + final List output = api.echoNonNullEnumList(arg_enumList); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6397,8 +5188,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullClassList$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6407,20 +5197,12 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullClassList was null.', - ); - final List args = (message as List?)!; - final List? arg_classList = - (args[0] as List?)?.cast(); - assert( - arg_classList != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullClassList was null, expected non-null List.', - ); + final List args = message! as List; + final List arg_classList = + (args[0]! as List).cast(); try { final List output = api.echoNonNullClassList( - arg_classList!, + arg_classList, ); return wrapResponse(result: output); } on PlatformException catch (e) { @@ -6434,8 +5216,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoMap$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6444,19 +5225,11 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoMap was null.', - ); - final List args = (message as List?)!; - final Map? arg_map = - (args[0] as Map?)?.cast(); - assert( - arg_map != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoMap was null, expected non-null Map.', - ); + final List args = message! as List; + final Map arg_map = + args[0]! as Map; try { - final Map output = api.echoMap(arg_map!); + final Map output = api.echoMap(arg_map); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6469,8 +5242,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoStringMap$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6479,20 +5251,12 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoStringMap was null.', - ); - final List args = (message as List?)!; - final Map? arg_stringMap = - (args[0] as Map?)?.cast(); - assert( - arg_stringMap != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoStringMap was null, expected non-null Map.', - ); + final List args = message! as List; + final Map arg_stringMap = + (args[0]! as Map).cast(); try { final Map output = api.echoStringMap( - arg_stringMap!, + arg_stringMap, ); return wrapResponse(result: output); } on PlatformException catch (e) { @@ -6506,8 +5270,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoIntMap$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6516,19 +5279,11 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoIntMap was null.', - ); - final List args = (message as List?)!; - final Map? arg_intMap = - (args[0] as Map?)?.cast(); - assert( - arg_intMap != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoIntMap was null, expected non-null Map.', - ); + final List args = message! as List; + final Map arg_intMap = (args[0]! as Map) + .cast(); try { - final Map output = api.echoIntMap(arg_intMap!); + final Map output = api.echoIntMap(arg_intMap); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6541,8 +5296,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnumMap$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6551,19 +5305,11 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnumMap was null.', - ); - final List args = (message as List?)!; - final Map? arg_enumMap = - (args[0] as Map?)?.cast(); - assert( - arg_enumMap != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnumMap was null, expected non-null Map.', - ); + final List args = message! as List; + final Map arg_enumMap = + (args[0]! as Map).cast(); try { - final Map output = api.echoEnumMap(arg_enumMap!); + final Map output = api.echoEnumMap(arg_enumMap); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6576,8 +5322,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoClassMap$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6586,21 +5331,13 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoClassMap was null.', - ); - final List args = (message as List?)!; - final Map? arg_classMap = - (args[0] as Map?) - ?.cast(); - assert( - arg_classMap != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoClassMap was null, expected non-null Map.', - ); + final List args = message! as List; + final Map arg_classMap = + (args[0]! as Map) + .cast(); try { final Map output = api.echoClassMap( - arg_classMap!, + arg_classMap, ); return wrapResponse(result: output); } on PlatformException catch (e) { @@ -6614,8 +5351,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullStringMap$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6624,20 +5360,12 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullStringMap was null.', - ); - final List args = (message as List?)!; - final Map? arg_stringMap = - (args[0] as Map?)?.cast(); - assert( - arg_stringMap != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullStringMap was null, expected non-null Map.', - ); + final List args = message! as List; + final Map arg_stringMap = + (args[0]! as Map).cast(); try { final Map output = api.echoNonNullStringMap( - arg_stringMap!, + arg_stringMap, ); return wrapResponse(result: output); } on PlatformException catch (e) { @@ -6651,8 +5379,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullIntMap$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6661,19 +5388,11 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullIntMap was null.', - ); - final List args = (message as List?)!; - final Map? arg_intMap = (args[0] as Map?) - ?.cast(); - assert( - arg_intMap != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullIntMap was null, expected non-null Map.', - ); + final List args = message! as List; + final Map arg_intMap = (args[0]! as Map) + .cast(); try { - final Map output = api.echoNonNullIntMap(arg_intMap!); + final Map output = api.echoNonNullIntMap(arg_intMap); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6686,8 +5405,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullEnumMap$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6696,20 +5414,12 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullEnumMap was null.', - ); - final List args = (message as List?)!; - final Map? arg_enumMap = - (args[0] as Map?)?.cast(); - assert( - arg_enumMap != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullEnumMap was null, expected non-null Map.', - ); + final List args = message! as List; + final Map arg_enumMap = + (args[0]! as Map).cast(); try { final Map output = api.echoNonNullEnumMap( - arg_enumMap!, + arg_enumMap, ); return wrapResponse(result: output); } on PlatformException catch (e) { @@ -6723,8 +5433,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullClassMap$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6733,21 +5442,12 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullClassMap was null.', - ); - final List args = (message as List?)!; - final Map? arg_classMap = - (args[0] as Map?) - ?.cast(); - assert( - arg_classMap != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNonNullClassMap was null, expected non-null Map.', - ); + final List args = message! as List; + final Map arg_classMap = + (args[0]! as Map).cast(); try { final Map output = api.echoNonNullClassMap( - arg_classMap!, + arg_classMap, ); return wrapResponse(result: output); } on PlatformException catch (e) { @@ -6761,8 +5461,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnum$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6771,18 +5470,10 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnum was null.', - ); - final List args = (message as List?)!; - final AnEnum? arg_anEnum = (args[0] as AnEnum?); - assert( - arg_anEnum != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoEnum was null, expected non-null AnEnum.', - ); + final List args = message! as List; + final AnEnum arg_anEnum = args[0]! as AnEnum; try { - final AnEnum output = api.echoEnum(arg_anEnum!); + final AnEnum output = api.echoEnum(arg_anEnum); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6795,8 +5486,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAnotherEnum$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6805,18 +5495,10 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAnotherEnum was null.', - ); - final List args = (message as List?)!; - final AnotherEnum? arg_anotherEnum = (args[0] as AnotherEnum?); - assert( - arg_anotherEnum != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAnotherEnum was null, expected non-null AnotherEnum.', - ); + final List args = message! as List; + final AnotherEnum arg_anotherEnum = args[0]! as AnotherEnum; try { - final AnotherEnum output = api.echoAnotherEnum(arg_anotherEnum!); + final AnotherEnum output = api.echoAnotherEnum(arg_anotherEnum); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -6829,8 +5511,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableBool$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6839,12 +5520,8 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableBool was null.', - ); - final List args = (message as List?)!; - final bool? arg_aBool = (args[0] as bool?); + final List args = message! as List; + final bool? arg_aBool = args[0] as bool?; try { final bool? output = api.echoNullableBool(arg_aBool); return wrapResponse(result: output); @@ -6859,8 +5536,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableInt$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6869,12 +5545,8 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableInt was null.', - ); - final List args = (message as List?)!; - final int? arg_anInt = (args[0] as int?); + final List args = message! as List; + final int? arg_anInt = args[0] as int?; try { final int? output = api.echoNullableInt(arg_anInt); return wrapResponse(result: output); @@ -6889,8 +5561,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableDouble$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6899,12 +5570,8 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableDouble was null.', - ); - final List args = (message as List?)!; - final double? arg_aDouble = (args[0] as double?); + final List args = message! as List; + final double? arg_aDouble = args[0] as double?; try { final double? output = api.echoNullableDouble(arg_aDouble); return wrapResponse(result: output); @@ -6919,8 +5586,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableString$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6929,12 +5595,8 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableString was null.', - ); - final List args = (message as List?)!; - final String? arg_aString = (args[0] as String?); + final List args = message! as List; + final String? arg_aString = args[0] as String?; try { final String? output = api.echoNullableString(arg_aString); return wrapResponse(result: output); @@ -6949,8 +5611,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableUint8List$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6959,12 +5620,8 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableUint8List was null.', - ); - final List args = (message as List?)!; - final Uint8List? arg_list = (args[0] as Uint8List?); + final List args = message! as List; + final Uint8List? arg_list = args[0] as Uint8List?; try { final Uint8List? output = api.echoNullableUint8List(arg_list); return wrapResponse(result: output); @@ -6979,8 +5636,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableList$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6989,13 +5645,8 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableList was null.', - ); - final List args = (message as List?)!; - final List? arg_list = (args[0] as List?) - ?.cast(); + final List args = message! as List; + final List? arg_list = args[0] as List?; try { final List? output = api.echoNullableList(arg_list); return wrapResponse(result: output); @@ -7010,8 +5661,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableEnumList$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7020,11 +5670,7 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableEnumList was null.', - ); - final List args = (message as List?)!; + final List args = message! as List; final List? arg_enumList = (args[0] as List?) ?.cast(); try { @@ -7043,8 +5689,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableClassList$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7053,11 +5698,7 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableClassList was null.', - ); - final List args = (message as List?)!; + final List args = message! as List; final List? arg_classList = (args[0] as List?)?.cast(); try { @@ -7076,8 +5717,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullEnumList$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7086,11 +5726,7 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullEnumList was null.', - ); - final List args = (message as List?)!; + final List args = message! as List; final List? arg_enumList = (args[0] as List?) ?.cast(); try { @@ -7109,8 +5745,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullClassList$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7119,11 +5754,7 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullClassList was null.', - ); - final List args = (message as List?)!; + final List args = message! as List; final List? arg_classList = (args[0] as List?)?.cast(); try { @@ -7141,8 +5772,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableMap$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7151,13 +5781,9 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableMap was null.', - ); - final List args = (message as List?)!; + final List args = message! as List; final Map? arg_map = - (args[0] as Map?)?.cast(); + args[0] as Map?; try { final Map? output = api.echoNullableMap(arg_map); return wrapResponse(result: output); @@ -7172,8 +5798,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableStringMap$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7182,11 +5807,7 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableStringMap was null.', - ); - final List args = (message as List?)!; + final List args = message! as List; final Map? arg_stringMap = (args[0] as Map?)?.cast(); try { @@ -7205,8 +5826,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableIntMap$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7215,11 +5835,7 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableIntMap was null.', - ); - final List args = (message as List?)!; + final List args = message! as List; final Map? arg_intMap = (args[0] as Map?)?.cast(); try { @@ -7236,8 +5852,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableEnumMap$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7246,11 +5861,7 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableEnumMap was null.', - ); - final List args = (message as List?)!; + final List args = message! as List; final Map? arg_enumMap = (args[0] as Map?)?.cast(); try { @@ -7269,8 +5880,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableClassMap$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7279,11 +5889,7 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableClassMap was null.', - ); - final List args = (message as List?)!; + final List args = message! as List; final Map? arg_classMap = (args[0] as Map?) ?.cast(); @@ -7302,8 +5908,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullStringMap$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7312,11 +5917,7 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullStringMap was null.', - ); - final List args = (message as List?)!; + final List args = message! as List; final Map? arg_stringMap = (args[0] as Map?)?.cast(); try { @@ -7334,8 +5935,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullIntMap$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7344,11 +5944,7 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullIntMap was null.', - ); - final List args = (message as List?)!; + final List args = message! as List; final Map? arg_intMap = (args[0] as Map?) ?.cast(); try { @@ -7367,8 +5963,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullEnumMap$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7377,11 +5972,7 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullEnumMap was null.', - ); - final List args = (message as List?)!; + final List args = message! as List; final Map? arg_enumMap = (args[0] as Map?)?.cast(); try { @@ -7400,8 +5991,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullClassMap$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7410,11 +6000,7 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableNonNullClassMap was null.', - ); - final List args = (message as List?)!; + final List args = message! as List; final Map? arg_classMap = (args[0] as Map?) ?.cast(); @@ -7433,8 +6019,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableEnum$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7443,12 +6028,8 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoNullableEnum was null.', - ); - final List args = (message as List?)!; - final AnEnum? arg_anEnum = (args[0] as AnEnum?); + final List args = message! as List; + final AnEnum? arg_anEnum = args[0] as AnEnum?; try { final AnEnum? output = api.echoNullableEnum(arg_anEnum); return wrapResponse(result: output); @@ -7463,8 +6044,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAnotherNullableEnum$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7473,12 +6053,8 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAnotherNullableEnum was null.', - ); - final List args = (message as List?)!; - final AnotherEnum? arg_anotherEnum = (args[0] as AnotherEnum?); + final List args = message! as List; + final AnotherEnum? arg_anotherEnum = args[0] as AnotherEnum?; try { final AnotherEnum? output = api.echoAnotherNullableEnum( arg_anotherEnum, @@ -7495,8 +6071,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.noopAsync$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7519,8 +6094,7 @@ abstract class FlutterIntegrationCoreApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAsyncString$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7529,18 +6103,10 @@ abstract class FlutterIntegrationCoreApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAsyncString was null.', - ); - final List args = (message as List?)!; - final String? arg_aString = (args[0] as String?); - assert( - arg_aString != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAsyncString was null, expected non-null String.', - ); + final List args = message! as List; + final String arg_aString = args[0]! as String; try { - final String output = await api.echoAsyncString(arg_aString!); + final String output = await api.echoAsyncString(arg_aString); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -7574,28 +6140,21 @@ class HostTrivialApi { final String pigeonVar_messageChannelSuffix; Future noop() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostTrivialApi.noop$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); } } @@ -7618,60 +6177,42 @@ class HostSmallApi { final String pigeonVar_messageChannelSuffix; Future echo(String aString) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.echo$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aString], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as String; } Future voidVoid() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.voidVoid$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); } } @@ -7692,8 +6233,7 @@ abstract class FlutterSmallApi { ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoWrappedList$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7702,18 +6242,10 @@ abstract class FlutterSmallApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoWrappedList was null.', - ); - final List args = (message as List?)!; - final TestMessage? arg_msg = (args[0] as TestMessage?); - assert( - arg_msg != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoWrappedList was null, expected non-null TestMessage.', - ); + final List args = message! as List; + final TestMessage arg_msg = args[0]! as TestMessage; try { - final TestMessage output = api.echoWrappedList(arg_msg!); + final TestMessage output = api.echoWrappedList(arg_msg); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -7726,8 +6258,7 @@ abstract class FlutterSmallApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoString$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -7736,18 +6267,10 @@ abstract class FlutterSmallApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoString was null.', - ); - final List args = (message as List?)!; - final String? arg_aString = (args[0] as String?); - assert( - arg_aString != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoString was null, expected non-null String.', - ); + final List args = message! as List; + final String arg_aString = args[0]! as String; try { - final String output = api.echoString(arg_aString!); + final String output = api.echoString(arg_aString); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/enum.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/enum.gen.dart index 7a652d525b23..06185b61738e 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/enum.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/enum.gen.dart @@ -4,19 +4,38 @@ // // Autogenerated from Pigeon, 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 +// ignore_for_file: unused_import, unused_shown_name +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, omit_obvious_local_variable_types, unnecessary_import, no_leading_underscores_for_local_identifiers import 'dart:async'; -import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; +import 'dart:typed_data' show Float64List, Int32List, Int64List; -import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; +import 'package:meta/meta.dart' show immutable, protected, visibleForTesting; -PlatformException _createConnectionError(String channelName) { - return PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel: "$channelName".', - ); +Object? _extractReplyValueOrThrow( + List? replyList, + String channelName, { + required bool isNullValid, +}) { + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel: "$channelName".', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (!isNullValid && (replyList.isNotEmpty && replyList[0] == null)) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } + return replyList.firstOrNull; } List wrapResponse({ @@ -34,6 +53,15 @@ List wrapResponse({ } bool _deepEquals(Object? a, Object? b) { + if (identical(a, b)) { + return true; + } + if (a is double && b is double) { + if (a.isNaN && b.isNaN) { + return true; + } + return a == b; + } if (a is List && b is List) { return a.length == b.length && a.indexed.every( @@ -41,16 +69,52 @@ bool _deepEquals(Object? a, Object? b) { ); } if (a is Map && b is Map) { - return a.length == b.length && - a.entries.every( - (MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key]), - ); + if (a.length != b.length) { + return false; + } + for (final MapEntry entryA in a.entries) { + bool found = false; + for (final MapEntry entryB in b.entries) { + if (_deepEquals(entryA.key, entryB.key)) { + if (_deepEquals(entryA.value, entryB.value)) { + found = true; + break; + } else { + return false; + } + } + } + if (!found) { + return false; + } + } + return true; } return a == b; } +int _deepHash(Object? value) { + if (value is List) { + return Object.hashAll(value.map(_deepHash)); + } + if (value is Map) { + int result = 0; + for (final MapEntry entry in value.entries) { + result += (_deepHash(entry.key) * 31) ^ _deepHash(entry.value); + } + return result; + } + if (value is double && value.isNaN) { + // Normalize NaN to a consistent hash. + return 0x7FF8000000000000.hashCode; + } + if (value is double && value == 0.0) { + // Normalize -0.0 to 0.0 so they have the same hash code. + return 0.0.hashCode; + } + return value.hashCode; +} + /// This comment is to test enum documentation comments. enum EnumState { /// This comment is to test enum member (Pending) documentation comments. @@ -95,12 +159,12 @@ class DataWithEnum { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(state, other.state); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } class _PigeonCodec extends StandardMessageCodec { @@ -125,7 +189,7 @@ class _PigeonCodec extends StandardMessageCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 129: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : EnumState.values[value]; case 130: return DataWithEnum.decode(readValue(buffer)!); @@ -155,35 +219,24 @@ class EnumApi2Host { /// This comment is to test method documentation comments. Future echo(DataWithEnum data) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.EnumApi2Host.echo$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [data], ); - 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 DataWithEnum?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as DataWithEnum; } } @@ -203,8 +256,7 @@ abstract class EnumApi2Flutter { ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.EnumApi2Flutter.echo$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -213,18 +265,10 @@ abstract class EnumApi2Flutter { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.EnumApi2Flutter.echo was null.', - ); - final List args = (message as List?)!; - final DataWithEnum? arg_data = (args[0] as DataWithEnum?); - assert( - arg_data != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.EnumApi2Flutter.echo was null, expected non-null DataWithEnum.', - ); + final List args = message! as List; + final DataWithEnum arg_data = args[0]! as DataWithEnum; try { - final DataWithEnum output = api.echo(arg_data!); + final DataWithEnum output = api.echo(arg_data); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_tests.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_tests.gen.dart index 90b95c9d3d15..814f9efc5f50 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_tests.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_tests.gen.dart @@ -4,15 +4,25 @@ // // Autogenerated from Pigeon, 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 +// ignore_for_file: unused_import, unused_shown_name +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, omit_obvious_local_variable_types, unnecessary_import, no_leading_underscores_for_local_identifiers import 'dart:async'; -import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; +import 'dart:typed_data' show Float64List, Int32List, Int64List; -import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; +import 'package:meta/meta.dart' show immutable, protected, visibleForTesting; bool _deepEquals(Object? a, Object? b) { + if (identical(a, b)) { + return true; + } + if (a is double && b is double) { + if (a.isNaN && b.isNaN) { + return true; + } + return a == b; + } if (a is List && b is List) { return a.length == b.length && a.indexed.every( @@ -20,16 +30,52 @@ bool _deepEquals(Object? a, Object? b) { ); } if (a is Map && b is Map) { - return a.length == b.length && - a.entries.every( - (MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key]), - ); + if (a.length != b.length) { + return false; + } + for (final MapEntry entryA in a.entries) { + bool found = false; + for (final MapEntry entryB in b.entries) { + if (_deepEquals(entryA.key, entryB.key)) { + if (_deepEquals(entryA.value, entryB.value)) { + found = true; + break; + } else { + return false; + } + } + } + if (!found) { + return false; + } + } + return true; } return a == b; } +int _deepHash(Object? value) { + if (value is List) { + return Object.hashAll(value.map(_deepHash)); + } + if (value is Map) { + int result = 0; + for (final MapEntry entry in value.entries) { + result += (_deepHash(entry.key) * 31) ^ _deepHash(entry.value); + } + return result; + } + if (value is double && value.isNaN) { + // Normalize NaN to a consistent hash. + return 0x7FF8000000000000.hashCode; + } + if (value is double && value == 0.0) { + // Normalize -0.0 to 0.0 so they have the same hash code. + return 0.0.hashCode; + } + return value.hashCode; +} + enum EventEnum { one, two, three, fortyTwo, fourHundredTwentyTwo } enum AnotherEventEnum { justInCase } @@ -194,7 +240,7 @@ class EventAllNullableTypes { doubleList: (result[16] as List?)?.cast(), boolList: (result[17] as List?)?.cast(), enumList: (result[18] as List?)?.cast(), - objectList: (result[19] as List?)?.cast(), + objectList: result[19] as List?, listList: (result[20] as List?)?.cast?>(), mapList: (result[21] as List?)?.cast?>(), recursiveClassList: (result[22] as List?) @@ -205,8 +251,7 @@ class EventAllNullableTypes { intMap: (result[25] as Map?)?.cast(), enumMap: (result[26] as Map?) ?.cast(), - objectMap: (result[27] as Map?) - ?.cast(), + objectMap: result[27] as Map?, listMap: (result[28] as Map?) ?.cast?>(), mapMap: (result[29] as Map?) @@ -225,12 +270,42 @@ class EventAllNullableTypes { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(aNullableBool, other.aNullableBool) && + _deepEquals(aNullableInt, other.aNullableInt) && + _deepEquals(aNullableInt64, other.aNullableInt64) && + _deepEquals(aNullableDouble, other.aNullableDouble) && + _deepEquals(aNullableByteArray, other.aNullableByteArray) && + _deepEquals(aNullable4ByteArray, other.aNullable4ByteArray) && + _deepEquals(aNullable8ByteArray, other.aNullable8ByteArray) && + _deepEquals(aNullableFloatArray, other.aNullableFloatArray) && + _deepEquals(aNullableEnum, other.aNullableEnum) && + _deepEquals(anotherNullableEnum, other.anotherNullableEnum) && + _deepEquals(aNullableString, other.aNullableString) && + _deepEquals(aNullableObject, other.aNullableObject) && + _deepEquals(allNullableTypes, other.allNullableTypes) && + _deepEquals(list, other.list) && + _deepEquals(stringList, other.stringList) && + _deepEquals(intList, other.intList) && + _deepEquals(doubleList, other.doubleList) && + _deepEquals(boolList, other.boolList) && + _deepEquals(enumList, other.enumList) && + _deepEquals(objectList, other.objectList) && + _deepEquals(listList, other.listList) && + _deepEquals(mapList, other.mapList) && + _deepEquals(recursiveClassList, other.recursiveClassList) && + _deepEquals(map, other.map) && + _deepEquals(stringMap, other.stringMap) && + _deepEquals(intMap, other.intMap) && + _deepEquals(enumMap, other.enumMap) && + _deepEquals(objectMap, other.objectMap) && + _deepEquals(listMap, other.listMap) && + _deepEquals(mapMap, other.mapMap) && + _deepEquals(recursiveClassMap, other.recursiveClassMap); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } sealed class PlatformEvent {} @@ -262,12 +337,12 @@ class IntEvent extends PlatformEvent { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(value, other.value); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } class StringEvent extends PlatformEvent { @@ -297,12 +372,12 @@ class StringEvent extends PlatformEvent { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(value, other.value); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } class BoolEvent extends PlatformEvent { @@ -332,12 +407,12 @@ class BoolEvent extends PlatformEvent { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(value, other.value); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } class DoubleEvent extends PlatformEvent { @@ -367,12 +442,12 @@ class DoubleEvent extends PlatformEvent { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(value, other.value); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } class ObjectsEvent extends PlatformEvent { @@ -402,12 +477,12 @@ class ObjectsEvent extends PlatformEvent { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(value, other.value); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } class EnumEvent extends PlatformEvent { @@ -437,12 +512,12 @@ class EnumEvent extends PlatformEvent { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(value, other.value); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } class ClassEvent extends PlatformEvent { @@ -472,12 +547,12 @@ class ClassEvent extends PlatformEvent { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(value, other.value); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } class _PigeonCodec extends StandardMessageCodec { @@ -526,10 +601,10 @@ class _PigeonCodec extends StandardMessageCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 129: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : EventEnum.values[value]; case 130: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : AnotherEventEnum.values[value]; case 131: return EventAllNullableTypes.decode(readValue(buffer)!); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_without_classes_tests.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_without_classes_tests.gen.dart index 052a18b0019f..80e794008d43 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_without_classes_tests.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/event_channel_without_classes_tests.gen.dart @@ -4,13 +4,14 @@ // // Autogenerated from Pigeon, 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 +// ignore_for_file: unused_import, unused_shown_name +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, omit_obvious_local_variable_types, unnecessary_import, no_leading_underscores_for_local_identifiers import 'dart:async'; -import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; +import 'dart:typed_data' show Float64List, Int32List, Int64List; -import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; +import 'package:meta/meta.dart' show immutable, protected, visibleForTesting; class _PigeonCodec extends StandardMessageCodec { const _PigeonCodec(); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/flutter_unittests.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/flutter_unittests.gen.dart index b72f676e84df..f34e47cf80b1 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/flutter_unittests.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/flutter_unittests.gen.dart @@ -4,22 +4,50 @@ // // Autogenerated from Pigeon, 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 +// ignore_for_file: unused_import, unused_shown_name +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, omit_obvious_local_variable_types, unnecessary_import, no_leading_underscores_for_local_identifiers import 'dart:async'; -import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; +import 'dart:typed_data' show Float64List, Int32List, Int64List; -import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; - -PlatformException _createConnectionError(String channelName) { - return PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel: "$channelName".', - ); +import 'package:meta/meta.dart' show immutable, protected, visibleForTesting; + +Object? _extractReplyValueOrThrow( + List? replyList, + String channelName, { + required bool isNullValid, +}) { + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel: "$channelName".', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (!isNullValid && (replyList.isNotEmpty && replyList[0] == null)) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } + return replyList.firstOrNull; } bool _deepEquals(Object? a, Object? b) { + if (identical(a, b)) { + return true; + } + if (a is double && b is double) { + if (a.isNaN && b.isNaN) { + return true; + } + return a == b; + } if (a is List && b is List) { return a.length == b.length && a.indexed.every( @@ -27,16 +55,52 @@ bool _deepEquals(Object? a, Object? b) { ); } if (a is Map && b is Map) { - return a.length == b.length && - a.entries.every( - (MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key]), - ); + if (a.length != b.length) { + return false; + } + for (final MapEntry entryA in a.entries) { + bool found = false; + for (final MapEntry entryB in b.entries) { + if (_deepEquals(entryA.key, entryB.key)) { + if (_deepEquals(entryA.value, entryB.value)) { + found = true; + break; + } else { + return false; + } + } + } + if (!found) { + return false; + } + } + return true; } return a == b; } +int _deepHash(Object? value) { + if (value is List) { + return Object.hashAll(value.map(_deepHash)); + } + if (value is Map) { + int result = 0; + for (final MapEntry entry in value.entries) { + result += (_deepHash(entry.key) * 31) ^ _deepHash(entry.value); + } + return result; + } + if (value is double && value.isNaN) { + // Normalize NaN to a consistent hash. + return 0x7FF8000000000000.hashCode; + } + if (value is double && value == 0.0) { + // Normalize -0.0 to 0.0 so they have the same hash code. + return 0.0.hashCode; + } + return value.hashCode; +} + class FlutterSearchRequest { FlutterSearchRequest({this.query}); @@ -64,12 +128,12 @@ class FlutterSearchRequest { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(query, other.query); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } class FlutterSearchReply { @@ -104,12 +168,12 @@ class FlutterSearchReply { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(result, other.result) && _deepEquals(error, other.error); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } class FlutterSearchRequests { @@ -139,12 +203,12 @@ class FlutterSearchRequests { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(requests, other.requests); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } class FlutterSearchReplies { @@ -174,12 +238,12 @@ class FlutterSearchReplies { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(replies, other.replies); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } class _PigeonCodec extends StandardMessageCodec { @@ -239,130 +303,86 @@ class Api { final String pigeonVar_messageChannelSuffix; Future search(FlutterSearchRequest request) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.Api.search$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [request], ); - 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 FlutterSearchReply?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as FlutterSearchReply; } Future doSearches(FlutterSearchRequests request) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.Api.doSearches$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [request], ); - 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 FlutterSearchReplies?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as FlutterSearchReplies; } Future echo(FlutterSearchRequests requests) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.Api.echo$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [requests], ); - 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 FlutterSearchRequests?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as FlutterSearchRequests; } Future anInt(int value) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.Api.anInt$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [value], ); - 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 int?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as int; } } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/message.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/message.gen.dart index 1d708172886f..5bccedeb9f2f 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/message.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/message.gen.dart @@ -4,19 +4,38 @@ // // Autogenerated from Pigeon, 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 +// ignore_for_file: unused_import, unused_shown_name +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, omit_obvious_local_variable_types, unnecessary_import, no_leading_underscores_for_local_identifiers import 'dart:async'; -import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; +import 'dart:typed_data' show Float64List, Int32List, Int64List; -import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; +import 'package:meta/meta.dart' show immutable, protected, visibleForTesting; -PlatformException _createConnectionError(String channelName) { - return PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel: "$channelName".', - ); +Object? _extractReplyValueOrThrow( + List? replyList, + String channelName, { + required bool isNullValid, +}) { + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel: "$channelName".', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (!isNullValid && (replyList.isNotEmpty && replyList[0] == null)) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } + return replyList.firstOrNull; } List wrapResponse({ @@ -34,6 +53,15 @@ List wrapResponse({ } bool _deepEquals(Object? a, Object? b) { + if (identical(a, b)) { + return true; + } + if (a is double && b is double) { + if (a.isNaN && b.isNaN) { + return true; + } + return a == b; + } if (a is List && b is List) { return a.length == b.length && a.indexed.every( @@ -41,16 +69,52 @@ bool _deepEquals(Object? a, Object? b) { ); } if (a is Map && b is Map) { - return a.length == b.length && - a.entries.every( - (MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key]), - ); + if (a.length != b.length) { + return false; + } + for (final MapEntry entryA in a.entries) { + bool found = false; + for (final MapEntry entryB in b.entries) { + if (_deepEquals(entryA.key, entryB.key)) { + if (_deepEquals(entryA.value, entryB.value)) { + found = true; + break; + } else { + return false; + } + } + } + if (!found) { + return false; + } + } + return true; } return a == b; } +int _deepHash(Object? value) { + if (value is List) { + return Object.hashAll(value.map(_deepHash)); + } + if (value is Map) { + int result = 0; + for (final MapEntry entry in value.entries) { + result += (_deepHash(entry.key) * 31) ^ _deepHash(entry.value); + } + return result; + } + if (value is double && value.isNaN) { + // Normalize NaN to a consistent hash. + return 0x7FF8000000000000.hashCode; + } + if (value is double && value == 0.0) { + // Normalize -0.0 to 0.0 so they have the same hash code. + return 0.0.hashCode; + } + return value.hashCode; +} + /// This comment is to test enum documentation comments. /// /// This comment also tests multiple line comments. @@ -101,12 +165,14 @@ class MessageSearchRequest { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(query, other.query) && + _deepEquals(anInt, other.anInt) && + _deepEquals(aBool, other.aBool); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } /// This comment is to test class documentation comments. @@ -150,12 +216,14 @@ class MessageSearchReply { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(result, other.result) && + _deepEquals(error, other.error) && + _deepEquals(state, other.state); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } /// This comment is to test class documentation comments. @@ -187,12 +255,12 @@ class MessageNested { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(request, other.request); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } class _PigeonCodec extends StandardMessageCodec { @@ -223,7 +291,7 @@ class _PigeonCodec extends StandardMessageCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 129: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : MessageRequestState.values[value]; case 130: return MessageSearchRequest.decode(readValue(buffer)!); @@ -261,61 +329,43 @@ class MessageApi { /// /// This comment also tests multiple line comments. Future initialize() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.initialize$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); } /// This comment is to test method documentation comments. Future search(MessageSearchRequest request) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [request], ); - 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 MessageSearchReply?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as MessageSearchReply; } } @@ -341,35 +391,24 @@ class MessageNestedApi { /// /// This comment also tests multiple line comments. Future search(MessageNested nested) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.MessageNestedApi.search$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [nested], ); - 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 MessageSearchReply?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as MessageSearchReply; } } @@ -389,8 +428,7 @@ abstract class MessageFlutterSearchApi { ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.MessageFlutterSearchApi.search$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -399,19 +437,11 @@ abstract class MessageFlutterSearchApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageFlutterSearchApi.search was null.', - ); - final List args = (message as List?)!; - final MessageSearchRequest? arg_request = - (args[0] as MessageSearchRequest?); - assert( - arg_request != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageFlutterSearchApi.search was null, expected non-null MessageSearchRequest.', - ); + final List args = message! as List; + final MessageSearchRequest arg_request = + args[0]! as MessageSearchRequest; try { - final MessageSearchReply output = api.search(arg_request!); + final MessageSearchReply output = api.search(arg_request); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/multiple_arity.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/multiple_arity.gen.dart index 0fceae131667..42bfad79d7b5 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/multiple_arity.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/multiple_arity.gen.dart @@ -4,19 +4,38 @@ // // Autogenerated from Pigeon, 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 +// ignore_for_file: unused_import, unused_shown_name +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, omit_obvious_local_variable_types, unnecessary_import, no_leading_underscores_for_local_identifiers import 'dart:async'; -import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; +import 'dart:typed_data' show Float64List, Int32List, Int64List; -import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; +import 'package:meta/meta.dart' show immutable, protected, visibleForTesting; -PlatformException _createConnectionError(String channelName) { - return PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel: "$channelName".', - ); +Object? _extractReplyValueOrThrow( + List? replyList, + String channelName, { + required bool isNullValid, +}) { + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel: "$channelName".', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (!isNullValid && (replyList.isNotEmpty && replyList[0] == null)) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } + return replyList.firstOrNull; } List wrapResponse({ @@ -72,35 +91,24 @@ class MultipleArityHostApi { final String pigeonVar_messageChannelSuffix; Future subtract(int x, int y) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.MultipleArityHostApi.subtract$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [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: 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 int?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as int; } } @@ -118,8 +126,7 @@ abstract class MultipleArityFlutterApi { ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.MultipleArityFlutterApi.subtract$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -128,23 +135,11 @@ abstract class MultipleArityFlutterApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MultipleArityFlutterApi.subtract was null.', - ); - final List args = (message as List?)!; - final int? arg_x = (args[0] as int?); - assert( - arg_x != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MultipleArityFlutterApi.subtract was null, expected non-null int.', - ); - final int? arg_y = (args[1] as int?); - assert( - arg_y != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MultipleArityFlutterApi.subtract was null, expected non-null int.', - ); + final List args = message! as List; + final int arg_x = args[0]! as int; + final int arg_y = args[1]! as int; try { - final int output = api.subtract(arg_x!, arg_y!); + final int output = api.subtract(arg_x, arg_y); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/non_null_fields.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/non_null_fields.gen.dart index 7433ca9a50c4..e551956e8091 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/non_null_fields.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/non_null_fields.gen.dart @@ -4,19 +4,38 @@ // // Autogenerated from Pigeon, 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 +// ignore_for_file: unused_import, unused_shown_name +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, omit_obvious_local_variable_types, unnecessary_import, no_leading_underscores_for_local_identifiers import 'dart:async'; -import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; +import 'dart:typed_data' show Float64List, Int32List, Int64List; -import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; +import 'package:meta/meta.dart' show immutable, protected, visibleForTesting; -PlatformException _createConnectionError(String channelName) { - return PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel: "$channelName".', - ); +Object? _extractReplyValueOrThrow( + List? replyList, + String channelName, { + required bool isNullValid, +}) { + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel: "$channelName".', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (!isNullValid && (replyList.isNotEmpty && replyList[0] == null)) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } + return replyList.firstOrNull; } List wrapResponse({ @@ -34,6 +53,15 @@ List wrapResponse({ } bool _deepEquals(Object? a, Object? b) { + if (identical(a, b)) { + return true; + } + if (a is double && b is double) { + if (a.isNaN && b.isNaN) { + return true; + } + return a == b; + } if (a is List && b is List) { return a.length == b.length && a.indexed.every( @@ -41,16 +69,52 @@ bool _deepEquals(Object? a, Object? b) { ); } if (a is Map && b is Map) { - return a.length == b.length && - a.entries.every( - (MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key]), - ); + if (a.length != b.length) { + return false; + } + for (final MapEntry entryA in a.entries) { + bool found = false; + for (final MapEntry entryB in b.entries) { + if (_deepEquals(entryA.key, entryB.key)) { + if (_deepEquals(entryA.value, entryB.value)) { + found = true; + break; + } else { + return false; + } + } + } + if (!found) { + return false; + } + } + return true; } return a == b; } +int _deepHash(Object? value) { + if (value is List) { + return Object.hashAll(value.map(_deepHash)); + } + if (value is Map) { + int result = 0; + for (final MapEntry entry in value.entries) { + result += (_deepHash(entry.key) * 31) ^ _deepHash(entry.value); + } + return result; + } + if (value is double && value.isNaN) { + // Normalize NaN to a consistent hash. + return 0x7FF8000000000000.hashCode; + } + if (value is double && value == 0.0) { + // Normalize -0.0 to 0.0 so they have the same hash code. + return 0.0.hashCode; + } + return value.hashCode; +} + enum ReplyType { success, error } class NonNullFieldSearchRequest { @@ -81,12 +145,12 @@ class NonNullFieldSearchRequest { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(query, other.query); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } class ExtraData { @@ -121,12 +185,13 @@ class ExtraData { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(detailA, other.detailA) && + _deepEquals(detailB, other.detailB); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } class NonNullFieldSearchReply { @@ -161,7 +226,7 @@ class NonNullFieldSearchReply { return NonNullFieldSearchReply( result: result[0]! as String, error: result[1]! as String, - indices: (result[2] as List?)!.cast(), + indices: (result[2]! as List).cast(), extraData: result[3]! as ExtraData, type: result[4]! as ReplyType, ); @@ -176,12 +241,16 @@ class NonNullFieldSearchReply { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(result, other.result) && + _deepEquals(error, other.error) && + _deepEquals(indices, other.indices) && + _deepEquals(extraData, other.extraData) && + _deepEquals(type, other.type); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } class _PigeonCodec extends StandardMessageCodec { @@ -212,7 +281,7 @@ class _PigeonCodec extends StandardMessageCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 129: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : ReplyType.values[value]; case 130: return NonNullFieldSearchRequest.decode(readValue(buffer)!); @@ -246,35 +315,24 @@ class NonNullFieldHostApi { Future search( NonNullFieldSearchRequest nested, ) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.NonNullFieldHostApi.search$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [nested], ); - 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 NonNullFieldSearchReply?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as NonNullFieldSearchReply; } } @@ -292,8 +350,7 @@ abstract class NonNullFieldFlutterApi { ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.NonNullFieldFlutterApi.search$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -302,19 +359,11 @@ abstract class NonNullFieldFlutterApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.NonNullFieldFlutterApi.search was null.', - ); - final List args = (message as List?)!; - final NonNullFieldSearchRequest? arg_request = - (args[0] as NonNullFieldSearchRequest?); - assert( - arg_request != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.NonNullFieldFlutterApi.search was null, expected non-null NonNullFieldSearchRequest.', - ); + final List args = message! as List; + final NonNullFieldSearchRequest arg_request = + args[0]! as NonNullFieldSearchRequest; try { - final NonNullFieldSearchReply output = api.search(arg_request!); + final NonNullFieldSearchReply output = api.search(arg_request); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/null_fields.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/null_fields.gen.dart index 526d27171802..6dbbbad8c197 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/null_fields.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/null_fields.gen.dart @@ -4,19 +4,38 @@ // // Autogenerated from Pigeon, 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 +// ignore_for_file: unused_import, unused_shown_name +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, omit_obvious_local_variable_types, unnecessary_import, no_leading_underscores_for_local_identifiers import 'dart:async'; -import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; +import 'dart:typed_data' show Float64List, Int32List, Int64List; -import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; +import 'package:meta/meta.dart' show immutable, protected, visibleForTesting; -PlatformException _createConnectionError(String channelName) { - return PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel: "$channelName".', - ); +Object? _extractReplyValueOrThrow( + List? replyList, + String channelName, { + required bool isNullValid, +}) { + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel: "$channelName".', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (!isNullValid && (replyList.isNotEmpty && replyList[0] == null)) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } + return replyList.firstOrNull; } List wrapResponse({ @@ -34,6 +53,15 @@ List wrapResponse({ } bool _deepEquals(Object? a, Object? b) { + if (identical(a, b)) { + return true; + } + if (a is double && b is double) { + if (a.isNaN && b.isNaN) { + return true; + } + return a == b; + } if (a is List && b is List) { return a.length == b.length && a.indexed.every( @@ -41,16 +69,52 @@ bool _deepEquals(Object? a, Object? b) { ); } if (a is Map && b is Map) { - return a.length == b.length && - a.entries.every( - (MapEntry entry) => - (b as Map).containsKey(entry.key) && - _deepEquals(entry.value, b[entry.key]), - ); + if (a.length != b.length) { + return false; + } + for (final MapEntry entryA in a.entries) { + bool found = false; + for (final MapEntry entryB in b.entries) { + if (_deepEquals(entryA.key, entryB.key)) { + if (_deepEquals(entryA.value, entryB.value)) { + found = true; + break; + } else { + return false; + } + } + } + if (!found) { + return false; + } + } + return true; } return a == b; } +int _deepHash(Object? value) { + if (value is List) { + return Object.hashAll(value.map(_deepHash)); + } + if (value is Map) { + int result = 0; + for (final MapEntry entry in value.entries) { + result += (_deepHash(entry.key) * 31) ^ _deepHash(entry.value); + } + return result; + } + if (value is double && value.isNaN) { + // Normalize NaN to a consistent hash. + return 0x7FF8000000000000.hashCode; + } + if (value is double && value == 0.0) { + // Normalize -0.0 to 0.0 so they have the same hash code. + return 0.0.hashCode; + } + return value.hashCode; +} + enum NullFieldsSearchReplyType { success, failure } class NullFieldsSearchRequest { @@ -85,12 +149,13 @@ class NullFieldsSearchRequest { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(query, other.query) && + _deepEquals(identifier, other.identifier); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } class NullFieldsSearchReply { @@ -140,12 +205,16 @@ class NullFieldsSearchReply { if (identical(this, other)) { return true; } - return _deepEquals(encode(), other.encode()); + return _deepEquals(result, other.result) && + _deepEquals(error, other.error) && + _deepEquals(indices, other.indices) && + _deepEquals(request, other.request) && + _deepEquals(type, other.type); } @override // ignore: avoid_equals_and_hash_code_on_mutable_classes - int get hashCode => Object.hashAll(_toList()); + int get hashCode => _deepHash([runtimeType, ..._toList()]); } class _PigeonCodec extends StandardMessageCodec { @@ -173,7 +242,7 @@ class _PigeonCodec extends StandardMessageCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 129: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : NullFieldsSearchReplyType.values[value]; case 130: return NullFieldsSearchRequest.decode(readValue(buffer)!); @@ -203,35 +272,24 @@ class NullFieldsHostApi { final String pigeonVar_messageChannelSuffix; Future search(NullFieldsSearchRequest nested) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.NullFieldsHostApi.search$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [nested], ); - 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 NullFieldsSearchReply?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as NullFieldsSearchReply; } } @@ -249,8 +307,7 @@ abstract class NullFieldsFlutterApi { ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.NullFieldsFlutterApi.search$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -259,19 +316,11 @@ abstract class NullFieldsFlutterApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.NullFieldsFlutterApi.search was null.', - ); - final List args = (message as List?)!; - final NullFieldsSearchRequest? arg_request = - (args[0] as NullFieldsSearchRequest?); - assert( - arg_request != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.NullFieldsFlutterApi.search was null, expected non-null NullFieldsSearchRequest.', - ); + final List args = message! as List; + final NullFieldsSearchRequest arg_request = + args[0]! as NullFieldsSearchRequest; try { - final NullFieldsSearchReply output = api.search(arg_request!); + final NullFieldsSearchReply output = api.search(arg_request); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/nullable_returns.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/nullable_returns.gen.dart index 942aa7c039f2..a54434311c5e 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/nullable_returns.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/nullable_returns.gen.dart @@ -4,19 +4,38 @@ // // Autogenerated from Pigeon, 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 +// ignore_for_file: unused_import, unused_shown_name +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, omit_obvious_local_variable_types, unnecessary_import, no_leading_underscores_for_local_identifiers import 'dart:async'; -import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; +import 'dart:typed_data' show Float64List, Int32List, Int64List; -import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; +import 'package:meta/meta.dart' show immutable, protected, visibleForTesting; -PlatformException _createConnectionError(String channelName) { - return PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel: "$channelName".', - ); +Object? _extractReplyValueOrThrow( + List? replyList, + String channelName, { + required bool isNullValid, +}) { + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel: "$channelName".', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (!isNullValid && (replyList.isNotEmpty && replyList[0] == null)) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } + return replyList.firstOrNull; } List wrapResponse({ @@ -72,28 +91,22 @@ class NullableReturnHostApi { final String pigeonVar_messageChannelSuffix; Future doit() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.NullableReturnHostApi.doit$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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 (pigeonVar_replyList[0] as int?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as int?; } } @@ -111,8 +124,7 @@ abstract class NullableReturnFlutterApi { ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.NullableReturnFlutterApi.doit$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -155,35 +167,24 @@ class NullableArgHostApi { final String pigeonVar_messageChannelSuffix; Future doit(int? x) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.NullableArgHostApi.doit$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [x], ); - 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 int?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as int; } } @@ -201,8 +202,7 @@ abstract class NullableArgFlutterApi { ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.NullableArgFlutterApi.doit$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -211,12 +211,8 @@ abstract class NullableArgFlutterApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.NullableArgFlutterApi.doit was null.', - ); - final List args = (message as List?)!; - final int? arg_x = (args[0] as int?); + final List args = message! as List; + final int? arg_x = args[0] as int?; try { final int? output = api.doit(arg_x); return wrapResponse(result: output); @@ -251,28 +247,22 @@ class NullableCollectionReturnHostApi { final String pigeonVar_messageChannelSuffix; Future?> doit() async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionReturnHostApi.doit$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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 (pigeonVar_replyList[0] as List?)?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as List?)?.cast(); } } @@ -290,8 +280,7 @@ abstract class NullableCollectionReturnFlutterApi { ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionReturnFlutterApi.doit$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -334,35 +323,24 @@ class NullableCollectionArgHostApi { final String pigeonVar_messageChannelSuffix; Future> doit(List? x) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionArgHostApi.doit$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [x], ); - 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 List?)!.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as List).cast(); } } @@ -380,8 +358,7 @@ abstract class NullableCollectionArgFlutterApi { ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionArgFlutterApi.doit$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -390,11 +367,7 @@ abstract class NullableCollectionArgFlutterApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionArgFlutterApi.doit was null.', - ); - final List args = (message as List?)!; + final List args = message! as List; final List? arg_x = (args[0] as List?) ?.cast(); try { diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/primitive.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/primitive.gen.dart index 03becd18df68..8dfe854ad227 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/primitive.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/primitive.gen.dart @@ -4,19 +4,38 @@ // // Autogenerated from Pigeon, 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 +// ignore_for_file: unused_import, unused_shown_name +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, omit_obvious_local_variable_types, unnecessary_import, no_leading_underscores_for_local_identifiers import 'dart:async'; -import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; +import 'dart:typed_data' show Float64List, Int32List, Int64List; -import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; +import 'package:meta/meta.dart' show immutable, protected, visibleForTesting; -PlatformException _createConnectionError(String channelName) { - return PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel: "$channelName".', - ); +Object? _extractReplyValueOrThrow( + List? replyList, + String channelName, { + required bool isNullValid, +}) { + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel: "$channelName".', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (!isNullValid && (replyList.isNotEmpty && replyList[0] == null)) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } + return replyList.firstOrNull; } List wrapResponse({ @@ -72,292 +91,193 @@ class PrimitiveHostApi { final String pigeonVar_messageChannelSuffix; Future anInt(int value) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.anInt$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [value], ); - 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 int?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as int; } Future aBool(bool value) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aBool$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [value], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as bool; } Future aString(String value) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aString$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [value], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as String; } Future aDouble(double value) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aDouble$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [value], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as double; } Future> aMap(Map value) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [value], ); - 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 Map?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as Map; } Future> aList(List value) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [value], ); - 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 List?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as List; } Future anInt32List(Int32List value) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.anInt32List$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [value], ); - 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 Int32List?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as Int32List; } Future> aBoolList(List value) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aBoolList$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [value], ); - 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 List?)!.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as List).cast(); } Future> aStringIntMap(Map value) async { - final String pigeonVar_channelName = + final pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aStringIntMap$pigeonVar_messageChannelSuffix'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [value], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map) + .cast(); } } @@ -391,8 +311,7 @@ abstract class PrimitiveFlutterApi { ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -401,18 +320,10 @@ abstract class PrimitiveFlutterApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt was null.', - ); - final List args = (message as List?)!; - final int? arg_value = (args[0] as int?); - assert( - arg_value != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt was null, expected non-null int.', - ); + final List args = message! as List; + final int arg_value = args[0]! as int; try { - final int output = api.anInt(arg_value!); + final int output = api.anInt(arg_value); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -425,8 +336,7 @@ abstract class PrimitiveFlutterApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBool$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -435,18 +345,10 @@ abstract class PrimitiveFlutterApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBool was null.', - ); - final List args = (message as List?)!; - final bool? arg_value = (args[0] as bool?); - assert( - arg_value != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBool was null, expected non-null bool.', - ); + final List args = message! as List; + final bool arg_value = args[0]! as bool; try { - final bool output = api.aBool(arg_value!); + final bool output = api.aBool(arg_value); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -459,8 +361,7 @@ abstract class PrimitiveFlutterApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aString$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -469,18 +370,10 @@ abstract class PrimitiveFlutterApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aString was null.', - ); - final List args = (message as List?)!; - final String? arg_value = (args[0] as String?); - assert( - arg_value != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aString was null, expected non-null String.', - ); + final List args = message! as List; + final String arg_value = args[0]! as String; try { - final String output = api.aString(arg_value!); + final String output = api.aString(arg_value); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -493,8 +386,7 @@ abstract class PrimitiveFlutterApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aDouble$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -503,18 +395,10 @@ abstract class PrimitiveFlutterApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aDouble was null.', - ); - final List args = (message as List?)!; - final double? arg_value = (args[0] as double?); - assert( - arg_value != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aDouble was null, expected non-null double.', - ); + final List args = message! as List; + final double arg_value = args[0]! as double; try { - final double output = api.aDouble(arg_value!); + final double output = api.aDouble(arg_value); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -527,8 +411,7 @@ abstract class PrimitiveFlutterApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aMap$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -537,19 +420,11 @@ abstract class PrimitiveFlutterApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aMap was null.', - ); - final List args = (message as List?)!; - final Map? arg_value = - (args[0] as Map?); - assert( - arg_value != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aMap was null, expected non-null Map.', - ); + final List args = message! as List; + final Map arg_value = + args[0]! as Map; try { - final Map output = api.aMap(arg_value!); + final Map output = api.aMap(arg_value); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -562,8 +437,7 @@ abstract class PrimitiveFlutterApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aList$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -572,18 +446,10 @@ abstract class PrimitiveFlutterApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aList was null.', - ); - final List args = (message as List?)!; - final List? arg_value = (args[0] as List?); - assert( - arg_value != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aList was null, expected non-null List.', - ); + final List args = message! as List; + final List arg_value = args[0]! as List; try { - final List output = api.aList(arg_value!); + final List output = api.aList(arg_value); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -596,8 +462,7 @@ abstract class PrimitiveFlutterApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt32List$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -606,18 +471,10 @@ abstract class PrimitiveFlutterApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt32List was null.', - ); - final List args = (message as List?)!; - final Int32List? arg_value = (args[0] as Int32List?); - assert( - arg_value != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt32List was null, expected non-null Int32List.', - ); + final List args = message! as List; + final Int32List arg_value = args[0]! as Int32List; try { - final Int32List output = api.anInt32List(arg_value!); + final Int32List output = api.anInt32List(arg_value); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -630,8 +487,7 @@ abstract class PrimitiveFlutterApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBoolList$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -640,19 +496,11 @@ abstract class PrimitiveFlutterApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBoolList was null.', - ); - final List args = (message as List?)!; - final List? arg_value = (args[0] as List?) - ?.cast(); - assert( - arg_value != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBoolList was null, expected non-null List.', - ); + final List args = message! as List; + final List arg_value = (args[0]! as List) + .cast(); try { - final List output = api.aBoolList(arg_value!); + final List output = api.aBoolList(arg_value); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -665,8 +513,7 @@ abstract class PrimitiveFlutterApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aStringIntMap$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -675,19 +522,11 @@ abstract class PrimitiveFlutterApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aStringIntMap was null.', - ); - final List args = (message as List?)!; - final Map? arg_value = - (args[0] as Map?)?.cast(); - assert( - arg_value != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aStringIntMap was null, expected non-null Map.', - ); + final List args = message! as List; + final Map arg_value = + (args[0]! as Map).cast(); try { - final Map output = api.aStringIntMap(arg_value!); + final Map output = api.aStringIntMap(arg_value); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/proxy_api_tests.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/proxy_api_tests.gen.dart index 1e705c650716..16ea40c4e399 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/proxy_api_tests.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/proxy_api_tests.gen.dart @@ -4,22 +4,40 @@ // // Autogenerated from Pigeon, 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 +// ignore_for_file: unused_import, unused_shown_name +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, omit_obvious_local_variable_types, unnecessary_import, no_leading_underscores_for_local_identifiers import 'dart:async'; import 'dart:io' show Platform; -import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; +import 'dart:typed_data' show Float64List, Int32List, Int64List; -import 'package:flutter/foundation.dart' - show ReadBuffer, WriteBuffer, immutable, protected, visibleForTesting; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart' show WidgetsFlutterBinding; +import 'package:meta/meta.dart' show immutable, protected, visibleForTesting; -PlatformException _createConnectionError(String channelName) { - return PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel: "$channelName".', - ); +Object? _extractReplyValueOrThrow( + List? replyList, + String channelName, { + required bool isNullValid, +}) { + if (replyList == null) { + throw PlatformException( + code: 'channel-error', + message: 'Unable to establish connection on channel: "$channelName".', + ); + } else if (replyList.length > 1) { + throw PlatformException( + code: replyList[0]! as String, + message: replyList[1] as String?, + details: replyList[2], + ); + } else if (!isNullValid && (replyList.isNotEmpty && replyList[0] == null)) { + throw PlatformException( + code: 'null-error', + message: 'Host platform returned null value for non-null return value.', + ); + } + return replyList.firstOrNull; } List wrapResponse({ @@ -587,8 +605,7 @@ class _PigeonInternalInstanceManagerApi { PigeonInstanceManager? instanceManager, }) { { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.PigeonInternalInstanceManager.removeStrongReference', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -597,19 +614,11 @@ class _PigeonInternalInstanceManagerApi { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.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.pigeon_integration_tests.PigeonInternalInstanceManager.removeStrongReference was null, expected non-null int.', - ); + final List args = message! as List; + final int arg_identifier = args[0]! as int; try { (instanceManager ?? PigeonInstanceManager.instance).remove( - arg_identifier!, + arg_identifier, ); return wrapResponse(empty: true); } on PlatformException catch (e) { @@ -625,58 +634,44 @@ class _PigeonInternalInstanceManagerApi { } Future removeStrongReference(int identifier) async { - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.PigeonInternalInstanceManager.removeStrongReference'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); } /// Clear the native `PigeonInstanceManager`. /// /// This is typically called after a hot restart. Future clear() async { - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.PigeonInternalInstanceManager.clear'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); } } @@ -727,7 +722,7 @@ class _PigeonCodec extends StandardMessageCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 129: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : ProxyApiTestEnum.values[value]; default: return super.readValueOfType(type, buffer); @@ -1068,14 +1063,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel .send([ pigeonVar_instanceIdentifier, @@ -1117,19 +1111,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass nullableProxyApiParam, ]); () 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); }(); } @@ -1390,14 +1378,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.namedConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel .send([ pigeonVar_instanceIdentifier, @@ -1421,19 +1408,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass aNullableProxyApi, ]); () 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); }(); } @@ -2218,8 +2199,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoop', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2228,20 +2208,12 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoop was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoop was null, expected non-null ProxyApiTestClass.', - ); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; try { - (flutterNoop ?? arg_pigeon_instance!.flutterNoop)?.call( - arg_pigeon_instance!, + (flutterNoop ?? arg_pigeon_instance.flutterNoop)?.call( + arg_pigeon_instance, ); return wrapResponse(empty: true); } on PlatformException catch (e) { @@ -2256,8 +2228,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowError', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2266,21 +2237,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowError was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowError was null, expected non-null ProxyApiTestClass.', - ); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; try { final Object? output = - (flutterThrowError ?? arg_pigeon_instance!.flutterThrowError) - ?.call(arg_pigeon_instance!); + (flutterThrowError ?? arg_pigeon_instance.flutterThrowError) + ?.call(arg_pigeon_instance); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2294,8 +2257,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowErrorFromVoid', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2304,21 +2266,13 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowErrorFromVoid was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterThrowErrorFromVoid was null, expected non-null ProxyApiTestClass.', - ); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; try { (flutterThrowErrorFromVoid ?? - arg_pigeon_instance!.flutterThrowErrorFromVoid) - ?.call(arg_pigeon_instance!); + arg_pigeon_instance.flutterThrowErrorFromVoid) + ?.call(arg_pigeon_instance); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2332,8 +2286,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoBool', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2342,27 +2295,15 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoBool was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoBool was null, expected non-null ProxyApiTestClass.', - ); - final bool? arg_aBool = (args[1] as bool?); - assert( - arg_aBool != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoBool was null, expected non-null bool.', - ); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; + final bool arg_aBool = args[1]! as bool; try { final bool output = - (flutterEchoBool ?? arg_pigeon_instance!.flutterEchoBool).call( - arg_pigeon_instance!, - arg_aBool!, + (flutterEchoBool ?? arg_pigeon_instance.flutterEchoBool).call( + arg_pigeon_instance, + arg_aBool, ); return wrapResponse(result: output); } on PlatformException catch (e) { @@ -2377,8 +2318,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoInt', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2387,27 +2327,15 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoInt was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoInt was null, expected non-null ProxyApiTestClass.', - ); - final int? arg_anInt = (args[1] as int?); - assert( - arg_anInt != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoInt was null, expected non-null int.', - ); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; + final int arg_anInt = args[1]! as int; try { final int output = - (flutterEchoInt ?? arg_pigeon_instance!.flutterEchoInt).call( - arg_pigeon_instance!, - arg_anInt!, + (flutterEchoInt ?? arg_pigeon_instance.flutterEchoInt).call( + arg_pigeon_instance, + arg_anInt, ); return wrapResponse(result: output); } on PlatformException catch (e) { @@ -2422,8 +2350,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoDouble', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2432,26 +2359,14 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoDouble was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoDouble was null, expected non-null ProxyApiTestClass.', - ); - final double? arg_aDouble = (args[1] as double?); - assert( - arg_aDouble != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoDouble was null, expected non-null double.', - ); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; + final double arg_aDouble = args[1]! as double; try { final double output = - (flutterEchoDouble ?? arg_pigeon_instance!.flutterEchoDouble) - .call(arg_pigeon_instance!, arg_aDouble!); + (flutterEchoDouble ?? arg_pigeon_instance.flutterEchoDouble) + .call(arg_pigeon_instance, arg_aDouble); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2465,8 +2380,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoString', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2475,26 +2389,14 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoString was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoString was null, expected non-null ProxyApiTestClass.', - ); - final String? arg_aString = (args[1] as String?); - assert( - arg_aString != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoString was null, expected non-null String.', - ); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; + final String arg_aString = args[1]! as String; try { final String output = - (flutterEchoString ?? arg_pigeon_instance!.flutterEchoString) - .call(arg_pigeon_instance!, arg_aString!); + (flutterEchoString ?? arg_pigeon_instance.flutterEchoString) + .call(arg_pigeon_instance, arg_aString); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2508,8 +2410,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoUint8List', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2518,27 +2419,15 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoUint8List was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoUint8List was null, expected non-null ProxyApiTestClass.', - ); - final Uint8List? arg_aList = (args[1] as Uint8List?); - assert( - arg_aList != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoUint8List was null, expected non-null Uint8List.', - ); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; + final Uint8List arg_aList = args[1]! as Uint8List; try { final Uint8List output = (flutterEchoUint8List ?? - arg_pigeon_instance!.flutterEchoUint8List) - .call(arg_pigeon_instance!, arg_aList!); + arg_pigeon_instance.flutterEchoUint8List) + .call(arg_pigeon_instance, arg_aList); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2552,8 +2441,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoList', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2562,28 +2450,15 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoList was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoList was null, expected non-null ProxyApiTestClass.', - ); - final List? arg_aList = (args[1] as List?) - ?.cast(); - assert( - arg_aList != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoList was null, expected non-null List.', - ); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; + final List arg_aList = args[1]! as List; try { final List output = - (flutterEchoList ?? arg_pigeon_instance!.flutterEchoList).call( - arg_pigeon_instance!, - arg_aList!, + (flutterEchoList ?? arg_pigeon_instance.flutterEchoList).call( + arg_pigeon_instance, + arg_aList, ); return wrapResponse(result: output); } on PlatformException catch (e) { @@ -2598,8 +2473,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiList', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2608,28 +2482,16 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiList was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiList was null, expected non-null ProxyApiTestClass.', - ); - final List? arg_aList = - (args[1] as List?)?.cast(); - assert( - arg_aList != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiList was null, expected non-null List.', - ); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; + final List arg_aList = (args[1]! as List) + .cast(); try { final List output = (flutterEchoProxyApiList ?? - arg_pigeon_instance!.flutterEchoProxyApiList) - .call(arg_pigeon_instance!, arg_aList!); + arg_pigeon_instance.flutterEchoProxyApiList) + .call(arg_pigeon_instance, arg_aList); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2643,8 +2505,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoMap', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2653,28 +2514,16 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoMap was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoMap was null, expected non-null ProxyApiTestClass.', - ); - final Map? arg_aMap = - (args[1] as Map?)?.cast(); - assert( - arg_aMap != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoMap was null, expected non-null Map.', - ); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; + final Map arg_aMap = + (args[1]! as Map).cast(); try { final Map output = - (flutterEchoMap ?? arg_pigeon_instance!.flutterEchoMap).call( - arg_pigeon_instance!, - arg_aMap!, + (flutterEchoMap ?? arg_pigeon_instance.flutterEchoMap).call( + arg_pigeon_instance, + arg_aMap, ); return wrapResponse(result: output); } on PlatformException catch (e) { @@ -2689,8 +2538,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiMap', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2699,29 +2547,17 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiMap was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiMap was null, expected non-null ProxyApiTestClass.', - ); - final Map? arg_aMap = - (args[1] as Map?) - ?.cast(); - assert( - arg_aMap != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApiMap was null, expected non-null Map.', - ); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; + final Map arg_aMap = + (args[1]! as Map) + .cast(); try { final Map output = (flutterEchoProxyApiMap ?? - arg_pigeon_instance!.flutterEchoProxyApiMap) - .call(arg_pigeon_instance!, arg_aMap!); + arg_pigeon_instance.flutterEchoProxyApiMap) + .call(arg_pigeon_instance, arg_aMap); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2735,8 +2571,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoEnum', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2745,27 +2580,15 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoEnum was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoEnum was null, expected non-null ProxyApiTestClass.', - ); - final ProxyApiTestEnum? arg_anEnum = (args[1] as ProxyApiTestEnum?); - assert( - arg_anEnum != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoEnum was null, expected non-null ProxyApiTestEnum.', - ); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; + final ProxyApiTestEnum arg_anEnum = args[1]! as ProxyApiTestEnum; try { final ProxyApiTestEnum output = - (flutterEchoEnum ?? arg_pigeon_instance!.flutterEchoEnum).call( - arg_pigeon_instance!, - arg_anEnum!, + (flutterEchoEnum ?? arg_pigeon_instance.flutterEchoEnum).call( + arg_pigeon_instance, + arg_anEnum, ); return wrapResponse(result: output); } on PlatformException catch (e) { @@ -2780,8 +2603,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApi', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2790,28 +2612,15 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApi was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApi was null, expected non-null ProxyApiTestClass.', - ); - final ProxyApiSuperClass? arg_aProxyApi = - (args[1] as ProxyApiSuperClass?); - assert( - arg_aProxyApi != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoProxyApi was null, expected non-null ProxyApiSuperClass.', - ); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; + final ProxyApiSuperClass arg_aProxyApi = + args[1]! as ProxyApiSuperClass; try { final ProxyApiSuperClass output = - (flutterEchoProxyApi ?? - arg_pigeon_instance!.flutterEchoProxyApi) - .call(arg_pigeon_instance!, arg_aProxyApi!); + (flutterEchoProxyApi ?? arg_pigeon_instance.flutterEchoProxyApi) + .call(arg_pigeon_instance, arg_aProxyApi); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2825,8 +2634,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableBool', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2835,23 +2643,15 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableBool was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableBool was null, expected non-null ProxyApiTestClass.', - ); - final bool? arg_aBool = (args[1] as bool?); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; + final bool? arg_aBool = args[1] as bool?; try { final bool? output = (flutterEchoNullableBool ?? - arg_pigeon_instance!.flutterEchoNullableBool) - ?.call(arg_pigeon_instance!, arg_aBool); + arg_pigeon_instance.flutterEchoNullableBool) + ?.call(arg_pigeon_instance, arg_aBool); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2865,8 +2665,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableInt', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2875,23 +2674,15 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableInt was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableInt was null, expected non-null ProxyApiTestClass.', - ); - final int? arg_anInt = (args[1] as int?); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; + final int? arg_anInt = args[1] as int?; try { final int? output = (flutterEchoNullableInt ?? - arg_pigeon_instance!.flutterEchoNullableInt) - ?.call(arg_pigeon_instance!, arg_anInt); + arg_pigeon_instance.flutterEchoNullableInt) + ?.call(arg_pigeon_instance, arg_anInt); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2905,8 +2696,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableDouble', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2915,23 +2705,15 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableDouble was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableDouble was null, expected non-null ProxyApiTestClass.', - ); - final double? arg_aDouble = (args[1] as double?); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; + final double? arg_aDouble = args[1] as double?; try { final double? output = (flutterEchoNullableDouble ?? - arg_pigeon_instance!.flutterEchoNullableDouble) - ?.call(arg_pigeon_instance!, arg_aDouble); + arg_pigeon_instance.flutterEchoNullableDouble) + ?.call(arg_pigeon_instance, arg_aDouble); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2945,8 +2727,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableString', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2955,23 +2736,15 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableString was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableString was null, expected non-null ProxyApiTestClass.', - ); - final String? arg_aString = (args[1] as String?); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; + final String? arg_aString = args[1] as String?; try { final String? output = (flutterEchoNullableString ?? - arg_pigeon_instance!.flutterEchoNullableString) - ?.call(arg_pigeon_instance!, arg_aString); + arg_pigeon_instance.flutterEchoNullableString) + ?.call(arg_pigeon_instance, arg_aString); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -2985,8 +2758,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableUint8List', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -2995,23 +2767,15 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableUint8List was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableUint8List was null, expected non-null ProxyApiTestClass.', - ); - final Uint8List? arg_aList = (args[1] as Uint8List?); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; + final Uint8List? arg_aList = args[1] as Uint8List?; try { final Uint8List? output = (flutterEchoNullableUint8List ?? - arg_pigeon_instance!.flutterEchoNullableUint8List) - ?.call(arg_pigeon_instance!, arg_aList); + arg_pigeon_instance.flutterEchoNullableUint8List) + ?.call(arg_pigeon_instance, arg_aList); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -3025,8 +2789,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableList', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -3035,24 +2798,15 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableList was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableList was null, expected non-null ProxyApiTestClass.', - ); - final List? arg_aList = (args[1] as List?) - ?.cast(); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; + final List? arg_aList = args[1] as List?; try { final List? output = (flutterEchoNullableList ?? - arg_pigeon_instance!.flutterEchoNullableList) - ?.call(arg_pigeon_instance!, arg_aList); + arg_pigeon_instance.flutterEchoNullableList) + ?.call(arg_pigeon_instance, arg_aList); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -3066,8 +2820,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableMap', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -3076,24 +2829,16 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableMap was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableMap was null, expected non-null ProxyApiTestClass.', - ); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; final Map? arg_aMap = (args[1] as Map?)?.cast(); try { final Map? output = (flutterEchoNullableMap ?? - arg_pigeon_instance!.flutterEchoNullableMap) - ?.call(arg_pigeon_instance!, arg_aMap); + arg_pigeon_instance.flutterEchoNullableMap) + ?.call(arg_pigeon_instance, arg_aMap); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -3107,8 +2852,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableEnum', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -3117,23 +2861,15 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableEnum was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableEnum was null, expected non-null ProxyApiTestClass.', - ); - final ProxyApiTestEnum? arg_anEnum = (args[1] as ProxyApiTestEnum?); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; + final ProxyApiTestEnum? arg_anEnum = args[1] as ProxyApiTestEnum?; try { final ProxyApiTestEnum? output = (flutterEchoNullableEnum ?? - arg_pigeon_instance!.flutterEchoNullableEnum) - ?.call(arg_pigeon_instance!, arg_anEnum); + arg_pigeon_instance.flutterEchoNullableEnum) + ?.call(arg_pigeon_instance, arg_anEnum); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -3147,8 +2883,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableProxyApi', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -3157,24 +2892,16 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableProxyApi was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoNullableProxyApi was null, expected non-null ProxyApiTestClass.', - ); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; final ProxyApiSuperClass? arg_aProxyApi = - (args[1] as ProxyApiSuperClass?); + args[1] as ProxyApiSuperClass?; try { final ProxyApiSuperClass? output = (flutterEchoNullableProxyApi ?? - arg_pigeon_instance!.flutterEchoNullableProxyApi) - ?.call(arg_pigeon_instance!, arg_aProxyApi); + arg_pigeon_instance.flutterEchoNullableProxyApi) + ?.call(arg_pigeon_instance, arg_aProxyApi); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -3188,8 +2915,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoopAsync', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -3198,20 +2924,12 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoopAsync was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterNoopAsync was null, expected non-null ProxyApiTestClass.', - ); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; try { - await (flutterNoopAsync ?? arg_pigeon_instance!.flutterNoopAsync) - ?.call(arg_pigeon_instance!); + await (flutterNoopAsync ?? arg_pigeon_instance.flutterNoopAsync) + ?.call(arg_pigeon_instance); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -3225,8 +2943,7 @@ class ProxyApiTestClass extends ProxyApiSuperClass } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoAsyncString', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -3235,27 +2952,15 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoAsyncString was null.', - ); - final List args = (message as List?)!; - final ProxyApiTestClass? arg_pigeon_instance = - (args[0] as ProxyApiTestClass?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoAsyncString was null, expected non-null ProxyApiTestClass.', - ); - final String? arg_aString = (args[1] as String?); - assert( - arg_aString != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.flutterEchoAsyncString was null, expected non-null String.', - ); + final List args = message! as List; + final ProxyApiTestClass arg_pigeon_instance = + args[0]! as ProxyApiTestClass; + final String arg_aString = args[1]! as String; try { final String output = await (flutterEchoAsyncString ?? - arg_pigeon_instance!.flutterEchoAsyncString) - .call(arg_pigeon_instance!, arg_aString!); + arg_pigeon_instance.flutterEchoAsyncString) + .call(arg_pigeon_instance, arg_aString); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); @@ -3281,30 +2986,23 @@ class ProxyApiTestClass extends ProxyApiSuperClass final int pigeonVar_instanceIdentifier = pigeon_instanceManager .addDartCreatedInstance(pigeonVar_instance); () async { - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.attachedField'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); 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) { - throw PlatformException( - code: pigeonVar_replyList[0]! as String, - message: pigeonVar_replyList[1] as String?, - details: pigeonVar_replyList[2], - ); - } else { - return; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); }(); return pigeonVar_instance; } @@ -3319,30 +3017,23 @@ class ProxyApiTestClass extends ProxyApiSuperClass final int pigeonVar_instanceIdentifier = PigeonInstanceManager.instance .addDartCreatedInstance(pigeonVar_instance); () async { - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.staticAttachedField'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); }(); return pigeonVar_instance; } @@ -3353,30 +3044,23 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.noop'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); } /// Returns an error, to test error handling. @@ -3384,30 +3068,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwError'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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]; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue; } /// Returns an error from a void function, to test error handling. @@ -3415,30 +3093,23 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwErrorFromVoid'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); } /// Returns a Flutter error, to test error handling. @@ -3446,30 +3117,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwFlutterError'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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]; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue; } /// Returns passed in int. @@ -3477,35 +3142,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoInt'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, anInt], ); - 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 int?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as int; } /// Returns passed in double. @@ -3513,35 +3167,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoDouble'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aDouble], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as double; } /// Returns the passed in boolean. @@ -3549,35 +3192,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoBool'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aBool], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as bool; } /// Returns the passed in string. @@ -3585,35 +3217,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoString'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aString], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as String; } /// Returns the passed in Uint8List. @@ -3621,35 +3242,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoUint8List'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aUint8List], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as Uint8List; } /// Returns the passed in generic Object. @@ -3657,35 +3267,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoObject'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, anObject], ); - 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]!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue!; } /// Returns the passed list, to test serialization and deserialization. @@ -3693,35 +3292,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoList'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aList], ); - 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 List?)!.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as List; } /// Returns the passed list with ProxyApis, to test serialization and @@ -3732,36 +3320,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoProxyApiList'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aList], ); - 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 List?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as List).cast(); } /// Returns the passed map, to test serialization and deserialization. @@ -3769,36 +3345,25 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoMap'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map) + .cast(); } /// Returns the passed map with ProxyApis, to test serialization and @@ -3809,36 +3374,25 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoProxyApiMap'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map) + .cast(); } /// Returns the passed enum to test serialization and deserialization. @@ -3846,35 +3400,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoEnum'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, anEnum], ); - 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 ProxyApiTestEnum?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as ProxyApiTestEnum; } /// Returns the passed ProxyApi to test serialization and deserialization. @@ -3882,35 +3425,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoProxyApi'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aProxyApi], ); - 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 ProxyApiSuperClass?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as ProxyApiSuperClass; } /// Returns passed in int. @@ -3918,30 +3450,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableInt'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aNullableInt], ); - 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?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as int?; } /// Returns passed in double. @@ -3949,30 +3475,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableDouble'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aNullableDouble], ); - 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 double?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as double?; } /// Returns the passed in boolean. @@ -3980,30 +3500,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableBool'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aNullableBool], ); - 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 bool?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as bool?; } /// Returns the passed in string. @@ -4011,30 +3525,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableString'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aNullableString], ); - 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 String?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as String?; } /// Returns the passed in Uint8List. @@ -4044,30 +3552,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableUint8List'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aNullableUint8List], ); - 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?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as Uint8List?; } /// Returns the passed in generic Object. @@ -4075,30 +3577,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableObject'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aNullableObject], ); - 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]; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue; } /// Returns the passed list, to test serialization and deserialization. @@ -4106,30 +3602,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableList'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aNullableList], ); - 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(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as List?; } /// Returns the passed map, to test serialization and deserialization. @@ -4139,31 +3629,25 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableMap'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aNullableMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?) + ?.cast(); } Future echoNullableEnum( @@ -4172,30 +3656,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableEnum'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aNullableEnum], ); - 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 ProxyApiTestEnum?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as ProxyApiTestEnum?; } /// Returns the passed ProxyApi to test serialization and deserialization. @@ -4205,30 +3683,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoNullableProxyApi'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aNullableProxyApi], ); - 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 ProxyApiSuperClass?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as ProxyApiSuperClass?; } /// A no-op function taking no arguments and returning no value, to sanity @@ -4237,30 +3709,23 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.noopAsync'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); } /// Returns passed in int asynchronously. @@ -4268,35 +3733,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncInt'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, anInt], ); - 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 int?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as int; } /// Returns passed in double asynchronously. @@ -4304,35 +3758,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncDouble'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aDouble], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as double; } /// Returns the passed in boolean asynchronously. @@ -4340,35 +3783,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncBool'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aBool], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as bool; } /// Returns the passed string asynchronously. @@ -4376,35 +3808,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncString'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aString], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as String; } /// Returns the passed in Uint8List asynchronously. @@ -4412,35 +3833,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncUint8List'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aUint8List], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as Uint8List; } /// Returns the passed in generic Object asynchronously. @@ -4448,35 +3858,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncObject'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, anObject], ); - 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]!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue!; } /// Returns the passed list, to test asynchronous serialization and deserialization. @@ -4484,35 +3883,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncList'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aList], ); - 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 List?)!.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as List; } /// Returns the passed map, to test asynchronous serialization and deserialization. @@ -4520,36 +3908,25 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncMap'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map) + .cast(); } /// Returns the passed enum, to test asynchronous serialization and deserialization. @@ -4557,35 +3934,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncEnum'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, anEnum], ); - 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 ProxyApiTestEnum?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as ProxyApiTestEnum; } /// Responds with an error from an async function returning a value. @@ -4593,30 +3959,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwAsyncError'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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]; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue; } /// Responds with an error from an async void function. @@ -4624,30 +3984,23 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwAsyncErrorFromVoid'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); } /// Responds with a Flutter error from an async function returning a value. @@ -4655,30 +4008,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.throwAsyncFlutterError'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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]; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue; } /// Returns passed in int asynchronously. @@ -4686,30 +4033,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableInt'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, anInt], ); - 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?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as int?; } /// Returns passed in double asynchronously. @@ -4717,30 +4058,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableDouble'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aDouble], ); - 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 double?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as double?; } /// Returns the passed in boolean asynchronously. @@ -4748,30 +4083,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableBool'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aBool], ); - 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 bool?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as bool?; } /// Returns the passed string asynchronously. @@ -4779,30 +4108,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableString'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aString], ); - 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 String?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as String?; } /// Returns the passed in Uint8List asynchronously. @@ -4810,30 +4133,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableUint8List'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aUint8List], ); - 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?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as Uint8List?; } /// Returns the passed in generic Object asynchronously. @@ -4841,30 +4158,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableObject'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, anObject], ); - 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]; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue; } /// Returns the passed list, to test asynchronous serialization and deserialization. @@ -4872,30 +4183,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableList'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aList], ); - 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(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as List?; } /// Returns the passed map, to test asynchronous serialization and deserialization. @@ -4905,31 +4210,25 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableMap'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?) + ?.cast(); } /// Returns the passed enum, to test asynchronous serialization and deserialization. @@ -4939,30 +4238,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoAsyncNullableEnum'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, anEnum], ); - 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 ProxyApiTestEnum?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as ProxyApiTestEnum?; } static Future staticNoop({ @@ -4977,28 +4270,21 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeon_instanceManager ?? PigeonInstanceManager.instance, ); final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.staticNoop'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); } static Future echoStaticString( @@ -5014,35 +4300,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeon_instanceManager ?? PigeonInstanceManager.instance, ); final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.echoStaticString'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [aString], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as String; } static Future staticAsyncNoop({ @@ -5057,328 +4332,235 @@ class ProxyApiTestClass extends ProxyApiSuperClass pigeon_instanceManager ?? PigeonInstanceManager.instance, ); final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.staticAsyncNoop'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); } Future callFlutterNoop() async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterNoop'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); } Future callFlutterThrowError() async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterThrowError'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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]; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue; } Future callFlutterThrowErrorFromVoid() async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterThrowErrorFromVoid'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); } Future callFlutterEchoBool(bool aBool) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoBool'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aBool], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as bool; } Future callFlutterEchoInt(int anInt) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoInt'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, anInt], ); - 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 int?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as int; } Future callFlutterEchoDouble(double aDouble) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoDouble'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aDouble], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as double; } Future callFlutterEchoString(String aString) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoString'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aString], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as String; } Future callFlutterEchoUint8List(Uint8List aUint8List) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoUint8List'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aUint8List], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as Uint8List; } Future> callFlutterEchoList(List aList) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoList'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aList], ); - 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 List?)!.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as List; } Future> callFlutterEchoProxyApiList( @@ -5387,36 +4569,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoProxyApiList'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aList], ); - 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 List?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as List).cast(); } Future> callFlutterEchoMap( @@ -5425,36 +4595,25 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoMap'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map) + .cast(); } Future> callFlutterEchoProxyApiMap( @@ -5463,71 +4622,49 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoProxyApiMap'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aMap], ); - 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 Map?)! - .cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return (pigeonVar_replyValue! as Map) + .cast(); } Future callFlutterEchoEnum(ProxyApiTestEnum anEnum) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoEnum'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, anEnum], ); - 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 ProxyApiTestEnum?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as ProxyApiTestEnum; } Future callFlutterEchoProxyApi( @@ -5536,155 +4673,120 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoProxyApi'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aProxyApi], ); - 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 ProxyApiSuperClass?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as ProxyApiSuperClass; } Future callFlutterEchoNullableBool(bool? aBool) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableBool'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aBool], ); - 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 bool?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as bool?; } Future callFlutterEchoNullableInt(int? anInt) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableInt'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, anInt], ); - 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?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as int?; } Future callFlutterEchoNullableDouble(double? aDouble) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableDouble'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aDouble], ); - 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 double?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as double?; } Future callFlutterEchoNullableString(String? aString) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableString'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aString], ); - 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 String?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as String?; } Future callFlutterEchoNullableUint8List( @@ -5693,30 +4795,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableUint8List'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aUint8List], ); - 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?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as Uint8List?; } Future?> callFlutterEchoNullableList( @@ -5725,30 +4821,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableList'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aList], ); - 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(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as List?; } Future?> callFlutterEchoNullableMap( @@ -5757,31 +4847,25 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableMap'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aMap], ); - 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 Map?) - ?.cast(); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return (pigeonVar_replyValue as Map?) + ?.cast(); } Future callFlutterEchoNullableEnum( @@ -5790,30 +4874,24 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableEnum'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, anEnum], ); - 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 ProxyApiTestEnum?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as ProxyApiTestEnum?; } Future callFlutterEchoNullableProxyApi( @@ -5822,95 +4900,71 @@ class ProxyApiTestClass extends ProxyApiSuperClass final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoNullableProxyApi'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aProxyApi], ); - 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 ProxyApiSuperClass?); - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as ProxyApiSuperClass?; } Future callFlutterNoopAsync() async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterNoopAsync'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); } Future callFlutterEchoAsyncString(String aString) async { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiTestClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiTestClass.callFlutterEchoAsyncString'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); final Future pigeonVar_sendFuture = pigeonVar_channel.send( [this, aString], ); - 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?)!; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: false, + ); + return pigeonVar_replyValue! as String; } @override @@ -5991,31 +5045,24 @@ class ProxyApiSuperClass extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiSuperClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiSuperClass.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); }(); } @@ -6046,8 +5093,7 @@ class ProxyApiSuperClass extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiSuperClass.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6056,16 +5102,8 @@ class ProxyApiSuperClass extends PigeonInternalProxyApiBaseClass { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiSuperClass.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.pigeon_integration_tests.ProxyApiSuperClass.pigeon_newInstance was null, expected non-null int.', - ); + final List args = message! as List; + final int arg_pigeon_instanceIdentifier = args[0]! as int; try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( @@ -6074,7 +5112,7 @@ class ProxyApiSuperClass extends PigeonInternalProxyApiBaseClass { pigeon_binaryMessenger: pigeon_binaryMessenger, pigeon_instanceManager: pigeon_instanceManager, ), - arg_pigeon_instanceIdentifier!, + arg_pigeon_instanceIdentifier, ); return wrapResponse(empty: true); } on PlatformException catch (e) { @@ -6093,30 +5131,23 @@ class ProxyApiSuperClass extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecProxyApiSuperClass; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiSuperClass.aSuperMethod'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); } @override @@ -6175,8 +5206,7 @@ class ProxyApiInterface extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6185,16 +5215,8 @@ class ProxyApiInterface extends PigeonInternalProxyApiBaseClass { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.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.pigeon_integration_tests.ProxyApiInterface.pigeon_newInstance was null, expected non-null int.', - ); + final List args = message! as List; + final int arg_pigeon_instanceIdentifier = args[0]! as int; try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( @@ -6203,7 +5225,7 @@ class ProxyApiInterface extends PigeonInternalProxyApiBaseClass { pigeon_binaryMessenger: pigeon_binaryMessenger, pigeon_instanceManager: pigeon_instanceManager, ), - arg_pigeon_instanceIdentifier!, + arg_pigeon_instanceIdentifier, ); return wrapResponse(empty: true); } on PlatformException catch (e) { @@ -6218,8 +5240,7 @@ class ProxyApiInterface extends PigeonInternalProxyApiBaseClass { } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.anInterfaceMethod', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6228,20 +5249,12 @@ class ProxyApiInterface extends PigeonInternalProxyApiBaseClass { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.anInterfaceMethod was null.', - ); - final List args = (message as List?)!; - final ProxyApiInterface? arg_pigeon_instance = - (args[0] as ProxyApiInterface?); - assert( - arg_pigeon_instance != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ProxyApiInterface.anInterfaceMethod was null, expected non-null ProxyApiInterface.', - ); + final List args = message! as List; + final ProxyApiInterface arg_pigeon_instance = + args[0]! as ProxyApiInterface; try { - (anInterfaceMethod ?? arg_pigeon_instance!.anInterfaceMethod)?.call( - arg_pigeon_instance!, + (anInterfaceMethod ?? arg_pigeon_instance.anInterfaceMethod)?.call( + arg_pigeon_instance, ); return wrapResponse(empty: true); } on PlatformException catch (e) { @@ -6290,31 +5303,24 @@ class ClassWithApiRequirement extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecClassWithApiRequirement; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ClassWithApiRequirement.pigeon_defaultConstructor'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); }(); } @@ -6345,8 +5351,7 @@ class ClassWithApiRequirement extends PigeonInternalProxyApiBaseClass { ); final BinaryMessenger? binaryMessenger = pigeon_binaryMessenger; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.ClassWithApiRequirement.pigeon_newInstance', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -6355,16 +5360,8 @@ class ClassWithApiRequirement extends PigeonInternalProxyApiBaseClass { pigeonVar_channel.setMessageHandler(null); } else { pigeonVar_channel.setMessageHandler((Object? message) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.ClassWithApiRequirement.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.pigeon_integration_tests.ClassWithApiRequirement.pigeon_newInstance was null, expected non-null int.', - ); + final List args = message! as List; + final int arg_pigeon_instanceIdentifier = args[0]! as int; try { (pigeon_instanceManager ?? PigeonInstanceManager.instance) .addHostCreatedInstance( @@ -6373,7 +5370,7 @@ class ClassWithApiRequirement extends PigeonInternalProxyApiBaseClass { pigeon_binaryMessenger: pigeon_binaryMessenger, pigeon_instanceManager: pigeon_instanceManager, ), - arg_pigeon_instanceIdentifier!, + arg_pigeon_instanceIdentifier, ); return wrapResponse(empty: true); } on PlatformException catch (e) { @@ -6392,30 +5389,23 @@ class ClassWithApiRequirement extends PigeonInternalProxyApiBaseClass { final _PigeonInternalProxyApiBaseCodec pigeonChannelCodec = _pigeonVar_codecClassWithApiRequirement; final BinaryMessenger? pigeonVar_binaryMessenger = pigeon_binaryMessenger; - const String pigeonVar_channelName = + const pigeonVar_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.ClassWithApiRequirement.aMethod'; - final BasicMessageChannel pigeonVar_channel = - BasicMessageChannel( - pigeonVar_channelName, - pigeonChannelCodec, - binaryMessenger: pigeonVar_binaryMessenger, - ); + final 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; - } + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); } @override diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/pubspec.yaml b/packages/pigeon/platform_tests/shared_test_plugin_code/pubspec.yaml index 995b01de0f50..eb4825f64344 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/pubspec.yaml +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/pubspec.yaml @@ -18,6 +18,7 @@ dependencies: sdk: flutter integration_test: sdk: flutter + meta: ^1.17.0 mockito: ^5.4.4 dev_dependencies: diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/equality_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/equality_test.dart new file mode 100644 index 000000000000..2fb8d597a3fa --- /dev/null +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/equality_test.dart @@ -0,0 +1,240 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_test_plugin_code/src/generated/core_tests.gen.dart'; +import 'package:shared_test_plugin_code/src/generated/non_null_fields.gen.dart'; +import 'package:shared_test_plugin_code/test_types.dart'; + +void main() { + test('NaN equality', () { + final list = [double.nan]; + final map = {1: double.nan}; + final all1 = AllNullableTypes( + aNullableDouble: double.nan, + doubleList: list, + recursiveClassList: [ + AllNullableTypes(aNullableDouble: double.nan), + ], + map: map, + ); + final all2 = AllNullableTypes( + aNullableDouble: double.nan, + doubleList: list, + recursiveClassList: [ + AllNullableTypes(aNullableDouble: double.nan), + ], + map: map, + ); + + expect(all1, all2); + expect(all1.hashCode, all2.hashCode); + }); + + test('Nested collection equality', () { + final all1 = AllNullableTypes( + listList: >[ + [1, 2], + ], + mapMap: >{ + 1: {'a': 'b'}, + }, + ); + final all2 = AllNullableTypes( + listList: >[ + [1, 2], + ], + mapMap: >{ + 1: {'a': 'b'}, + }, + ); + + expect(all1, all2); + expect(all1.hashCode, all2.hashCode); + }); + + test('Cross-type equality returns false', () { + final a = AllNullableTypes(aNullableInt: 1); + final b = AllNullableTypesWithoutRecursion(aNullableInt: 1); + // ignore: unrelated_type_equality_checks + expect(a == b, isFalse); + // ignore: unrelated_type_equality_checks + expect(b == a, isFalse); + }); + + test('non-null fields equality', () { + final request1 = NonNullFieldSearchRequest(query: 'hello'); + final request2 = NonNullFieldSearchRequest(query: 'hello'); + final request3 = NonNullFieldSearchRequest(query: 'world'); + + expect(request1, request2); + expect(request1, isNot(request3)); + expect(request1.hashCode, request2.hashCode); + }); + + group('deep equality', () { + final correctList = ['a', 2, 'three']; + final List matchingList = correctList.toList(); + final differentList = ['a', 2, 'three', 4.0]; + final correctMap = {'a': 1, 'b': 2, 'c': 'three'}; + final matchingMap = {...correctMap}; + final differentKeyMap = {'a': 1, 'b': 2, 'd': 'three'}; + final differentValueMap = {'a': 1, 'b': 2, 'c': 'five'}; + final correctListInMap = { + 'a': 1, + 'b': 2, + 'c': correctList, + }; + final matchingListInMap = { + 'a': 1, + 'b': 2, + 'c': matchingList, + }; + final differentListInMap = { + 'a': 1, + 'b': 2, + 'c': differentList, + }; + final correctMapInList = ['a', 2, correctMap]; + final matchingMapInList = ['a', 2, matchingMap]; + final differentKeyMapInList = ['a', 2, differentKeyMap]; + final differentValueMapInList = ['a', 2, differentValueMap]; + + test('equality method correctly checks deep equality', () { + final AllNullableTypes generic = genericAllNullableTypes; + final AllNullableTypes identical = AllNullableTypes.decode( + generic.encode(), + ); + expect(identical, generic); + }); + + test('equality method correctly identifies non-matching classes', () { + final AllNullableTypes generic = genericAllNullableTypes; + final allNull = AllNullableTypes(); + expect(allNull == generic, false); + }); + + test( + 'equality method correctly identifies non-matching lists in classes', + () { + final withList = AllNullableTypes(list: correctList); + final withDifferentList = AllNullableTypes(list: differentList); + expect(withList == withDifferentList, false); + }, + ); + + test( + 'equality method correctly identifies matching -but unique- lists in classes', + () { + final withList = AllNullableTypes(list: correctList); + final withDifferentList = AllNullableTypes(list: matchingList); + expect(withList, withDifferentList); + }, + ); + + test( + 'equality method correctly identifies non-matching keys in maps in classes', + () { + final withMap = AllNullableTypes(map: correctMap); + final withDifferentMap = AllNullableTypes(map: differentKeyMap); + expect(withMap == withDifferentMap, false); + }, + ); + + test( + 'equality method correctly identifies non-matching values in maps in classes', + () { + final withMap = AllNullableTypes(map: correctMap); + final withDifferentMap = AllNullableTypes(map: differentValueMap); + expect(withMap == withDifferentMap, false); + }, + ); + + test( + 'equality method correctly identifies matching -but unique- maps in classes', + () { + final withMap = AllNullableTypes(map: correctMap); + final withDifferentMap = AllNullableTypes(map: matchingMap); + expect(withMap, withDifferentMap); + }, + ); + test('signed zero equality', () { + final v1 = AllNullableTypes(aNullableDouble: 0.0); + final v2 = AllNullableTypes(aNullableDouble: -0.0); + expect(v1, v2); + expect(v1.hashCode, v2.hashCode); + }); + test('signed zero map key equality', () { + final v1 = AllNullableTypes(map: {0.0: 'a'}); + final v2 = AllNullableTypes(map: {-0.0: 'a'}); + expect(v1, v2); + expect(v1.hashCode, v2.hashCode); + }); + test('signed zero map value equality', () { + final v1 = AllNullableTypes(map: {'a': 0.0}); + final v2 = AllNullableTypes(map: {'a': -0.0}); + expect(v1, v2); + expect(v1.hashCode, v2.hashCode); + }); + test('signed zero nested list equality', () { + final v1 = AllNullableTypes(doubleList: [0.0]); + final v2 = AllNullableTypes(doubleList: [-0.0]); + expect(v1, v2); + expect(v1.hashCode, v2.hashCode); + }); + + test( + 'equality method correctly identifies non-matching lists nested in maps in classes', + () { + final withListInMap = AllNullableTypes(map: correctListInMap); + final withDifferentListInMap = AllNullableTypes( + map: differentListInMap, + ); + expect(withListInMap == withDifferentListInMap, false); + }, + ); + + test( + 'equality method correctly identifies matching -but unique- lists nested in maps in classes', + () { + final withListInMap = AllNullableTypes(map: correctListInMap); + final withDifferentListInMap = AllNullableTypes(map: matchingListInMap); + expect(withListInMap, withDifferentListInMap); + }, + ); + + test( + 'equality method correctly identifies non-matching keys in maps nested in lists in classes', + () { + final withMapInList = AllNullableTypes(list: correctMapInList); + final withDifferentMapInList = AllNullableTypes( + list: differentKeyMapInList, + ); + expect(withMapInList == withDifferentMapInList, false); + }, + ); + + test( + 'equality method correctly identifies non-matching values in maps nested in lists in classes', + () { + final withMapInList = AllNullableTypes(list: correctMapInList); + final withDifferentMapInList = AllNullableTypes( + list: differentValueMapInList, + ); + expect(withMapInList == withDifferentMapInList, false); + }, + ); + + test( + 'equality method correctly identifies matching -but unique- maps nested in lists in classes', + () { + final withMapInList = AllNullableTypes(list: correctMapInList); + final withDifferentMapInList = AllNullableTypes( + list: matchingMapInList, + ); + expect(withMapInList, withDifferentMapInList); + }, + ); + }); +} diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/generated_dart_test_code_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/generated_dart_test_code_test.dart index 6c1b4e5510e8..e8046afc4545 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/generated_dart_test_code_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/generated_dart_test_code_test.dart @@ -6,10 +6,7 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:shared_test_plugin_code/src/generated/core_tests.gen.dart' - show AllNullableTypes; import 'package:shared_test_plugin_code/src/generated/message.gen.dart'; -import 'package:shared_test_plugin_code/test_types.dart'; import 'test_message.gen.dart'; @@ -44,191 +41,9 @@ class MockNested implements TestNestedApi { void main() { TestWidgetsFlutterBinding.ensureInitialized(); - group('equality method', () { - final List correctList = ['a', 2, 'three']; - final List matchingList = correctList.toList(); - final List differentList = ['a', 2, 'three', 4.0]; - final Map correctMap = { - 'a': 1, - 'b': 2, - 'c': 'three', - }; - final Map matchingMap = {...correctMap}; - final Map differentKeyMap = { - 'a': 1, - 'b': 2, - 'd': 'three', - }; - final Map differentValueMap = { - 'a': 1, - 'b': 2, - 'c': 'five', - }; - final Map correctListInMap = { - 'a': 1, - 'b': 2, - 'c': correctList, - }; - final Map matchingListInMap = { - 'a': 1, - 'b': 2, - 'c': matchingList, - }; - final Map differentListInMap = { - 'a': 1, - 'b': 2, - 'c': differentList, - }; - final List correctMapInList = ['a', 2, correctMap]; - final List matchingMapInList = ['a', 2, matchingMap]; - final List differentKeyMapInList = [ - 'a', - 2, - differentKeyMap, - ]; - final List differentValueMapInList = [ - 'a', - 2, - differentValueMap, - ]; - - test('equality method correctly checks deep equality', () { - final AllNullableTypes generic = genericAllNullableTypes; - final AllNullableTypes identical = AllNullableTypes.decode( - generic.encode(), - ); - expect(identical, generic); - }); - - test('equality method correctly identifies non-matching classes', () { - final AllNullableTypes generic = genericAllNullableTypes; - final AllNullableTypes allNull = AllNullableTypes(); - expect(allNull == generic, false); - }); - - test( - 'equality method correctly identifies non-matching lists in classes', - () { - final AllNullableTypes withList = AllNullableTypes(list: correctList); - final AllNullableTypes withDifferentList = AllNullableTypes( - list: differentList, - ); - expect(withList == withDifferentList, false); - }, - ); - - test( - 'equality method correctly identifies matching -but unique- lists in classes', - () { - final AllNullableTypes withList = AllNullableTypes(list: correctList); - final AllNullableTypes withDifferentList = AllNullableTypes( - list: matchingList, - ); - expect(withList, withDifferentList); - }, - ); - - test( - 'equality method correctly identifies non-matching keys in maps in classes', - () { - final AllNullableTypes withMap = AllNullableTypes(map: correctMap); - final AllNullableTypes withDifferentMap = AllNullableTypes( - map: differentKeyMap, - ); - expect(withMap == withDifferentMap, false); - }, - ); - - test( - 'equality method correctly identifies non-matching values in maps in classes', - () { - final AllNullableTypes withMap = AllNullableTypes(map: correctMap); - final AllNullableTypes withDifferentMap = AllNullableTypes( - map: differentValueMap, - ); - expect(withMap == withDifferentMap, false); - }, - ); - - test( - 'equality method correctly identifies matching -but unique- maps in classes', - () { - final AllNullableTypes withMap = AllNullableTypes(map: correctMap); - final AllNullableTypes withDifferentMap = AllNullableTypes( - map: matchingMap, - ); - expect(withMap, withDifferentMap); - }, - ); - - test( - 'equality method correctly identifies non-matching lists nested in maps in classes', - () { - final AllNullableTypes withListInMap = AllNullableTypes( - map: correctListInMap, - ); - final AllNullableTypes withDifferentListInMap = AllNullableTypes( - map: differentListInMap, - ); - expect(withListInMap == withDifferentListInMap, false); - }, - ); - - test( - 'equality method correctly identifies matching -but unique- lists nested in maps in classes', - () { - final AllNullableTypes withListInMap = AllNullableTypes( - map: correctListInMap, - ); - final AllNullableTypes withDifferentListInMap = AllNullableTypes( - map: matchingListInMap, - ); - expect(withListInMap, withDifferentListInMap); - }, - ); - - test( - 'equality method correctly identifies non-matching keys in maps nested in lists in classes', - () { - final AllNullableTypes withMapInList = AllNullableTypes( - list: correctMapInList, - ); - final AllNullableTypes withDifferentMapInList = AllNullableTypes( - list: differentKeyMapInList, - ); - expect(withMapInList == withDifferentMapInList, false); - }, - ); - - test( - 'equality method correctly identifies non-matching values in maps nested in lists in classes', - () { - final AllNullableTypes withMapInList = AllNullableTypes( - list: correctMapInList, - ); - final AllNullableTypes withDifferentMapInList = AllNullableTypes( - list: differentValueMapInList, - ); - expect(withMapInList == withDifferentMapInList, false); - }, - ); - - test( - 'equality method correctly identifies matching -but unique- maps nested in lists in classes', - () { - final AllNullableTypes withMapInList = AllNullableTypes( - list: correctMapInList, - ); - final AllNullableTypes withDifferentMapInList = AllNullableTypes( - list: matchingMapInList, - ); - expect(withMapInList, withDifferentMapInList); - }, - ); - }); test('simple', () async { - final MessageNestedApi api = MessageNestedApi(); - final MockNested mock = MockNested(); + final api = MessageNestedApi(); + final mock = MockNested(); TestNestedApi.setUp(mock); final MessageSearchReply reply = await api.search( MessageNested()..request = null, @@ -238,8 +53,8 @@ void main() { }); test('nested', () async { - final MessageApi api = MessageApi(); - final Mock mock = Mock(); + final api = MessageApi(); + final mock = Mock(); TestHostApi.setUp(mock); final MessageSearchReply reply = await api.search( MessageSearchRequest()..query = 'foo', @@ -249,15 +64,15 @@ void main() { }); test('no-arg calls', () async { - final MessageApi api = MessageApi(); - final Mock mock = Mock(); + final api = MessageApi(); + final mock = Mock(); TestHostApi.setUp(mock); await api.initialize(); expect(mock.log, ['initialize']); }); test('calling methods with null', () async { - final Mock mock = Mock(); + final mock = Mock(); TestHostApi.setUp(mock); expect( await const BasicMessageChannel( @@ -266,22 +81,15 @@ void main() { ).send([null]), isEmpty, ); - try { - await const BasicMessageChannel( - 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search', - StandardMessageCodec(), - ).send([null]) - as List?; - expect(true, isFalse); // should not reach here - } catch (error) { - expect(error, isAssertionError); - expect( - error.toString(), - contains( - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search was null, expected non-null MessageSearchRequest.', - ), - ); - } + expect( + () async => + await const BasicMessageChannel( + 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search', + StandardMessageCodec(), + ).send([null]) + as List?, + throwsA(isA()), + ); expect(mock.log, ['initialize']); }); } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/instance_manager_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/instance_manager_test.dart index c6c4506c972e..ed38f8f53e45 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/instance_manager_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/instance_manager_test.dart @@ -11,13 +11,11 @@ import 'package:shared_test_plugin_code/src/generated/proxy_api_tests.gen.dart'; void main() { group('InstanceManager', () { test('addHostCreatedInstance', () { - final PigeonInstanceManager instanceManager = PigeonInstanceManager( + final instanceManager = PigeonInstanceManager( onWeakReferenceRemoved: (_) {}, ); - final CopyableObject object = CopyableObject( - pigeon_instanceManager: instanceManager, - ); + final object = CopyableObject(pigeon_instanceManager: instanceManager); instanceManager.addHostCreatedInstance(object, 0); @@ -29,13 +27,11 @@ void main() { }); test('addHostCreatedInstance prevents already used objects and ids', () { - final PigeonInstanceManager instanceManager = PigeonInstanceManager( + final instanceManager = PigeonInstanceManager( onWeakReferenceRemoved: (_) {}, ); - final CopyableObject object = CopyableObject( - pigeon_instanceManager: instanceManager, - ); + final object = CopyableObject(pigeon_instanceManager: instanceManager); instanceManager.addHostCreatedInstance(object, 0); @@ -54,13 +50,11 @@ void main() { }); test('addFlutterCreatedInstance', () { - final PigeonInstanceManager instanceManager = PigeonInstanceManager( + final instanceManager = PigeonInstanceManager( onWeakReferenceRemoved: (_) {}, ); - final CopyableObject object = CopyableObject( - pigeon_instanceManager: instanceManager, - ); + final object = CopyableObject(pigeon_instanceManager: instanceManager); instanceManager.addDartCreatedInstance(object); @@ -71,15 +65,13 @@ void main() { test('removeWeakReference', () { int? weakInstanceId; - final PigeonInstanceManager instanceManager = PigeonInstanceManager( + final instanceManager = PigeonInstanceManager( onWeakReferenceRemoved: (int instanceId) { weakInstanceId = instanceId; }, ); - final CopyableObject object = CopyableObject( - pigeon_instanceManager: instanceManager, - ); + final object = CopyableObject(pigeon_instanceManager: instanceManager); instanceManager.addHostCreatedInstance(object, 0); @@ -92,13 +84,11 @@ void main() { }); test('removeWeakReference removes only weak reference', () { - final PigeonInstanceManager instanceManager = PigeonInstanceManager( + final instanceManager = PigeonInstanceManager( onWeakReferenceRemoved: (_) {}, ); - final CopyableObject object = CopyableObject( - pigeon_instanceManager: instanceManager, - ); + final object = CopyableObject(pigeon_instanceManager: instanceManager); instanceManager.addHostCreatedInstance(object, 0); @@ -110,13 +100,11 @@ void main() { }); test('remove', () { - final PigeonInstanceManager instanceManager = PigeonInstanceManager( + final instanceManager = PigeonInstanceManager( onWeakReferenceRemoved: (_) {}, ); - final CopyableObject object = CopyableObject( - pigeon_instanceManager: instanceManager, - ); + final object = CopyableObject(pigeon_instanceManager: instanceManager); instanceManager.addHostCreatedInstance(object, 0); instanceManager.removeWeakReference(object); @@ -125,26 +113,22 @@ void main() { }); test('remove throws AssertionError if weak reference still exists', () { - final PigeonInstanceManager instanceManager = PigeonInstanceManager( + final instanceManager = PigeonInstanceManager( onWeakReferenceRemoved: (_) {}, ); - final CopyableObject object = CopyableObject( - pigeon_instanceManager: instanceManager, - ); + final object = CopyableObject(pigeon_instanceManager: instanceManager); instanceManager.addDartCreatedInstance(object); expect(() => instanceManager.remove(0), throwsAssertionError); }); test('getInstance can add a new weak reference', () { - final PigeonInstanceManager instanceManager = PigeonInstanceManager( + final instanceManager = PigeonInstanceManager( onWeakReferenceRemoved: (_) {}, ); - final CopyableObject object = CopyableObject( - pigeon_instanceManager: instanceManager, - ); + final object = CopyableObject(pigeon_instanceManager: instanceManager); instanceManager.addHostCreatedInstance(object, 0); instanceManager.removeWeakReference(object); @@ -157,8 +141,8 @@ void main() { test( 'addDartCreatedInstance should add finalizer to original object', () async { - bool weakReferencedRemovedCalled = false; - final PigeonInstanceManager instanceManager = PigeonInstanceManager( + var weakReferencedRemovedCalled = false; + final instanceManager = PigeonInstanceManager( onWeakReferenceRemoved: (_) { weakReferencedRemovedCalled = true; }, @@ -180,8 +164,8 @@ void main() { test( 'addHostCreatedInstance should not add finalizer to original object', () async { - bool weakReferencedRemovedCalled = false; - final PigeonInstanceManager instanceManager = PigeonInstanceManager( + var weakReferencedRemovedCalled = false; + final instanceManager = PigeonInstanceManager( onWeakReferenceRemoved: (_) { weakReferencedRemovedCalled = true; }, @@ -203,7 +187,7 @@ void main() { testWidgets( 'instantiating default InstanceManager does not make a message call', (WidgetTester tester) async { - bool messageCallMade = false; + var messageCallMade = false; TestDefaultBinaryMessengerBinding .instance .defaultBinaryMessenger @@ -223,7 +207,7 @@ void main() { testWidgets( 'default InstanceManager does not make message call when weak reference is removed', (WidgetTester tester) async { - bool messageCallMade = false; + var messageCallMade = false; TestDefaultBinaryMessengerBinding .instance .defaultBinaryMessenger diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/multiple_arity_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/multiple_arity_test.dart index f7c8585bbdb5..2209c6936a45 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/multiple_arity_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/multiple_arity_test.dart @@ -22,7 +22,7 @@ void main() { ).thenAnswer((Invocation realInvocation) async { final Object input = MultipleArityHostApi.pigeonChannelCodec .decodeMessage(realInvocation.positionalArguments[1] as ByteData?)!; - final List args = input as List; + final args = input as List; final int x = (args[0] as int?)!; final int y = (args[1] as int?)!; return MultipleArityHostApi.pigeonChannelCodec.encodeMessage([ @@ -30,9 +30,7 @@ void main() { ]); }); - final MultipleArityHostApi api = MultipleArityHostApi( - binaryMessenger: mockMessenger, - ); + final api = MultipleArityHostApi(binaryMessenger: mockMessenger); final int result = await api.subtract(30, 10); expect(result, 20); }); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/non_null_fields_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/non_null_fields_test.dart index c05f31f03331..6e051d13e5ac 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/non_null_fields_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/non_null_fields_test.dart @@ -7,9 +7,7 @@ import 'package:shared_test_plugin_code/src/generated/non_null_fields.gen.dart'; void main() { test('test constructor', () { - final NonNullFieldSearchRequest request = NonNullFieldSearchRequest( - query: 'what?', - ); + final request = NonNullFieldSearchRequest(query: 'what?'); expect(request.query, 'what?'); }); } diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_fields_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_fields_test.dart index 071cef316ec7..09033590b636 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_fields_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_fields_test.dart @@ -7,12 +7,9 @@ import 'package:shared_test_plugin_code/src/generated/null_fields.gen.dart'; void main() { test('test constructor with values', () { - final NullFieldsSearchRequest request = NullFieldsSearchRequest( - query: 'query', - identifier: 1, - ); + final request = NullFieldsSearchRequest(query: 'query', identifier: 1); - final NullFieldsSearchReply reply = NullFieldsSearchReply( + final reply = NullFieldsSearchReply( result: 'result', error: 'error', indices: [1, 2, 3], @@ -28,15 +25,13 @@ void main() { }); test('test request constructor with nulls', () { - final NullFieldsSearchRequest request = NullFieldsSearchRequest( - identifier: 1, - ); + final request = NullFieldsSearchRequest(identifier: 1); expect(request.query, isNull); }); test('test reply constructor with nulls', () { - final NullFieldsSearchReply reply = NullFieldsSearchReply(); + final reply = NullFieldsSearchReply(); expect(reply.result, isNull); expect(reply.error, isNull); @@ -96,28 +91,20 @@ void main() { }); test('test request encode with values', () { - final NullFieldsSearchRequest request = NullFieldsSearchRequest( - query: 'query', - identifier: 1, - ); + final request = NullFieldsSearchRequest(query: 'query', identifier: 1); expect(request.encode(), ['query', 1]); }); test('test request encode with null', () { - final NullFieldsSearchRequest request = NullFieldsSearchRequest( - identifier: 1, - ); + final request = NullFieldsSearchRequest(identifier: 1); expect(request.encode(), [null, 1]); }); test('test reply encode with values', () { - final NullFieldsSearchRequest request = NullFieldsSearchRequest( - query: 'query', - identifier: 1, - ); - final NullFieldsSearchReply reply = NullFieldsSearchReply( + final request = NullFieldsSearchRequest(query: 'query', identifier: 1); + final reply = NullFieldsSearchReply( result: 'result', error: 'error', indices: [1, 2, 3], @@ -135,7 +122,7 @@ void main() { }); test('test reply encode with nulls', () { - final NullFieldsSearchReply reply = NullFieldsSearchReply(); + final reply = NullFieldsSearchReply(); expect(reply.encode(), [null, null, null, null, null]); }); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_safe_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_safe_test.dart index 405f48343b64..e50136696b62 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_safe_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_safe_test.dart @@ -26,30 +26,30 @@ void main() { TestWidgetsFlutterBinding.ensureInitialized(); test('with values filled', () { - final FlutterSearchReply reply = FlutterSearchReply() + final reply = FlutterSearchReply() ..result = 'foo' ..error = 'bar'; - final List encoded = reply.encode() as List; + final encoded = reply.encode() as List; final FlutterSearchReply decoded = FlutterSearchReply.decode(encoded); expect(reply.result, decoded.result); expect(reply.error, decoded.error); }); test('with null value', () { - final FlutterSearchReply reply = FlutterSearchReply() + final reply = FlutterSearchReply() ..result = 'foo' ..error = null; - final List encoded = reply.encode() as List; + final encoded = reply.encode() as List; final FlutterSearchReply decoded = FlutterSearchReply.decode(encoded); expect(reply.result, decoded.result); expect(reply.error, decoded.error); }); test('send/receive', () async { - final FlutterSearchRequest request = FlutterSearchRequest()..query = 'hey'; - final FlutterSearchReply reply = FlutterSearchReply()..result = 'ho'; + final request = FlutterSearchRequest()..query = 'hey'; + final reply = FlutterSearchReply()..result = 'ho'; final BinaryMessenger mockMessenger = MockBinaryMessenger(); - final Completer completer = Completer(); + final completer = Completer(); completer.complete(Api.pigeonChannelCodec.encodeMessage([reply])); final Future sendResult = completer.future; when( @@ -58,15 +58,15 @@ void main() { any, ), ).thenAnswer((Invocation realInvocation) => sendResult); - final Api api = Api(binaryMessenger: mockMessenger); + final api = Api(binaryMessenger: mockMessenger); final FlutterSearchReply readReply = await api.search(request); expect(readReply, isNotNull); expect(reply.result, readReply.result); }); test('send/receive list classes', () async { - final FlutterSearchRequest request = FlutterSearchRequest()..query = 'hey'; - final FlutterSearchRequests requests = FlutterSearchRequests() + final request = FlutterSearchRequest()..query = 'hey'; + final requests = FlutterSearchRequests() ..requests = [request]; final BinaryMessenger mockMessenger = MockBinaryMessenger(); echoOneArgument( @@ -74,7 +74,7 @@ void main() { 'dev.flutter.pigeon.pigeon_integration_tests.Api.echo', Api.pigeonChannelCodec, ); - final Api api = Api(binaryMessenger: mockMessenger); + final api = Api(binaryMessenger: mockMessenger); final FlutterSearchRequests echo = await api.echo(requests); expect(echo.requests!.length, 1); expect((echo.requests![0] as FlutterSearchRequest?)!.query, 'hey'); @@ -87,21 +87,20 @@ void main() { 'dev.flutter.pigeon.pigeon_integration_tests.Api.anInt', Api.pigeonChannelCodec, ); - final Api api = Api(binaryMessenger: mockMessenger); + final api = Api(binaryMessenger: mockMessenger); final int result = await api.anInt(1); expect(result, 1); }); test('return null to nonnull', () async { final BinaryMessenger mockMessenger = MockBinaryMessenger(); - const String channel = - 'dev.flutter.pigeon.pigeon_integration_tests.Api.anInt'; + const channel = 'dev.flutter.pigeon.pigeon_integration_tests.Api.anInt'; when(mockMessenger.send(channel, any)).thenAnswer(( Invocation realInvocation, ) async { return Api.pigeonChannelCodec.encodeMessage([null]); }); - final Api api = Api(binaryMessenger: mockMessenger); + final api = Api(binaryMessenger: mockMessenger); expect( () async => api.anInt(1), throwsA(const TypeMatcher()), @@ -110,22 +109,20 @@ void main() { test('send null parameter', () async { final BinaryMessenger mockMessenger = MockBinaryMessenger(); - const String channel = + const channel = 'dev.flutter.pigeon.pigeon_integration_tests.NullableArgHostApi.doit'; when(mockMessenger.send(channel, any)).thenAnswer(( Invocation realInvocation, ) async { return Api.pigeonChannelCodec.encodeMessage([123]); }); - final NullableArgHostApi api = NullableArgHostApi( - binaryMessenger: mockMessenger, - ); + final api = NullableArgHostApi(binaryMessenger: mockMessenger); expect(await api.doit(null), 123); }); test('send null collection parameter', () async { final BinaryMessenger mockMessenger = MockBinaryMessenger(); - const String channel = + const channel = 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionArgHostApi.doit'; when(mockMessenger.send(channel, any)).thenAnswer(( Invocation realInvocation, @@ -134,20 +131,17 @@ void main() { ['123'], ]); }); - final NullableCollectionArgHostApi api = NullableCollectionArgHostApi( - binaryMessenger: mockMessenger, - ); + final api = NullableCollectionArgHostApi(binaryMessenger: mockMessenger); expect(await api.doit(null), ['123']); }); test('receive null parameters', () { - final MockNullableArgFlutterApi mockFlutterApi = - MockNullableArgFlutterApi(); + final mockFlutterApi = MockNullableArgFlutterApi(); when(mockFlutterApi.doit(null)).thenReturn(14); NullableArgFlutterApi.setUp(mockFlutterApi); - final Completer resultCompleter = Completer(); + final resultCompleter = Completer(); binding.defaultBinaryMessenger.handlePlatformMessage( 'dev.flutter.pigeon.pigeon_integration_tests.NullableArgFlutterApi.doit', NullableArgFlutterApi.pigeonChannelCodec.encodeMessage([null]), @@ -168,13 +162,12 @@ void main() { }); test('receive null collection parameters', () { - final MockNullableCollectionArgFlutterApi mockFlutterApi = - MockNullableCollectionArgFlutterApi(); + final mockFlutterApi = MockNullableCollectionArgFlutterApi(); when(mockFlutterApi.doit(null)).thenReturn(['14']); NullableCollectionArgFlutterApi.setUp(mockFlutterApi); - final Completer> resultCompleter = Completer>(); + final resultCompleter = Completer>(); binding.defaultBinaryMessenger.handlePlatformMessage( 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionArgFlutterApi.doit', NullableCollectionArgFlutterApi.pigeonChannelCodec.encodeMessage( @@ -201,7 +194,7 @@ void main() { test('receive null return', () async { final BinaryMessenger mockMessenger = MockBinaryMessenger(); - const String channel = + const channel = 'dev.flutter.pigeon.pigeon_integration_tests.NullableReturnHostApi.doit'; when(mockMessenger.send(channel, any)).thenAnswer(( Invocation realInvocation, @@ -210,15 +203,13 @@ void main() { null, ]); }); - final NullableReturnHostApi api = NullableReturnHostApi( - binaryMessenger: mockMessenger, - ); + final api = NullableReturnHostApi(binaryMessenger: mockMessenger); expect(await api.doit(), null); }); test('receive null collection return', () async { final BinaryMessenger mockMessenger = MockBinaryMessenger(); - const String channel = + const channel = 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionReturnHostApi.doit'; when(mockMessenger.send(channel, any)).thenAnswer(( Invocation realInvocation, @@ -227,20 +218,17 @@ void main() { [null], ); }); - final NullableCollectionReturnHostApi api = NullableCollectionReturnHostApi( - binaryMessenger: mockMessenger, - ); + final api = NullableCollectionReturnHostApi(binaryMessenger: mockMessenger); expect(await api.doit(), null); }); test('send null return', () async { - final MockNullableReturnFlutterApi mockFlutterApi = - MockNullableReturnFlutterApi(); + final mockFlutterApi = MockNullableReturnFlutterApi(); when(mockFlutterApi.doit()).thenReturn(null); NullableReturnFlutterApi.setUp(mockFlutterApi); - final Completer resultCompleter = Completer(); + final resultCompleter = Completer(); unawaited( binding.defaultBinaryMessenger.handlePlatformMessage( 'dev.flutter.pigeon.pigeon_integration_tests.NullableReturnFlutterApi.doit', @@ -258,14 +246,12 @@ void main() { }); test('send null collection return', () async { - final MockNullableCollectionReturnFlutterApi mockFlutterApi = - MockNullableCollectionReturnFlutterApi(); + final mockFlutterApi = MockNullableCollectionReturnFlutterApi(); when(mockFlutterApi.doit()).thenReturn(null); NullableCollectionReturnFlutterApi.setUp(mockFlutterApi); - final Completer?> resultCompleter = - Completer?>(); + final resultCompleter = Completer?>(); unawaited( binding.defaultBinaryMessenger.handlePlatformMessage( 'dev.flutter.pigeon.pigeon_integration_tests.NullableCollectionReturnFlutterApi.doit', diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/primitive_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/primitive_test.dart index d81640b5e5a3..dbfc6cd78a85 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/primitive_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/primitive_test.dart @@ -20,9 +20,7 @@ void main() { 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.anInt', PrimitiveHostApi.pigeonChannelCodec, ); - final PrimitiveHostApi api = PrimitiveHostApi( - binaryMessenger: mockMessenger, - ); + final api = PrimitiveHostApi(binaryMessenger: mockMessenger); final int result = await api.anInt(1); expect(result, 1); }); @@ -34,9 +32,7 @@ void main() { 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aBoolList', PrimitiveHostApi.pigeonChannelCodec, ); - final PrimitiveHostApi api = PrimitiveHostApi( - binaryMessenger: mockMessenger, - ); + final api = PrimitiveHostApi(binaryMessenger: mockMessenger); final List result = await api.aBoolList([true]); expect(result[0], true); }); @@ -51,8 +47,7 @@ void main() { any, ), ).thenAnswer((Invocation realInvocation) { - final MessageHandler? handler = - realInvocation.positionalArguments[1] as MessageHandler?; + final handler = realInvocation.positionalArguments[1] as MessageHandler?; handler!( PrimitiveFlutterApi.pigeonChannelCodec.encodeMessage([ [true, false], @@ -70,9 +65,7 @@ void main() { 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aStringIntMap', PrimitiveHostApi.pigeonChannelCodec, ); - final PrimitiveHostApi api = PrimitiveHostApi( - binaryMessenger: mockMessenger, - ); + final api = PrimitiveHostApi(binaryMessenger: mockMessenger); final Map result = await api.aStringIntMap({ 'hello': 1, }); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/proxy_api_overrides_test.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/proxy_api_overrides_test.dart index 3c0e4b8e3341..f7d5ac0a20ea 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/proxy_api_overrides_test.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/proxy_api_overrides_test.dart @@ -9,7 +9,7 @@ void main() { test('can override ProxyApi constructors', () { PigeonOverrides.pigeon_reset(); - final ProxyApiSuperClass instance = ProxyApiSuperClass.pigeon_detached(); + final instance = ProxyApiSuperClass.pigeon_detached(); PigeonOverrides.proxyApiSuperClass_new = () => instance; expect(ProxyApiSuperClass(), instance); @@ -18,7 +18,7 @@ void main() { test('can override ProxyApi static attached fields', () { PigeonOverrides.pigeon_reset(); - final ProxyApiSuperClass instance = ProxyApiSuperClass.pigeon_detached(); + final instance = ProxyApiSuperClass.pigeon_detached(); PigeonOverrides.proxyApiTestClass_staticAttachedField = instance; expect(ProxyApiTestClass.staticAttachedField, instance); @@ -31,7 +31,7 @@ void main() { return value; }; - const String value = 'testString'; + const value = 'testString'; expect(await ProxyApiTestClass.echoStaticString(value), value); }); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_message.gen.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_message.gen.dart index 59d3481b3af9..443efc77823d 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_message.gen.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_message.gen.dart @@ -4,7 +4,7 @@ // // Autogenerated from Pigeon, 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, no_leading_underscores_for_local_identifiers +// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, unnecessary_import, no_leading_underscores_for_local_identifiers, omit_obvious_local_variable_types // ignore_for_file: avoid_relative_lib_imports import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; @@ -42,7 +42,7 @@ class _PigeonCodec extends StandardMessageCodec { Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 129: - final int? value = readValue(buffer) as int?; + final value = readValue(buffer) as int?; return value == null ? null : MessageRequestState.values[value]; case 130: return MessageSearchRequest.decode(readValue(buffer)!); @@ -81,8 +81,7 @@ abstract class TestHostApi { ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.initialize$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -112,8 +111,7 @@ abstract class TestHostApi { } } { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -126,19 +124,11 @@ abstract class TestHostApi { .setMockDecodedMessageHandler(pigeonVar_channel, ( Object? message, ) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search was null.', - ); - final List args = (message as List?)!; - final MessageSearchRequest? arg_request = - (args[0] as MessageSearchRequest?); - assert( - arg_request != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search was null, expected non-null MessageSearchRequest.', - ); + final List args = message! as List; + final MessageSearchRequest arg_request = + args[0]! as MessageSearchRequest; try { - final MessageSearchReply output = api.search(arg_request!); + final MessageSearchReply output = api.search(arg_request); return [output]; } on PlatformException catch (e) { return wrapResponse(error: e); @@ -176,8 +166,7 @@ abstract class TestNestedApi { ? '.$messageChannelSuffix' : ''; { - final BasicMessageChannel - pigeonVar_channel = BasicMessageChannel( + final pigeonVar_channel = BasicMessageChannel( 'dev.flutter.pigeon.pigeon_integration_tests.MessageNestedApi.search$messageChannelSuffix', pigeonChannelCodec, binaryMessenger: binaryMessenger, @@ -190,18 +179,10 @@ abstract class TestNestedApi { .setMockDecodedMessageHandler(pigeonVar_channel, ( Object? message, ) async { - assert( - message != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageNestedApi.search was null.', - ); - final List args = (message as List?)!; - final MessageNested? arg_nested = (args[0] as MessageNested?); - assert( - arg_nested != null, - 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageNestedApi.search was null, expected non-null MessageNested.', - ); + final List args = message! as List; + final MessageNested arg_nested = args[0]! as MessageNested; try { - final MessageSearchReply output = api.search(arg_nested!); + final MessageSearchReply output = api.search(arg_nested); return [output]; } on PlatformException catch (e) { return wrapResponse(error: e); diff --git a/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_util.dart b/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_util.dart index abea719758aa..accc779e392e 100644 --- a/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_util.dart +++ b/packages/pigeon/platform_tests/shared_test_plugin_code/test/test_util.dart @@ -16,7 +16,7 @@ void echoOneArgument( final Object input = codec.decodeMessage( realInvocation.positionalArguments[1] as ByteData?, )!; - final List args = input as List; + final args = input as List; return codec.encodeMessage([args[0]!]); }); } diff --git a/packages/pigeon/platform_tests/test_plugin/android/build.gradle b/packages/pigeon/platform_tests/test_plugin/android/build.gradle deleted file mode 100644 index 147ff9e9aceb..000000000000 --- a/packages/pigeon/platform_tests/test_plugin/android/build.gradle +++ /dev/null @@ -1,75 +0,0 @@ -group = 'com.example.test_plugin' -version = '1.0-SNAPSHOT' - -buildscript { - ext.kotlin_version = '2.2.10' - repositories { - google() - mavenCentral() - } - - dependencies { - classpath 'com.android.tools.build:gradle:8.13.1' - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" - } -} - -allprojects { - repositories { - google() - mavenCentral() - } -} - -apply plugin: 'com.android.library' -apply plugin: 'kotlin-android' - -android { - namespace = "com.example.test_plugin" - compileSdk = flutter.compileSdkVersion - - compileOptions { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 - } - - kotlinOptions { - jvmTarget = JavaVersion.VERSION_17.toString() - allWarningsAsErrors = true - } - - sourceSets { - main.java.srcDirs += 'src/main/kotlin' - } - - defaultConfig { - minSdkVersion 21 - } - - testOptions { - unitTests.includeAndroidResources = true - unitTests.returnDefaultValues = true - unitTests.all { - testLogging { - events "passed", "skipped", "failed", "standardOut", "standardError" - outputs.upToDateWhen {false} - showStandardStreams = true - } - } - } - - lint { - checkAllWarnings = true - warningsAsErrors = true - disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency', 'NewerVersionAvailable' - baseline = file("lint-baseline.xml") - } - - dependencies { - testImplementation("junit:junit:4.13.2") - testImplementation("io.mockk:mockk:1.14.5") - // org.jetbrains.kotlin:kotlin-bom artifact purpose is to align kotlin stdlib and related code versions. - // See: https://youtrack.jetbrains.com/issue/KT-55297/kotlin-stdlib-should-declare-constraints-on-kotlin-stdlib-jdk8-and-kotlin-stdlib-jdk7 - implementation(platform("org.jetbrains.kotlin:kotlin-bom:2.2.21")) - } -} diff --git a/packages/pigeon/platform_tests/test_plugin/android/build.gradle.kts b/packages/pigeon/platform_tests/test_plugin/android/build.gradle.kts new file mode 100644 index 000000000000..284efe74ecb6 --- /dev/null +++ b/packages/pigeon/platform_tests/test_plugin/android/build.gradle.kts @@ -0,0 +1,80 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + +group = "com.example.test_plugin" +version = "1.0-SNAPSHOT" + +buildscript { + val kotlinVersion = "2.3.0" + repositories { + google() + mavenCentral() + } + + dependencies { + classpath("com.android.tools.build:gradle:8.13.1") + classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion") + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +plugins { + id("com.android.library") + id("kotlin-android") +} + +kotlin { + compilerOptions { + jvmTarget = JvmTarget.fromTarget(JavaVersion.VERSION_17.toString()) + allWarningsAsErrors = true + } +} + +android { + namespace = "com.example.test_plugin" + compileSdk = flutter.compileSdkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + defaultConfig { + minSdk = 24 + } + + testOptions { + unitTests { + isIncludeAndroidResources = true + isReturnDefaultValues = true + all { + it.outputs.upToDateWhen { false } + it.testLogging { + events("passed", "skipped", "failed", "standardOut", "standardError") + showStandardStreams = true + } + } + } + } + + lint { + checkAllWarnings = true + warningsAsErrors = true + disable.addAll(setOf("AndroidGradlePluginVersion", "InvalidPackage", "GradleDependency", "NewerVersionAvailable")) + baseline = file("lint-baseline.xml") + } + + dependencies { + compileOnly("javax.annotation:javax.annotation-api:1.3.2") + testImplementation("junit:junit:4.13.2") + testImplementation("io.mockk:mockk:1.14.9") + // org.jetbrains.kotlin:kotlin-bom artifact purpose is to align kotlin stdlib and related code versions. + // See: https://youtrack.jetbrains.com/issue/KT-55297/kotlin-stdlib-should-declare-constraints-on-kotlin-stdlib-jdk8-and-kotlin-stdlib-jdk7 + implementation(platform("org.jetbrains.kotlin:kotlin-bom:2.3.10")) + } +} diff --git a/packages/pigeon/platform_tests/test_plugin/android/settings.gradle b/packages/pigeon/platform_tests/test_plugin/android/settings.gradle deleted file mode 100644 index e9328f28412e..000000000000 --- a/packages/pigeon/platform_tests/test_plugin/android/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'test_plugin' diff --git a/packages/pigeon/platform_tests/test_plugin/android/settings.gradle.kts b/packages/pigeon/platform_tests/test_plugin/android/settings.gradle.kts new file mode 100644 index 000000000000..2e32f8d43572 --- /dev/null +++ b/packages/pigeon/platform_tests/test_plugin/android/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "test_plugin" diff --git a/packages/pigeon/platform_tests/test_plugin/android/src/main/kotlin/com/example/test_plugin/CoreTests.gen.kt b/packages/pigeon/platform_tests/test_plugin/android/src/main/kotlin/com/example/test_plugin/CoreTests.gen.kt index fe73e18c0998..338a53b8e3b3 100644 --- a/packages/pigeon/platform_tests/test_plugin/android/src/main/kotlin/com/example/test_plugin/CoreTests.gen.kt +++ b/packages/pigeon/platform_tests/test_plugin/android/src/main/kotlin/com/example/test_plugin/CoreTests.gen.kt @@ -38,7 +38,36 @@ private object CoreTestsPigeonUtils { } } + fun doubleEquals(a: Double, b: Double): Boolean { + // Normalize -0.0 to 0.0 and handle NaN equality. + return (if (a == 0.0) 0.0 else a) == (if (b == 0.0) 0.0 else b) || (a.isNaN() && b.isNaN()) + } + + fun floatEquals(a: Float, b: Float): Boolean { + // Normalize -0.0 to 0.0 and handle NaN equality. + return (if (a == 0.0f) 0.0f else a) == (if (b == 0.0f) 0.0f else b) || (a.isNaN() && b.isNaN()) + } + + fun doubleHash(d: Double): Int { + // Normalize -0.0 to 0.0 and handle NaN to ensure consistent hash codes. + val normalized = if (d == 0.0) 0.0 else d + val bits = java.lang.Double.doubleToLongBits(normalized) + return (bits xor (bits ushr 32)).toInt() + } + + fun floatHash(f: Float): Int { + // Normalize -0.0 to 0.0 and handle NaN to ensure consistent hash codes. + val normalized = if (f == 0.0f) 0.0f else f + return java.lang.Float.floatToIntBits(normalized) + } + fun deepEquals(a: Any?, b: Any?): Boolean { + if (a === b) { + return true + } + if (a == null || b == null) { + return false + } if (a is ByteArray && b is ByteArray) { return a.contentEquals(b) } @@ -49,20 +78,109 @@ private object CoreTestsPigeonUtils { return a.contentEquals(b) } if (a is DoubleArray && b is DoubleArray) { - return a.contentEquals(b) + if (a.size != b.size) return false + for (i in a.indices) { + if (!doubleEquals(a[i], b[i])) return false + } + return true + } + if (a is FloatArray && b is FloatArray) { + if (a.size != b.size) return false + for (i in a.indices) { + if (!floatEquals(a[i], b[i])) return false + } + return true } if (a is Array<*> && b is Array<*>) { - return a.size == b.size && a.indices.all { deepEquals(a[it], b[it]) } + if (a.size != b.size) return false + for (i in a.indices) { + if (!deepEquals(a[i], b[i])) return false + } + return true } if (a is List<*> && b is List<*>) { - return a.size == b.size && a.indices.all { deepEquals(a[it], b[it]) } + if (a.size != b.size) return false + val iterA = a.iterator() + val iterB = b.iterator() + while (iterA.hasNext() && iterB.hasNext()) { + if (!deepEquals(iterA.next(), iterB.next())) return false + } + return true } if (a is Map<*, *> && b is Map<*, *>) { - return a.size == b.size && - a.all { (b as Map).contains(it.key) && deepEquals(it.value, b[it.key]) } + if (a.size != b.size) return false + for (entry in a) { + val key = entry.key + var found = false + for (bEntry in b) { + if (deepEquals(key, bEntry.key)) { + if (deepEquals(entry.value, bEntry.value)) { + found = true + break + } else { + return false + } + } + } + if (!found) return false + } + return true + } + if (a is Double && b is Double) { + return doubleEquals(a, b) + } + if (a is Float && b is Float) { + return floatEquals(a, b) } return a == b } + + fun deepHash(value: Any?): Int { + return when (value) { + null -> 0 + is ByteArray -> value.contentHashCode() + is IntArray -> value.contentHashCode() + is LongArray -> value.contentHashCode() + is DoubleArray -> { + var result = 1 + for (item in value) { + result = 31 * result + doubleHash(item) + } + result + } + is FloatArray -> { + var result = 1 + for (item in value) { + result = 31 * result + floatHash(item) + } + result + } + is Array<*> -> { + var result = 1 + for (item in value) { + result = 31 * result + deepHash(item) + } + result + } + is List<*> -> { + var result = 1 + for (item in value) { + result = 31 * result + deepHash(item) + } + result + } + is Map<*, *> -> { + var result = 0 + for (entry in value) { + result += ((deepHash(entry.key) * 31) xor deepHash(entry.value)) + } + result + } + is Double -> doubleHash(value) + is Float -> floatHash(value) + else -> value.hashCode() + } + } } /** @@ -118,16 +236,21 @@ data class UnusedClass(val aField: Any? = null) { } override fun equals(other: Any?): Boolean { - if (other !is UnusedClass) { + if (other == null || other.javaClass != javaClass) { return false } if (this === other) { return true } - return CoreTestsPigeonUtils.deepEquals(toList(), other.toList()) + val other = other as UnusedClass + return CoreTestsPigeonUtils.deepEquals(this.aField, other.aField) } - override fun hashCode(): Int = toList().hashCode() + override fun hashCode(): Int { + var result = javaClass.hashCode() + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aField) + return result + } } /** @@ -261,16 +384,75 @@ data class AllTypes( } override fun equals(other: Any?): Boolean { - if (other !is AllTypes) { + if (other == null || other.javaClass != javaClass) { return false } if (this === other) { return true } - return CoreTestsPigeonUtils.deepEquals(toList(), other.toList()) + val other = other as AllTypes + return CoreTestsPigeonUtils.deepEquals(this.aBool, other.aBool) && + CoreTestsPigeonUtils.deepEquals(this.anInt, other.anInt) && + CoreTestsPigeonUtils.deepEquals(this.anInt64, other.anInt64) && + CoreTestsPigeonUtils.deepEquals(this.aDouble, other.aDouble) && + CoreTestsPigeonUtils.deepEquals(this.aByteArray, other.aByteArray) && + CoreTestsPigeonUtils.deepEquals(this.a4ByteArray, other.a4ByteArray) && + CoreTestsPigeonUtils.deepEquals(this.a8ByteArray, other.a8ByteArray) && + CoreTestsPigeonUtils.deepEquals(this.aFloatArray, other.aFloatArray) && + CoreTestsPigeonUtils.deepEquals(this.anEnum, other.anEnum) && + CoreTestsPigeonUtils.deepEquals(this.anotherEnum, other.anotherEnum) && + CoreTestsPigeonUtils.deepEquals(this.aString, other.aString) && + CoreTestsPigeonUtils.deepEquals(this.anObject, other.anObject) && + CoreTestsPigeonUtils.deepEquals(this.list, other.list) && + CoreTestsPigeonUtils.deepEquals(this.stringList, other.stringList) && + CoreTestsPigeonUtils.deepEquals(this.intList, other.intList) && + CoreTestsPigeonUtils.deepEquals(this.doubleList, other.doubleList) && + CoreTestsPigeonUtils.deepEquals(this.boolList, other.boolList) && + CoreTestsPigeonUtils.deepEquals(this.enumList, other.enumList) && + CoreTestsPigeonUtils.deepEquals(this.objectList, other.objectList) && + CoreTestsPigeonUtils.deepEquals(this.listList, other.listList) && + CoreTestsPigeonUtils.deepEquals(this.mapList, other.mapList) && + CoreTestsPigeonUtils.deepEquals(this.map, other.map) && + CoreTestsPigeonUtils.deepEquals(this.stringMap, other.stringMap) && + CoreTestsPigeonUtils.deepEquals(this.intMap, other.intMap) && + CoreTestsPigeonUtils.deepEquals(this.enumMap, other.enumMap) && + CoreTestsPigeonUtils.deepEquals(this.objectMap, other.objectMap) && + CoreTestsPigeonUtils.deepEquals(this.listMap, other.listMap) && + CoreTestsPigeonUtils.deepEquals(this.mapMap, other.mapMap) } - override fun hashCode(): Int = toList().hashCode() + override fun hashCode(): Int { + var result = javaClass.hashCode() + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aBool) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.anInt) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.anInt64) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aDouble) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aByteArray) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.a4ByteArray) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.a8ByteArray) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aFloatArray) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.anEnum) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.anotherEnum) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aString) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.anObject) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.list) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.stringList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.intList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.doubleList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.boolList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.enumList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.objectList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.listList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.mapList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.map) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.stringMap) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.intMap) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.enumMap) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.objectMap) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.listMap) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.mapMap) + return result + } } /** @@ -416,16 +598,81 @@ data class AllNullableTypes( } override fun equals(other: Any?): Boolean { - if (other !is AllNullableTypes) { + if (other == null || other.javaClass != javaClass) { return false } if (this === other) { return true } - return CoreTestsPigeonUtils.deepEquals(toList(), other.toList()) + val other = other as AllNullableTypes + return CoreTestsPigeonUtils.deepEquals(this.aNullableBool, other.aNullableBool) && + CoreTestsPigeonUtils.deepEquals(this.aNullableInt, other.aNullableInt) && + CoreTestsPigeonUtils.deepEquals(this.aNullableInt64, other.aNullableInt64) && + CoreTestsPigeonUtils.deepEquals(this.aNullableDouble, other.aNullableDouble) && + CoreTestsPigeonUtils.deepEquals(this.aNullableByteArray, other.aNullableByteArray) && + CoreTestsPigeonUtils.deepEquals(this.aNullable4ByteArray, other.aNullable4ByteArray) && + CoreTestsPigeonUtils.deepEquals(this.aNullable8ByteArray, other.aNullable8ByteArray) && + CoreTestsPigeonUtils.deepEquals(this.aNullableFloatArray, other.aNullableFloatArray) && + CoreTestsPigeonUtils.deepEquals(this.aNullableEnum, other.aNullableEnum) && + CoreTestsPigeonUtils.deepEquals(this.anotherNullableEnum, other.anotherNullableEnum) && + CoreTestsPigeonUtils.deepEquals(this.aNullableString, other.aNullableString) && + CoreTestsPigeonUtils.deepEquals(this.aNullableObject, other.aNullableObject) && + CoreTestsPigeonUtils.deepEquals(this.allNullableTypes, other.allNullableTypes) && + CoreTestsPigeonUtils.deepEquals(this.list, other.list) && + CoreTestsPigeonUtils.deepEquals(this.stringList, other.stringList) && + CoreTestsPigeonUtils.deepEquals(this.intList, other.intList) && + CoreTestsPigeonUtils.deepEquals(this.doubleList, other.doubleList) && + CoreTestsPigeonUtils.deepEquals(this.boolList, other.boolList) && + CoreTestsPigeonUtils.deepEquals(this.enumList, other.enumList) && + CoreTestsPigeonUtils.deepEquals(this.objectList, other.objectList) && + CoreTestsPigeonUtils.deepEquals(this.listList, other.listList) && + CoreTestsPigeonUtils.deepEquals(this.mapList, other.mapList) && + CoreTestsPigeonUtils.deepEquals(this.recursiveClassList, other.recursiveClassList) && + CoreTestsPigeonUtils.deepEquals(this.map, other.map) && + CoreTestsPigeonUtils.deepEquals(this.stringMap, other.stringMap) && + CoreTestsPigeonUtils.deepEquals(this.intMap, other.intMap) && + CoreTestsPigeonUtils.deepEquals(this.enumMap, other.enumMap) && + CoreTestsPigeonUtils.deepEquals(this.objectMap, other.objectMap) && + CoreTestsPigeonUtils.deepEquals(this.listMap, other.listMap) && + CoreTestsPigeonUtils.deepEquals(this.mapMap, other.mapMap) && + CoreTestsPigeonUtils.deepEquals(this.recursiveClassMap, other.recursiveClassMap) } - override fun hashCode(): Int = toList().hashCode() + override fun hashCode(): Int { + var result = javaClass.hashCode() + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aNullableBool) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aNullableInt) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aNullableInt64) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aNullableDouble) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aNullableByteArray) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aNullable4ByteArray) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aNullable8ByteArray) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aNullableFloatArray) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aNullableEnum) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.anotherNullableEnum) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aNullableString) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aNullableObject) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.allNullableTypes) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.list) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.stringList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.intList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.doubleList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.boolList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.enumList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.objectList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.listList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.mapList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.recursiveClassList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.map) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.stringMap) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.intMap) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.enumMap) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.objectMap) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.listMap) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.mapMap) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.recursiveClassMap) + return result + } } /** @@ -560,16 +807,75 @@ data class AllNullableTypesWithoutRecursion( } override fun equals(other: Any?): Boolean { - if (other !is AllNullableTypesWithoutRecursion) { + if (other == null || other.javaClass != javaClass) { return false } if (this === other) { return true } - return CoreTestsPigeonUtils.deepEquals(toList(), other.toList()) + val other = other as AllNullableTypesWithoutRecursion + return CoreTestsPigeonUtils.deepEquals(this.aNullableBool, other.aNullableBool) && + CoreTestsPigeonUtils.deepEquals(this.aNullableInt, other.aNullableInt) && + CoreTestsPigeonUtils.deepEquals(this.aNullableInt64, other.aNullableInt64) && + CoreTestsPigeonUtils.deepEquals(this.aNullableDouble, other.aNullableDouble) && + CoreTestsPigeonUtils.deepEquals(this.aNullableByteArray, other.aNullableByteArray) && + CoreTestsPigeonUtils.deepEquals(this.aNullable4ByteArray, other.aNullable4ByteArray) && + CoreTestsPigeonUtils.deepEquals(this.aNullable8ByteArray, other.aNullable8ByteArray) && + CoreTestsPigeonUtils.deepEquals(this.aNullableFloatArray, other.aNullableFloatArray) && + CoreTestsPigeonUtils.deepEquals(this.aNullableEnum, other.aNullableEnum) && + CoreTestsPigeonUtils.deepEquals(this.anotherNullableEnum, other.anotherNullableEnum) && + CoreTestsPigeonUtils.deepEquals(this.aNullableString, other.aNullableString) && + CoreTestsPigeonUtils.deepEquals(this.aNullableObject, other.aNullableObject) && + CoreTestsPigeonUtils.deepEquals(this.list, other.list) && + CoreTestsPigeonUtils.deepEquals(this.stringList, other.stringList) && + CoreTestsPigeonUtils.deepEquals(this.intList, other.intList) && + CoreTestsPigeonUtils.deepEquals(this.doubleList, other.doubleList) && + CoreTestsPigeonUtils.deepEquals(this.boolList, other.boolList) && + CoreTestsPigeonUtils.deepEquals(this.enumList, other.enumList) && + CoreTestsPigeonUtils.deepEquals(this.objectList, other.objectList) && + CoreTestsPigeonUtils.deepEquals(this.listList, other.listList) && + CoreTestsPigeonUtils.deepEquals(this.mapList, other.mapList) && + CoreTestsPigeonUtils.deepEquals(this.map, other.map) && + CoreTestsPigeonUtils.deepEquals(this.stringMap, other.stringMap) && + CoreTestsPigeonUtils.deepEquals(this.intMap, other.intMap) && + CoreTestsPigeonUtils.deepEquals(this.enumMap, other.enumMap) && + CoreTestsPigeonUtils.deepEquals(this.objectMap, other.objectMap) && + CoreTestsPigeonUtils.deepEquals(this.listMap, other.listMap) && + CoreTestsPigeonUtils.deepEquals(this.mapMap, other.mapMap) } - override fun hashCode(): Int = toList().hashCode() + override fun hashCode(): Int { + var result = javaClass.hashCode() + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aNullableBool) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aNullableInt) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aNullableInt64) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aNullableDouble) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aNullableByteArray) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aNullable4ByteArray) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aNullable8ByteArray) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aNullableFloatArray) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aNullableEnum) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.anotherNullableEnum) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aNullableString) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.aNullableObject) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.list) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.stringList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.intList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.doubleList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.boolList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.enumList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.objectList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.listList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.mapList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.map) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.stringMap) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.intMap) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.enumMap) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.objectMap) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.listMap) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.mapMap) + return result + } } /** @@ -623,16 +929,34 @@ data class AllClassesWrapper( } override fun equals(other: Any?): Boolean { - if (other !is AllClassesWrapper) { + if (other == null || other.javaClass != javaClass) { return false } if (this === other) { return true } - return CoreTestsPigeonUtils.deepEquals(toList(), other.toList()) + val other = other as AllClassesWrapper + return CoreTestsPigeonUtils.deepEquals(this.allNullableTypes, other.allNullableTypes) && + CoreTestsPigeonUtils.deepEquals( + this.allNullableTypesWithoutRecursion, other.allNullableTypesWithoutRecursion) && + CoreTestsPigeonUtils.deepEquals(this.allTypes, other.allTypes) && + CoreTestsPigeonUtils.deepEquals(this.classList, other.classList) && + CoreTestsPigeonUtils.deepEquals(this.nullableClassList, other.nullableClassList) && + CoreTestsPigeonUtils.deepEquals(this.classMap, other.classMap) && + CoreTestsPigeonUtils.deepEquals(this.nullableClassMap, other.nullableClassMap) } - override fun hashCode(): Int = toList().hashCode() + override fun hashCode(): Int { + var result = javaClass.hashCode() + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.allNullableTypes) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.allNullableTypesWithoutRecursion) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.allTypes) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.classList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.nullableClassList) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.classMap) + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.nullableClassMap) + return result + } } /** @@ -655,16 +979,21 @@ data class TestMessage(val testList: List? = null) { } override fun equals(other: Any?): Boolean { - if (other !is TestMessage) { + if (other == null || other.javaClass != javaClass) { return false } if (this === other) { return true } - return CoreTestsPigeonUtils.deepEquals(toList(), other.toList()) + val other = other as TestMessage + return CoreTestsPigeonUtils.deepEquals(this.testList, other.testList) } - override fun hashCode(): Int = toList().hashCode() + override fun hashCode(): Int { + var result = javaClass.hashCode() + result = 31 * result + CoreTestsPigeonUtils.deepHash(this.testList) + return result + } } private open class CoreTestsPigeonCodec : StandardMessageCodec() { @@ -808,6 +1137,12 @@ interface HostIntegrationCoreApi { fun echoOptionalDefaultDouble(aDouble: Double): Double /** Returns passed in int. */ fun echoRequiredInt(anInt: Long): Long + /** Returns the result of platform-side equality check. */ + fun areAllNullableTypesEqual(a: AllNullableTypes, b: AllNullableTypes): Boolean + /** Returns the platform-side hash code for the given object. */ + fun getAllNullableTypesHash(value: AllNullableTypes): Long + /** Returns the platform-side hash code for the given object. */ + fun getAllNullableTypesWithoutRecursionHash(value: AllNullableTypesWithoutRecursion): Long /** Returns the passed object, to test serialization and deserialization. */ fun echoAllNullableTypes(everything: AllNullableTypes?): AllNullableTypes? /** Returns the passed object, to test serialization and deserialization. */ @@ -1900,6 +2235,73 @@ interface HostIntegrationCoreApi { channel.setMessageHandler(null) } } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.areAllNullableTypesEqual$separatedMessageChannelSuffix", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val aArg = args[0] as AllNullableTypes + val bArg = args[1] as AllNullableTypes + val wrapped: List = + try { + listOf(api.areAllNullableTypesEqual(aArg, bArg)) + } catch (exception: Throwable) { + CoreTestsPigeonUtils.wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.getAllNullableTypesHash$separatedMessageChannelSuffix", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val valueArg = args[0] as AllNullableTypes + val wrapped: List = + try { + listOf(api.getAllNullableTypesHash(valueArg)) + } catch (exception: Throwable) { + CoreTestsPigeonUtils.wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.getAllNullableTypesWithoutRecursionHash$separatedMessageChannelSuffix", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val valueArg = args[0] as AllNullableTypesWithoutRecursion + val wrapped: List = + try { + listOf(api.getAllNullableTypesWithoutRecursionHash(valueArg)) + } catch (exception: Throwable) { + CoreTestsPigeonUtils.wrapError(exception) + } + reply.reply(wrapped) + } + } else { + channel.setMessageHandler(null) + } + } run { val channel = BasicMessageChannel( diff --git a/packages/pigeon/platform_tests/test_plugin/android/src/main/kotlin/com/example/test_plugin/EventChannelTests.gen.kt b/packages/pigeon/platform_tests/test_plugin/android/src/main/kotlin/com/example/test_plugin/EventChannelTests.gen.kt index 7e835701a237..b98e54fef79c 100644 --- a/packages/pigeon/platform_tests/test_plugin/android/src/main/kotlin/com/example/test_plugin/EventChannelTests.gen.kt +++ b/packages/pigeon/platform_tests/test_plugin/android/src/main/kotlin/com/example/test_plugin/EventChannelTests.gen.kt @@ -16,7 +16,36 @@ import java.io.ByteArrayOutputStream import java.nio.ByteBuffer private object EventChannelTestsPigeonUtils { + fun doubleEquals(a: Double, b: Double): Boolean { + // Normalize -0.0 to 0.0 and handle NaN equality. + return (if (a == 0.0) 0.0 else a) == (if (b == 0.0) 0.0 else b) || (a.isNaN() && b.isNaN()) + } + + fun floatEquals(a: Float, b: Float): Boolean { + // Normalize -0.0 to 0.0 and handle NaN equality. + return (if (a == 0.0f) 0.0f else a) == (if (b == 0.0f) 0.0f else b) || (a.isNaN() && b.isNaN()) + } + + fun doubleHash(d: Double): Int { + // Normalize -0.0 to 0.0 and handle NaN to ensure consistent hash codes. + val normalized = if (d == 0.0) 0.0 else d + val bits = java.lang.Double.doubleToLongBits(normalized) + return (bits xor (bits ushr 32)).toInt() + } + + fun floatHash(f: Float): Int { + // Normalize -0.0 to 0.0 and handle NaN to ensure consistent hash codes. + val normalized = if (f == 0.0f) 0.0f else f + return java.lang.Float.floatToIntBits(normalized) + } + fun deepEquals(a: Any?, b: Any?): Boolean { + if (a === b) { + return true + } + if (a == null || b == null) { + return false + } if (a is ByteArray && b is ByteArray) { return a.contentEquals(b) } @@ -27,20 +56,109 @@ private object EventChannelTestsPigeonUtils { return a.contentEquals(b) } if (a is DoubleArray && b is DoubleArray) { - return a.contentEquals(b) + if (a.size != b.size) return false + for (i in a.indices) { + if (!doubleEquals(a[i], b[i])) return false + } + return true + } + if (a is FloatArray && b is FloatArray) { + if (a.size != b.size) return false + for (i in a.indices) { + if (!floatEquals(a[i], b[i])) return false + } + return true } if (a is Array<*> && b is Array<*>) { - return a.size == b.size && a.indices.all { deepEquals(a[it], b[it]) } + if (a.size != b.size) return false + for (i in a.indices) { + if (!deepEquals(a[i], b[i])) return false + } + return true } if (a is List<*> && b is List<*>) { - return a.size == b.size && a.indices.all { deepEquals(a[it], b[it]) } + if (a.size != b.size) return false + val iterA = a.iterator() + val iterB = b.iterator() + while (iterA.hasNext() && iterB.hasNext()) { + if (!deepEquals(iterA.next(), iterB.next())) return false + } + return true } if (a is Map<*, *> && b is Map<*, *>) { - return a.size == b.size && - a.all { (b as Map).contains(it.key) && deepEquals(it.value, b[it.key]) } + if (a.size != b.size) return false + for (entry in a) { + val key = entry.key + var found = false + for (bEntry in b) { + if (deepEquals(key, bEntry.key)) { + if (deepEquals(entry.value, bEntry.value)) { + found = true + break + } else { + return false + } + } + } + if (!found) return false + } + return true + } + if (a is Double && b is Double) { + return doubleEquals(a, b) + } + if (a is Float && b is Float) { + return floatEquals(a, b) } return a == b } + + fun deepHash(value: Any?): Int { + return when (value) { + null -> 0 + is ByteArray -> value.contentHashCode() + is IntArray -> value.contentHashCode() + is LongArray -> value.contentHashCode() + is DoubleArray -> { + var result = 1 + for (item in value) { + result = 31 * result + doubleHash(item) + } + result + } + is FloatArray -> { + var result = 1 + for (item in value) { + result = 31 * result + floatHash(item) + } + result + } + is Array<*> -> { + var result = 1 + for (item in value) { + result = 31 * result + deepHash(item) + } + result + } + is List<*> -> { + var result = 1 + for (item in value) { + result = 31 * result + deepHash(item) + } + result + } + is Map<*, *> -> { + var result = 0 + for (entry in value) { + result += ((deepHash(entry.key) * 31) xor deepHash(entry.value)) + } + result + } + is Double -> doubleHash(value) + is Float -> floatHash(value) + else -> value.hashCode() + } + } } /** @@ -223,16 +341,87 @@ data class EventAllNullableTypes( } override fun equals(other: Any?): Boolean { - if (other !is EventAllNullableTypes) { + if (other == null || other.javaClass != javaClass) { return false } if (this === other) { return true } - return EventChannelTestsPigeonUtils.deepEquals(toList(), other.toList()) + val other = other as EventAllNullableTypes + return EventChannelTestsPigeonUtils.deepEquals(this.aNullableBool, other.aNullableBool) && + EventChannelTestsPigeonUtils.deepEquals(this.aNullableInt, other.aNullableInt) && + EventChannelTestsPigeonUtils.deepEquals(this.aNullableInt64, other.aNullableInt64) && + EventChannelTestsPigeonUtils.deepEquals(this.aNullableDouble, other.aNullableDouble) && + EventChannelTestsPigeonUtils.deepEquals( + this.aNullableByteArray, other.aNullableByteArray) && + EventChannelTestsPigeonUtils.deepEquals( + this.aNullable4ByteArray, other.aNullable4ByteArray) && + EventChannelTestsPigeonUtils.deepEquals( + this.aNullable8ByteArray, other.aNullable8ByteArray) && + EventChannelTestsPigeonUtils.deepEquals( + this.aNullableFloatArray, other.aNullableFloatArray) && + EventChannelTestsPigeonUtils.deepEquals(this.aNullableEnum, other.aNullableEnum) && + EventChannelTestsPigeonUtils.deepEquals( + this.anotherNullableEnum, other.anotherNullableEnum) && + EventChannelTestsPigeonUtils.deepEquals(this.aNullableString, other.aNullableString) && + EventChannelTestsPigeonUtils.deepEquals(this.aNullableObject, other.aNullableObject) && + EventChannelTestsPigeonUtils.deepEquals(this.allNullableTypes, other.allNullableTypes) && + EventChannelTestsPigeonUtils.deepEquals(this.list, other.list) && + EventChannelTestsPigeonUtils.deepEquals(this.stringList, other.stringList) && + EventChannelTestsPigeonUtils.deepEquals(this.intList, other.intList) && + EventChannelTestsPigeonUtils.deepEquals(this.doubleList, other.doubleList) && + EventChannelTestsPigeonUtils.deepEquals(this.boolList, other.boolList) && + EventChannelTestsPigeonUtils.deepEquals(this.enumList, other.enumList) && + EventChannelTestsPigeonUtils.deepEquals(this.objectList, other.objectList) && + EventChannelTestsPigeonUtils.deepEquals(this.listList, other.listList) && + EventChannelTestsPigeonUtils.deepEquals(this.mapList, other.mapList) && + EventChannelTestsPigeonUtils.deepEquals( + this.recursiveClassList, other.recursiveClassList) && + EventChannelTestsPigeonUtils.deepEquals(this.map, other.map) && + EventChannelTestsPigeonUtils.deepEquals(this.stringMap, other.stringMap) && + EventChannelTestsPigeonUtils.deepEquals(this.intMap, other.intMap) && + EventChannelTestsPigeonUtils.deepEquals(this.enumMap, other.enumMap) && + EventChannelTestsPigeonUtils.deepEquals(this.objectMap, other.objectMap) && + EventChannelTestsPigeonUtils.deepEquals(this.listMap, other.listMap) && + EventChannelTestsPigeonUtils.deepEquals(this.mapMap, other.mapMap) && + EventChannelTestsPigeonUtils.deepEquals(this.recursiveClassMap, other.recursiveClassMap) + } + + override fun hashCode(): Int { + var result = javaClass.hashCode() + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.aNullableBool) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.aNullableInt) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.aNullableInt64) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.aNullableDouble) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.aNullableByteArray) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.aNullable4ByteArray) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.aNullable8ByteArray) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.aNullableFloatArray) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.aNullableEnum) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.anotherNullableEnum) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.aNullableString) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.aNullableObject) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.allNullableTypes) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.list) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.stringList) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.intList) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.doubleList) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.boolList) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.enumList) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.objectList) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.listList) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.mapList) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.recursiveClassList) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.map) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.stringMap) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.intMap) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.enumMap) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.objectMap) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.listMap) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.mapMap) + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.recursiveClassMap) + return result } - - override fun hashCode(): Int = toList().hashCode() } /** @@ -256,16 +445,21 @@ data class IntEvent(val value: Long) : PlatformEvent() { } override fun equals(other: Any?): Boolean { - if (other !is IntEvent) { + if (other == null || other.javaClass != javaClass) { return false } if (this === other) { return true } - return EventChannelTestsPigeonUtils.deepEquals(toList(), other.toList()) + val other = other as IntEvent + return EventChannelTestsPigeonUtils.deepEquals(this.value, other.value) } - override fun hashCode(): Int = toList().hashCode() + override fun hashCode(): Int { + var result = javaClass.hashCode() + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.value) + return result + } } /** Generated class from Pigeon that represents data sent in messages. */ @@ -284,16 +478,21 @@ data class StringEvent(val value: String) : PlatformEvent() { } override fun equals(other: Any?): Boolean { - if (other !is StringEvent) { + if (other == null || other.javaClass != javaClass) { return false } if (this === other) { return true } - return EventChannelTestsPigeonUtils.deepEquals(toList(), other.toList()) + val other = other as StringEvent + return EventChannelTestsPigeonUtils.deepEquals(this.value, other.value) } - override fun hashCode(): Int = toList().hashCode() + override fun hashCode(): Int { + var result = javaClass.hashCode() + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.value) + return result + } } /** Generated class from Pigeon that represents data sent in messages. */ @@ -312,16 +511,21 @@ data class BoolEvent(val value: Boolean) : PlatformEvent() { } override fun equals(other: Any?): Boolean { - if (other !is BoolEvent) { + if (other == null || other.javaClass != javaClass) { return false } if (this === other) { return true } - return EventChannelTestsPigeonUtils.deepEquals(toList(), other.toList()) + val other = other as BoolEvent + return EventChannelTestsPigeonUtils.deepEquals(this.value, other.value) } - override fun hashCode(): Int = toList().hashCode() + override fun hashCode(): Int { + var result = javaClass.hashCode() + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.value) + return result + } } /** Generated class from Pigeon that represents data sent in messages. */ @@ -340,16 +544,21 @@ data class DoubleEvent(val value: Double) : PlatformEvent() { } override fun equals(other: Any?): Boolean { - if (other !is DoubleEvent) { + if (other == null || other.javaClass != javaClass) { return false } if (this === other) { return true } - return EventChannelTestsPigeonUtils.deepEquals(toList(), other.toList()) + val other = other as DoubleEvent + return EventChannelTestsPigeonUtils.deepEquals(this.value, other.value) } - override fun hashCode(): Int = toList().hashCode() + override fun hashCode(): Int { + var result = javaClass.hashCode() + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.value) + return result + } } /** Generated class from Pigeon that represents data sent in messages. */ @@ -368,16 +577,21 @@ data class ObjectsEvent(val value: Any) : PlatformEvent() { } override fun equals(other: Any?): Boolean { - if (other !is ObjectsEvent) { + if (other == null || other.javaClass != javaClass) { return false } if (this === other) { return true } - return EventChannelTestsPigeonUtils.deepEquals(toList(), other.toList()) + val other = other as ObjectsEvent + return EventChannelTestsPigeonUtils.deepEquals(this.value, other.value) } - override fun hashCode(): Int = toList().hashCode() + override fun hashCode(): Int { + var result = javaClass.hashCode() + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.value) + return result + } } /** Generated class from Pigeon that represents data sent in messages. */ @@ -396,16 +610,21 @@ data class EnumEvent(val value: EventEnum) : PlatformEvent() { } override fun equals(other: Any?): Boolean { - if (other !is EnumEvent) { + if (other == null || other.javaClass != javaClass) { return false } if (this === other) { return true } - return EventChannelTestsPigeonUtils.deepEquals(toList(), other.toList()) + val other = other as EnumEvent + return EventChannelTestsPigeonUtils.deepEquals(this.value, other.value) } - override fun hashCode(): Int = toList().hashCode() + override fun hashCode(): Int { + var result = javaClass.hashCode() + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.value) + return result + } } /** Generated class from Pigeon that represents data sent in messages. */ @@ -424,16 +643,21 @@ data class ClassEvent(val value: EventAllNullableTypes) : PlatformEvent() { } override fun equals(other: Any?): Boolean { - if (other !is ClassEvent) { + if (other == null || other.javaClass != javaClass) { return false } if (this === other) { return true } - return EventChannelTestsPigeonUtils.deepEquals(toList(), other.toList()) + val other = other as ClassEvent + return EventChannelTestsPigeonUtils.deepEquals(this.value, other.value) } - override fun hashCode(): Int = toList().hashCode() + override fun hashCode(): Int { + var result = javaClass.hashCode() + result = 31 * result + EventChannelTestsPigeonUtils.deepHash(this.value) + return result + } } private open class EventChannelTestsPigeonCodec : StandardMessageCodec() { @@ -575,6 +799,10 @@ abstract class StreamIntsStreamHandler : EventChannelTestsPigeonEventChannelWrap .setStreamHandler(internalStreamHandler) } } + // Implement methods from EventChannelTestsPigeonEventChannelWrapper + override fun onListen(p0: Any?, sink: PigeonEventSink) {} + + override fun onCancel(p0: Any?) {} } abstract class StreamEventsStreamHandler : @@ -595,6 +823,10 @@ abstract class StreamEventsStreamHandler : .setStreamHandler(internalStreamHandler) } } + // Implement methods from EventChannelTestsPigeonEventChannelWrapper + override fun onListen(p0: Any?, sink: PigeonEventSink) {} + + override fun onCancel(p0: Any?) {} } abstract class StreamConsistentNumbersStreamHandler : @@ -615,4 +847,8 @@ abstract class StreamConsistentNumbersStreamHandler : .setStreamHandler(internalStreamHandler) } } + // Implement methods from EventChannelTestsPigeonEventChannelWrapper + override fun onListen(p0: Any?, sink: PigeonEventSink) {} + + override fun onCancel(p0: Any?) {} } diff --git a/packages/pigeon/platform_tests/test_plugin/android/src/main/kotlin/com/example/test_plugin/ProxyApiTestApiImpls.kt b/packages/pigeon/platform_tests/test_plugin/android/src/main/kotlin/com/example/test_plugin/ProxyApiTestApiImpls.kt index ddf5b81888c5..d58c351d0e7a 100644 --- a/packages/pigeon/platform_tests/test_plugin/android/src/main/kotlin/com/example/test_plugin/ProxyApiTestApiImpls.kt +++ b/packages/pigeon/platform_tests/test_plugin/android/src/main/kotlin/com/example/test_plugin/ProxyApiTestApiImpls.kt @@ -15,7 +15,7 @@ interface ProxyApiInterface @RequiresApi(25) class ClassWithApiRequirement -class ProxyApiRegistrar(binaryMessenger: BinaryMessenger) : +open class ProxyApiRegistrar(binaryMessenger: BinaryMessenger) : ProxyApiTestsPigeonProxyApiRegistrar(binaryMessenger) { override fun getPigeonApiProxyApiTestClass(): PigeonApiProxyApiTestClass { return ProxyApiTestClassApi(this) diff --git a/packages/pigeon/platform_tests/test_plugin/android/src/main/kotlin/com/example/test_plugin/ProxyApiTests.gen.kt b/packages/pigeon/platform_tests/test_plugin/android/src/main/kotlin/com/example/test_plugin/ProxyApiTests.gen.kt index 97eb95d69d87..ab979311a10c 100644 --- a/packages/pigeon/platform_tests/test_plugin/android/src/main/kotlin/com/example/test_plugin/ProxyApiTests.gen.kt +++ b/packages/pigeon/platform_tests/test_plugin/android/src/main/kotlin/com/example/test_plugin/ProxyApiTests.gen.kt @@ -3133,6 +3133,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterNoop` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3160,6 +3168,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterThrowError` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3192,6 +3208,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterThrowErrorFromVoid` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3224,6 +3248,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterEchoBool` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3264,6 +3296,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterEchoInt` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3303,6 +3343,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterEchoDouble` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3343,6 +3391,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterEchoString` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3383,6 +3439,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterEchoUint8List` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3423,6 +3487,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterEchoList` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3463,6 +3535,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterEchoProxyApiList` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3503,6 +3583,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterEchoMap` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3542,6 +3630,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterEchoProxyApiMap` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3582,6 +3678,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterEchoEnum` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3622,6 +3726,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterEchoProxyApi` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3662,6 +3774,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterEchoNullableBool` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3695,6 +3815,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterEchoNullableInt` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3728,6 +3856,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterEchoNullableDouble` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3761,6 +3897,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterEchoNullableString` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3794,6 +3938,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterEchoNullableUint8List` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3827,6 +3979,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterEchoNullableList` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3860,6 +4020,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterEchoNullableMap` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3893,6 +4061,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterEchoNullableEnum` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3926,6 +4102,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterEchoNullableProxyApi` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3958,6 +4142,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterNoopAsync` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -3990,6 +4182,14 @@ abstract class PigeonApiProxyApiTestClass( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiTestClass.flutterEchoAsyncString` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec @@ -4174,6 +4374,14 @@ open class PigeonApiProxyApiInterface( Result.failure( ProxyApiTestsError("ignore-calls-error", "Calls to Dart are being ignored.", ""))) return + } else if (!pigeonRegistrar.instanceManager.containsInstance(pigeon_instanceArg)) { + callback( + Result.failure( + ProxyApiTestsError( + "missing-instance-error", + "Callback to `ProxyApiInterface.anInterfaceMethod` failed because native instance was not in the instance manager.", + ""))) + return } val binaryMessenger = pigeonRegistrar.binaryMessenger val codec = pigeonRegistrar.codec diff --git a/packages/pigeon/platform_tests/test_plugin/android/src/main/kotlin/com/example/test_plugin/TestPlugin.kt b/packages/pigeon/platform_tests/test_plugin/android/src/main/kotlin/com/example/test_plugin/TestPlugin.kt index e032596170cc..ea402e91d7a4 100644 --- a/packages/pigeon/platform_tests/test_plugin/android/src/main/kotlin/com/example/test_plugin/TestPlugin.kt +++ b/packages/pigeon/platform_tests/test_plugin/android/src/main/kotlin/com/example/test_plugin/TestPlugin.kt @@ -53,6 +53,20 @@ class TestPlugin : FlutterPlugin, HostIntegrationCoreApi { return everything } + override fun areAllNullableTypesEqual(a: AllNullableTypes, b: AllNullableTypes): Boolean { + return a == b + } + + override fun getAllNullableTypesHash(value: AllNullableTypes): Long { + return value.hashCode().toLong() + } + + override fun getAllNullableTypesWithoutRecursionHash( + value: AllNullableTypesWithoutRecursion + ): Long { + return value.hashCode().toLong() + } + override fun echoAllNullableTypesWithoutRecursion( everything: AllNullableTypesWithoutRecursion? ): AllNullableTypesWithoutRecursion? { diff --git a/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/AllDatatypesTest.kt b/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/AllDatatypesTest.kt index e2f80062c6e2..28a27c985604 100644 --- a/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/AllDatatypesTest.kt +++ b/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/AllDatatypesTest.kt @@ -227,4 +227,69 @@ internal class AllDatatypesTest { val withDifferentMapInList = AllNullableTypes(list = matchingMapInList) assertEquals(withMapInList, withDifferentMapInList) } + + @Test + fun `equality method correctly identifies NaN matches`() { + val withNaN = AllNullableTypes(aNullableDouble = Double.NaN) + val withAnotherNaN = AllNullableTypes(aNullableDouble = Double.NaN) + assertEquals(withNaN, withAnotherNaN) + assertEquals(withNaN.hashCode(), withAnotherNaN.hashCode()) + } + + @Test + fun `cross-type equality returns false`() { + val a = AllNullableTypes(aNullableInt = 1) + val b = AllNullableTypesWithoutRecursion(aNullableInt = 1) + assertNotEquals(a, b) + assertNotEquals(b, a) + } + + @Test + fun `byteArray equality`() { + val a = AllNullableTypes(aNullableByteArray = byteArrayOf(1, 2, 3)) + val b = AllNullableTypes(aNullableByteArray = byteArrayOf(1, 2, 3)) + assertEquals(a, b) + assertEquals(a.hashCode(), b.hashCode()) + } + + @Test + fun `zero equality`() { + val a = AllNullableTypes(aNullableDouble = 0.0) + val b = AllNullableTypes(aNullableDouble = -0.0) + // In many platforms, 0.0 and -0.0 are treated as equal. + assertEquals(a, b) + assertEquals(a.hashCode(), b.hashCode()) + } + + @Test + fun `zero map key equality`() { + val a = AllNullableTypes(map = mapOf(0.0 to "a")) + val b = AllNullableTypes(map = mapOf(-0.0 to "a")) + assertEquals(a, b) + assertEquals(a.hashCode(), b.hashCode()) + } + + @Test + fun `nested NaN equality`() { + val a = AllNullableTypes(doubleList = listOf(Double.NaN)) + val b = AllNullableTypes(doubleList = listOf(Double.NaN)) + assertEquals(a, b) + assertEquals(a.hashCode(), b.hashCode()) + } + + @Test + fun `nested zero list equality`() { + val a = AllNullableTypes(doubleList = listOf(0.0)) + val b = AllNullableTypes(doubleList = listOf(-0.0)) + assertEquals(a, b) + assertEquals(a.hashCode(), b.hashCode()) + } + + @Test + fun `nested zero array equality`() { + val a = AllNullableTypes(aNullableFloatArray = doubleArrayOf(0.0)) + val b = AllNullableTypes(aNullableFloatArray = doubleArrayOf(-0.0)) + assertEquals(a, b) + assertEquals(a.hashCode(), b.hashCode()) + } } diff --git a/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/NonNullFieldsTests.kt b/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/NonNullFieldsTests.kt index e5e97394f18f..fad1532b0599 100644 --- a/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/NonNullFieldsTests.kt +++ b/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/NonNullFieldsTests.kt @@ -14,4 +14,15 @@ class NonNullFieldsTests { val request = NonNullFieldSearchRequest("hello") assertEquals("hello", request.query) } + + @Test + fun testEquality() { + val request1 = NonNullFieldSearchRequest("hello") + val request2 = NonNullFieldSearchRequest("hello") + val request3 = NonNullFieldSearchRequest("world") + + assertEquals(request1, request2) + assert(request1 != request3) + assertEquals(request1.hashCode(), request2.hashCode()) + } } diff --git a/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/ProxyApiTest.kt b/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/ProxyApiTest.kt new file mode 100644 index 000000000000..1a370133fa07 --- /dev/null +++ b/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/ProxyApiTest.kt @@ -0,0 +1,30 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package com.example.test_plugin + +import io.flutter.plugin.common.StandardMessageCodec +import junit.framework.TestCase.assertEquals +import org.junit.Test + +class ProxyApiTest { + @Test + fun callsToDartFailIfTheInstanceIsNotInTheInstanceManager() { + val testObject = ProxyApiTestClass() + + val api = ProxyApiTestClassApi(TestProxyApiRegistrar()) + api.pigeonRegistrar.instanceManager.addHostCreatedInstance(testObject) + api.pigeonRegistrar.instanceManager.clear() + + var b: Throwable? = null + api.flutterNoop(testObject) { b = it.exceptionOrNull() } + + assertEquals( + b?.message, + "Callback to `ProxyApiTestClass.flutterNoop` failed because native instance was not in the instance manager.") + } +} + +/** Test implementation of `ProxyApiRegistrar` that provides a test binary messenger. */ +class TestProxyApiRegistrar : ProxyApiRegistrar(EchoBinaryMessenger(StandardMessageCodec())) diff --git a/packages/pigeon/platform_tests/test_plugin/darwin/test_plugin/Sources/test_plugin/CoreTests.gen.swift b/packages/pigeon/platform_tests/test_plugin/darwin/test_plugin/Sources/test_plugin/CoreTests.gen.swift index ddea768974b8..606d58783837 100644 --- a/packages/pigeon/platform_tests/test_plugin/darwin/test_plugin/Sources/test_plugin/CoreTests.gen.swift +++ b/packages/pigeon/platform_tests/test_plugin/darwin/test_plugin/Sources/test_plugin/CoreTests.gen.swift @@ -54,7 +54,7 @@ private func wrapError(_ error: Any) -> [Any?] { } return [ "\(error)", - "\(type(of: error))", + "\(Swift.type(of: error))", "Stacktrace: \(Thread.callStackSymbols)", ] } @@ -74,6 +74,19 @@ private func nilOrValue(_ value: Any?) -> T? { return value as! T? } +private func doubleEqualsCoreTests(_ lhs: Double, _ rhs: Double) -> Bool { + return (lhs.isNaN && rhs.isNaN) || lhs == rhs +} + +private func doubleHashCoreTests(_ value: Double, _ hasher: inout Hasher) { + if value.isNaN { + hasher.combine(0x7FF8_0000_0000_0000) + } else { + // Normalize -0.0 to 0.0 + hasher.combine(value == 0 ? 0 : value) + } +} + func deepEqualsCoreTests(_ lhs: Any?, _ rhs: Any?) -> Bool { let cleanLhs = nilOrValue(lhs) as Any? let cleanRhs = nilOrValue(rhs) as Any? @@ -84,56 +97,90 @@ func deepEqualsCoreTests(_ lhs: Any?, _ rhs: Any?) -> Bool { case (nil, _), (_, nil): return false - case is (Void, Void): + case (let lhs as AnyObject, let rhs as AnyObject) where lhs === rhs: return true - case let (cleanLhsHashable, cleanRhsHashable) as (AnyHashable, AnyHashable): - return cleanLhsHashable == cleanRhsHashable + case is (Void, Void): + return true - case let (cleanLhsArray, cleanRhsArray) as ([Any?], [Any?]): - guard cleanLhsArray.count == cleanRhsArray.count else { return false } - for (index, element) in cleanLhsArray.enumerated() { - if !deepEqualsCoreTests(element, cleanRhsArray[index]) { + case (let lhsArray, let rhsArray) as ([Any?], [Any?]): + guard lhsArray.count == rhsArray.count else { return false } + for (index, element) in lhsArray.enumerated() { + if !deepEqualsCoreTests(element, rhsArray[index]) { return false } } return true - case let (cleanLhsDictionary, cleanRhsDictionary) as ([AnyHashable: Any?], [AnyHashable: Any?]): - guard cleanLhsDictionary.count == cleanRhsDictionary.count else { return false } - for (key, cleanLhsValue) in cleanLhsDictionary { - guard cleanRhsDictionary.index(forKey: key) != nil else { return false } - if !deepEqualsCoreTests(cleanLhsValue, cleanRhsDictionary[key]!) { + case (let lhsArray, let rhsArray) as ([Double], [Double]): + guard lhsArray.count == rhsArray.count else { return false } + for (index, element) in lhsArray.enumerated() { + if !doubleEqualsCoreTests(element, rhsArray[index]) { return false } } return true + case (let lhsDictionary, let rhsDictionary) as ([AnyHashable: Any?], [AnyHashable: Any?]): + guard lhsDictionary.count == rhsDictionary.count else { return false } + for (lhsKey, lhsValue) in lhsDictionary { + var found = false + for (rhsKey, rhsValue) in rhsDictionary { + if deepEqualsCoreTests(lhsKey, rhsKey) { + if deepEqualsCoreTests(lhsValue, rhsValue) { + found = true + break + } else { + return false + } + } + } + if !found { return false } + } + return true + + case (let lhs as Double, let rhs as Double): + return doubleEqualsCoreTests(lhs, rhs) + + case (let lhsHashable, let rhsHashable) as (AnyHashable, AnyHashable): + return lhsHashable == rhsHashable + default: - // Any other type shouldn't be able to be used with pigeon. File an issue if you find this to be untrue. return false } } func deepHashCoreTests(value: Any?, hasher: inout Hasher) { - if let valueList = value as? [AnyHashable] { - for item in valueList { deepHashCoreTests(value: item, hasher: &hasher) } - return + let cleanValue = nilOrValue(value) as Any? + if let cleanValue = cleanValue { + if let doubleValue = cleanValue as? Double { + doubleHashCoreTests(doubleValue, &hasher) + } else if let valueList = cleanValue as? [Any?] { + for item in valueList { + deepHashCoreTests(value: item, hasher: &hasher) + } + } else if let valueList = cleanValue as? [Double] { + for item in valueList { + doubleHashCoreTests(item, &hasher) + } + } else if let valueDict = cleanValue as? [AnyHashable: Any?] { + var result = 0 + for (key, value) in valueDict { + var entryKeyHasher = Hasher() + deepHashCoreTests(value: key, hasher: &entryKeyHasher) + var entryValueHasher = Hasher() + deepHashCoreTests(value: value, hasher: &entryValueHasher) + result = result &+ ((entryKeyHasher.finalize() &* 31) ^ entryValueHasher.finalize()) + } + hasher.combine(result) + } else if let hashableValue = cleanValue as? AnyHashable { + hasher.combine(hashableValue) + } else { + hasher.combine(String(describing: cleanValue)) + } + } else { + hasher.combine(0) } - - if let valueDict = value as? [AnyHashable: AnyHashable] { - for key in valueDict.keys { - hasher.combine(key) - deepHashCoreTests(value: valueDict[key]!, hasher: &hasher) - } - return - } - - if let hashableValue = value as? AnyHashable { - hasher.combine(hashableValue.hashValue) - } - - return hasher.combine(String(describing: value)) } enum AnEnum: Int { @@ -166,10 +213,15 @@ struct UnusedClass: Hashable { ] } static func == (lhs: UnusedClass, rhs: UnusedClass) -> Bool { - return deepEqualsCoreTests(lhs.toList(), rhs.toList()) + if Swift.type(of: lhs) != Swift.type(of: rhs) { + return false + } + return deepEqualsCoreTests(lhs.aField, rhs.aField) } + func hash(into hasher: inout Hasher) { - deepHashCoreTests(value: toList(), hasher: &hasher) + hasher.combine("UnusedClass") + deepHashCoreTests(value: aField, hasher: &hasher) } } @@ -301,10 +353,66 @@ struct AllTypes: Hashable { ] } static func == (lhs: AllTypes, rhs: AllTypes) -> Bool { - return deepEqualsCoreTests(lhs.toList(), rhs.toList()) + if Swift.type(of: lhs) != Swift.type(of: rhs) { + return false + } + return deepEqualsCoreTests(lhs.aBool, rhs.aBool) && deepEqualsCoreTests(lhs.anInt, rhs.anInt) + && deepEqualsCoreTests(lhs.anInt64, rhs.anInt64) + && deepEqualsCoreTests(lhs.aDouble, rhs.aDouble) + && deepEqualsCoreTests(lhs.aByteArray, rhs.aByteArray) + && deepEqualsCoreTests(lhs.a4ByteArray, rhs.a4ByteArray) + && deepEqualsCoreTests(lhs.a8ByteArray, rhs.a8ByteArray) + && deepEqualsCoreTests(lhs.aFloatArray, rhs.aFloatArray) + && deepEqualsCoreTests(lhs.anEnum, rhs.anEnum) + && deepEqualsCoreTests(lhs.anotherEnum, rhs.anotherEnum) + && deepEqualsCoreTests(lhs.aString, rhs.aString) + && deepEqualsCoreTests(lhs.anObject, rhs.anObject) && deepEqualsCoreTests(lhs.list, rhs.list) + && deepEqualsCoreTests(lhs.stringList, rhs.stringList) + && deepEqualsCoreTests(lhs.intList, rhs.intList) + && deepEqualsCoreTests(lhs.doubleList, rhs.doubleList) + && deepEqualsCoreTests(lhs.boolList, rhs.boolList) + && deepEqualsCoreTests(lhs.enumList, rhs.enumList) + && deepEqualsCoreTests(lhs.objectList, rhs.objectList) + && deepEqualsCoreTests(lhs.listList, rhs.listList) + && deepEqualsCoreTests(lhs.mapList, rhs.mapList) && deepEqualsCoreTests(lhs.map, rhs.map) + && deepEqualsCoreTests(lhs.stringMap, rhs.stringMap) + && deepEqualsCoreTests(lhs.intMap, rhs.intMap) + && deepEqualsCoreTests(lhs.enumMap, rhs.enumMap) + && deepEqualsCoreTests(lhs.objectMap, rhs.objectMap) + && deepEqualsCoreTests(lhs.listMap, rhs.listMap) + && deepEqualsCoreTests(lhs.mapMap, rhs.mapMap) } + func hash(into hasher: inout Hasher) { - deepHashCoreTests(value: toList(), hasher: &hasher) + hasher.combine("AllTypes") + deepHashCoreTests(value: aBool, hasher: &hasher) + deepHashCoreTests(value: anInt, hasher: &hasher) + deepHashCoreTests(value: anInt64, hasher: &hasher) + deepHashCoreTests(value: aDouble, hasher: &hasher) + deepHashCoreTests(value: aByteArray, hasher: &hasher) + deepHashCoreTests(value: a4ByteArray, hasher: &hasher) + deepHashCoreTests(value: a8ByteArray, hasher: &hasher) + deepHashCoreTests(value: aFloatArray, hasher: &hasher) + deepHashCoreTests(value: anEnum, hasher: &hasher) + deepHashCoreTests(value: anotherEnum, hasher: &hasher) + deepHashCoreTests(value: aString, hasher: &hasher) + deepHashCoreTests(value: anObject, hasher: &hasher) + deepHashCoreTests(value: list, hasher: &hasher) + deepHashCoreTests(value: stringList, hasher: &hasher) + deepHashCoreTests(value: intList, hasher: &hasher) + deepHashCoreTests(value: doubleList, hasher: &hasher) + deepHashCoreTests(value: boolList, hasher: &hasher) + deepHashCoreTests(value: enumList, hasher: &hasher) + deepHashCoreTests(value: objectList, hasher: &hasher) + deepHashCoreTests(value: listList, hasher: &hasher) + deepHashCoreTests(value: mapList, hasher: &hasher) + deepHashCoreTests(value: map, hasher: &hasher) + deepHashCoreTests(value: stringMap, hasher: &hasher) + deepHashCoreTests(value: intMap, hasher: &hasher) + deepHashCoreTests(value: enumMap, hasher: &hasher) + deepHashCoreTests(value: objectMap, hasher: &hasher) + deepHashCoreTests(value: listMap, hasher: &hasher) + deepHashCoreTests(value: mapMap, hasher: &hasher) } } @@ -513,13 +621,77 @@ class AllNullableTypes: Hashable { ] } static func == (lhs: AllNullableTypes, rhs: AllNullableTypes) -> Bool { + if Swift.type(of: lhs) != Swift.type(of: rhs) { + return false + } if lhs === rhs { return true } - return deepEqualsCoreTests(lhs.toList(), rhs.toList()) + return deepEqualsCoreTests(lhs.aNullableBool, rhs.aNullableBool) + && deepEqualsCoreTests(lhs.aNullableInt, rhs.aNullableInt) + && deepEqualsCoreTests(lhs.aNullableInt64, rhs.aNullableInt64) + && deepEqualsCoreTests(lhs.aNullableDouble, rhs.aNullableDouble) + && deepEqualsCoreTests(lhs.aNullableByteArray, rhs.aNullableByteArray) + && deepEqualsCoreTests(lhs.aNullable4ByteArray, rhs.aNullable4ByteArray) + && deepEqualsCoreTests(lhs.aNullable8ByteArray, rhs.aNullable8ByteArray) + && deepEqualsCoreTests(lhs.aNullableFloatArray, rhs.aNullableFloatArray) + && deepEqualsCoreTests(lhs.aNullableEnum, rhs.aNullableEnum) + && deepEqualsCoreTests(lhs.anotherNullableEnum, rhs.anotherNullableEnum) + && deepEqualsCoreTests(lhs.aNullableString, rhs.aNullableString) + && deepEqualsCoreTests(lhs.aNullableObject, rhs.aNullableObject) + && deepEqualsCoreTests(lhs.allNullableTypes, rhs.allNullableTypes) + && deepEqualsCoreTests(lhs.list, rhs.list) + && deepEqualsCoreTests(lhs.stringList, rhs.stringList) + && deepEqualsCoreTests(lhs.intList, rhs.intList) + && deepEqualsCoreTests(lhs.doubleList, rhs.doubleList) + && deepEqualsCoreTests(lhs.boolList, rhs.boolList) + && deepEqualsCoreTests(lhs.enumList, rhs.enumList) + && deepEqualsCoreTests(lhs.objectList, rhs.objectList) + && deepEqualsCoreTests(lhs.listList, rhs.listList) + && deepEqualsCoreTests(lhs.mapList, rhs.mapList) + && deepEqualsCoreTests(lhs.recursiveClassList, rhs.recursiveClassList) + && deepEqualsCoreTests(lhs.map, rhs.map) && deepEqualsCoreTests(lhs.stringMap, rhs.stringMap) + && deepEqualsCoreTests(lhs.intMap, rhs.intMap) + && deepEqualsCoreTests(lhs.enumMap, rhs.enumMap) + && deepEqualsCoreTests(lhs.objectMap, rhs.objectMap) + && deepEqualsCoreTests(lhs.listMap, rhs.listMap) + && deepEqualsCoreTests(lhs.mapMap, rhs.mapMap) + && deepEqualsCoreTests(lhs.recursiveClassMap, rhs.recursiveClassMap) } + func hash(into hasher: inout Hasher) { - deepHashCoreTests(value: toList(), hasher: &hasher) + hasher.combine("AllNullableTypes") + deepHashCoreTests(value: aNullableBool, hasher: &hasher) + deepHashCoreTests(value: aNullableInt, hasher: &hasher) + deepHashCoreTests(value: aNullableInt64, hasher: &hasher) + deepHashCoreTests(value: aNullableDouble, hasher: &hasher) + deepHashCoreTests(value: aNullableByteArray, hasher: &hasher) + deepHashCoreTests(value: aNullable4ByteArray, hasher: &hasher) + deepHashCoreTests(value: aNullable8ByteArray, hasher: &hasher) + deepHashCoreTests(value: aNullableFloatArray, hasher: &hasher) + deepHashCoreTests(value: aNullableEnum, hasher: &hasher) + deepHashCoreTests(value: anotherNullableEnum, hasher: &hasher) + deepHashCoreTests(value: aNullableString, hasher: &hasher) + deepHashCoreTests(value: aNullableObject, hasher: &hasher) + deepHashCoreTests(value: allNullableTypes, hasher: &hasher) + deepHashCoreTests(value: list, hasher: &hasher) + deepHashCoreTests(value: stringList, hasher: &hasher) + deepHashCoreTests(value: intList, hasher: &hasher) + deepHashCoreTests(value: doubleList, hasher: &hasher) + deepHashCoreTests(value: boolList, hasher: &hasher) + deepHashCoreTests(value: enumList, hasher: &hasher) + deepHashCoreTests(value: objectList, hasher: &hasher) + deepHashCoreTests(value: listList, hasher: &hasher) + deepHashCoreTests(value: mapList, hasher: &hasher) + deepHashCoreTests(value: recursiveClassList, hasher: &hasher) + deepHashCoreTests(value: map, hasher: &hasher) + deepHashCoreTests(value: stringMap, hasher: &hasher) + deepHashCoreTests(value: intMap, hasher: &hasher) + deepHashCoreTests(value: enumMap, hasher: &hasher) + deepHashCoreTests(value: objectMap, hasher: &hasher) + deepHashCoreTests(value: listMap, hasher: &hasher) + deepHashCoreTests(value: mapMap, hasher: &hasher) + deepHashCoreTests(value: recursiveClassMap, hasher: &hasher) } } @@ -655,10 +827,68 @@ struct AllNullableTypesWithoutRecursion: Hashable { static func == (lhs: AllNullableTypesWithoutRecursion, rhs: AllNullableTypesWithoutRecursion) -> Bool { - return deepEqualsCoreTests(lhs.toList(), rhs.toList()) + if Swift.type(of: lhs) != Swift.type(of: rhs) { + return false + } + return deepEqualsCoreTests(lhs.aNullableBool, rhs.aNullableBool) + && deepEqualsCoreTests(lhs.aNullableInt, rhs.aNullableInt) + && deepEqualsCoreTests(lhs.aNullableInt64, rhs.aNullableInt64) + && deepEqualsCoreTests(lhs.aNullableDouble, rhs.aNullableDouble) + && deepEqualsCoreTests(lhs.aNullableByteArray, rhs.aNullableByteArray) + && deepEqualsCoreTests(lhs.aNullable4ByteArray, rhs.aNullable4ByteArray) + && deepEqualsCoreTests(lhs.aNullable8ByteArray, rhs.aNullable8ByteArray) + && deepEqualsCoreTests(lhs.aNullableFloatArray, rhs.aNullableFloatArray) + && deepEqualsCoreTests(lhs.aNullableEnum, rhs.aNullableEnum) + && deepEqualsCoreTests(lhs.anotherNullableEnum, rhs.anotherNullableEnum) + && deepEqualsCoreTests(lhs.aNullableString, rhs.aNullableString) + && deepEqualsCoreTests(lhs.aNullableObject, rhs.aNullableObject) + && deepEqualsCoreTests(lhs.list, rhs.list) + && deepEqualsCoreTests(lhs.stringList, rhs.stringList) + && deepEqualsCoreTests(lhs.intList, rhs.intList) + && deepEqualsCoreTests(lhs.doubleList, rhs.doubleList) + && deepEqualsCoreTests(lhs.boolList, rhs.boolList) + && deepEqualsCoreTests(lhs.enumList, rhs.enumList) + && deepEqualsCoreTests(lhs.objectList, rhs.objectList) + && deepEqualsCoreTests(lhs.listList, rhs.listList) + && deepEqualsCoreTests(lhs.mapList, rhs.mapList) && deepEqualsCoreTests(lhs.map, rhs.map) + && deepEqualsCoreTests(lhs.stringMap, rhs.stringMap) + && deepEqualsCoreTests(lhs.intMap, rhs.intMap) + && deepEqualsCoreTests(lhs.enumMap, rhs.enumMap) + && deepEqualsCoreTests(lhs.objectMap, rhs.objectMap) + && deepEqualsCoreTests(lhs.listMap, rhs.listMap) + && deepEqualsCoreTests(lhs.mapMap, rhs.mapMap) } + func hash(into hasher: inout Hasher) { - deepHashCoreTests(value: toList(), hasher: &hasher) + hasher.combine("AllNullableTypesWithoutRecursion") + deepHashCoreTests(value: aNullableBool, hasher: &hasher) + deepHashCoreTests(value: aNullableInt, hasher: &hasher) + deepHashCoreTests(value: aNullableInt64, hasher: &hasher) + deepHashCoreTests(value: aNullableDouble, hasher: &hasher) + deepHashCoreTests(value: aNullableByteArray, hasher: &hasher) + deepHashCoreTests(value: aNullable4ByteArray, hasher: &hasher) + deepHashCoreTests(value: aNullable8ByteArray, hasher: &hasher) + deepHashCoreTests(value: aNullableFloatArray, hasher: &hasher) + deepHashCoreTests(value: aNullableEnum, hasher: &hasher) + deepHashCoreTests(value: anotherNullableEnum, hasher: &hasher) + deepHashCoreTests(value: aNullableString, hasher: &hasher) + deepHashCoreTests(value: aNullableObject, hasher: &hasher) + deepHashCoreTests(value: list, hasher: &hasher) + deepHashCoreTests(value: stringList, hasher: &hasher) + deepHashCoreTests(value: intList, hasher: &hasher) + deepHashCoreTests(value: doubleList, hasher: &hasher) + deepHashCoreTests(value: boolList, hasher: &hasher) + deepHashCoreTests(value: enumList, hasher: &hasher) + deepHashCoreTests(value: objectList, hasher: &hasher) + deepHashCoreTests(value: listList, hasher: &hasher) + deepHashCoreTests(value: mapList, hasher: &hasher) + deepHashCoreTests(value: map, hasher: &hasher) + deepHashCoreTests(value: stringMap, hasher: &hasher) + deepHashCoreTests(value: intMap, hasher: &hasher) + deepHashCoreTests(value: enumMap, hasher: &hasher) + deepHashCoreTests(value: objectMap, hasher: &hasher) + deepHashCoreTests(value: listMap, hasher: &hasher) + deepHashCoreTests(value: mapMap, hasher: &hasher) } } @@ -712,10 +942,28 @@ struct AllClassesWrapper: Hashable { ] } static func == (lhs: AllClassesWrapper, rhs: AllClassesWrapper) -> Bool { - return deepEqualsCoreTests(lhs.toList(), rhs.toList()) + if Swift.type(of: lhs) != Swift.type(of: rhs) { + return false + } + return deepEqualsCoreTests(lhs.allNullableTypes, rhs.allNullableTypes) + && deepEqualsCoreTests( + lhs.allNullableTypesWithoutRecursion, rhs.allNullableTypesWithoutRecursion) + && deepEqualsCoreTests(lhs.allTypes, rhs.allTypes) + && deepEqualsCoreTests(lhs.classList, rhs.classList) + && deepEqualsCoreTests(lhs.nullableClassList, rhs.nullableClassList) + && deepEqualsCoreTests(lhs.classMap, rhs.classMap) + && deepEqualsCoreTests(lhs.nullableClassMap, rhs.nullableClassMap) } + func hash(into hasher: inout Hasher) { - deepHashCoreTests(value: toList(), hasher: &hasher) + hasher.combine("AllClassesWrapper") + deepHashCoreTests(value: allNullableTypes, hasher: &hasher) + deepHashCoreTests(value: allNullableTypesWithoutRecursion, hasher: &hasher) + deepHashCoreTests(value: allTypes, hasher: &hasher) + deepHashCoreTests(value: classList, hasher: &hasher) + deepHashCoreTests(value: nullableClassList, hasher: &hasher) + deepHashCoreTests(value: classMap, hasher: &hasher) + deepHashCoreTests(value: nullableClassMap, hasher: &hasher) } } @@ -739,10 +987,15 @@ struct TestMessage: Hashable { ] } static func == (lhs: TestMessage, rhs: TestMessage) -> Bool { - return deepEqualsCoreTests(lhs.toList(), rhs.toList()) + if Swift.type(of: lhs) != Swift.type(of: rhs) { + return false + } + return deepEqualsCoreTests(lhs.testList, rhs.testList) } + func hash(into hasher: inout Hasher) { - deepHashCoreTests(value: toList(), hasher: &hasher) + hasher.combine("TestMessage") + deepHashCoreTests(value: testList, hasher: &hasher) } } @@ -893,6 +1146,13 @@ protocol HostIntegrationCoreApi { func echoOptionalDefault(_ aDouble: Double) throws -> Double /// Returns passed in int. func echoRequired(_ anInt: Int64) throws -> Int64 + /// Returns the result of platform-side equality check. + func areAllNullableTypesEqual(a: AllNullableTypes, b: AllNullableTypes) throws -> Bool + /// Returns the platform-side hash code for the given object. + func getAllNullableTypesHash(value: AllNullableTypes) throws -> Int64 + /// Returns the platform-side hash code for the given object. + func getAllNullableTypesWithoutRecursionHash(value: AllNullableTypesWithoutRecursion) throws + -> Int64 /// Returns the passed object, to test serialization and deserialization. func echo(_ everything: AllNullableTypes?) throws -> AllNullableTypes? /// Returns the passed object, to test serialization and deserialization. @@ -1785,6 +2045,64 @@ class HostIntegrationCoreApiSetup { } else { echoRequiredIntChannel.setMessageHandler(nil) } + /// Returns the result of platform-side equality check. + let areAllNullableTypesEqualChannel = FlutterBasicMessageChannel( + name: + "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.areAllNullableTypesEqual\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + areAllNullableTypesEqualChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let aArg = args[0] as! AllNullableTypes + let bArg = args[1] as! AllNullableTypes + do { + let result = try api.areAllNullableTypesEqual(a: aArg, b: bArg) + reply(wrapResult(result)) + } catch { + reply(wrapError(error)) + } + } + } else { + areAllNullableTypesEqualChannel.setMessageHandler(nil) + } + /// Returns the platform-side hash code for the given object. + let getAllNullableTypesHashChannel = FlutterBasicMessageChannel( + name: + "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.getAllNullableTypesHash\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + getAllNullableTypesHashChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let valueArg = args[0] as! AllNullableTypes + do { + let result = try api.getAllNullableTypesHash(value: valueArg) + reply(wrapResult(result)) + } catch { + reply(wrapError(error)) + } + } + } else { + getAllNullableTypesHashChannel.setMessageHandler(nil) + } + /// Returns the platform-side hash code for the given object. + let getAllNullableTypesWithoutRecursionHashChannel = FlutterBasicMessageChannel( + name: + "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi.getAllNullableTypesWithoutRecursionHash\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + getAllNullableTypesWithoutRecursionHashChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let valueArg = args[0] as! AllNullableTypesWithoutRecursion + do { + let result = try api.getAllNullableTypesWithoutRecursionHash(value: valueArg) + reply(wrapResult(result)) + } catch { + reply(wrapError(error)) + } + } + } else { + getAllNullableTypesWithoutRecursionHashChannel.setMessageHandler(nil) + } /// Returns the passed object, to test serialization and deserialization. let echoAllNullableTypesChannel = FlutterBasicMessageChannel( name: diff --git a/packages/pigeon/platform_tests/test_plugin/darwin/test_plugin/Sources/test_plugin/EventChannelTests.gen.swift b/packages/pigeon/platform_tests/test_plugin/darwin/test_plugin/Sources/test_plugin/EventChannelTests.gen.swift index 6eeace16d903..da3e19626382 100644 --- a/packages/pigeon/platform_tests/test_plugin/darwin/test_plugin/Sources/test_plugin/EventChannelTests.gen.swift +++ b/packages/pigeon/platform_tests/test_plugin/darwin/test_plugin/Sources/test_plugin/EventChannelTests.gen.swift @@ -42,6 +42,19 @@ private func nilOrValue(_ value: Any?) -> T? { return value as! T? } +private func doubleEqualsEventChannelTests(_ lhs: Double, _ rhs: Double) -> Bool { + return (lhs.isNaN && rhs.isNaN) || lhs == rhs +} + +private func doubleHashEventChannelTests(_ value: Double, _ hasher: inout Hasher) { + if value.isNaN { + hasher.combine(0x7FF8_0000_0000_0000) + } else { + // Normalize -0.0 to 0.0 + hasher.combine(value == 0 ? 0 : value) + } +} + func deepEqualsEventChannelTests(_ lhs: Any?, _ rhs: Any?) -> Bool { let cleanLhs = nilOrValue(lhs) as Any? let cleanRhs = nilOrValue(rhs) as Any? @@ -52,56 +65,90 @@ func deepEqualsEventChannelTests(_ lhs: Any?, _ rhs: Any?) -> Bool { case (nil, _), (_, nil): return false - case is (Void, Void): + case (let lhs as AnyObject, let rhs as AnyObject) where lhs === rhs: return true - case let (cleanLhsHashable, cleanRhsHashable) as (AnyHashable, AnyHashable): - return cleanLhsHashable == cleanRhsHashable + case is (Void, Void): + return true - case let (cleanLhsArray, cleanRhsArray) as ([Any?], [Any?]): - guard cleanLhsArray.count == cleanRhsArray.count else { return false } - for (index, element) in cleanLhsArray.enumerated() { - if !deepEqualsEventChannelTests(element, cleanRhsArray[index]) { + case (let lhsArray, let rhsArray) as ([Any?], [Any?]): + guard lhsArray.count == rhsArray.count else { return false } + for (index, element) in lhsArray.enumerated() { + if !deepEqualsEventChannelTests(element, rhsArray[index]) { return false } } return true - case let (cleanLhsDictionary, cleanRhsDictionary) as ([AnyHashable: Any?], [AnyHashable: Any?]): - guard cleanLhsDictionary.count == cleanRhsDictionary.count else { return false } - for (key, cleanLhsValue) in cleanLhsDictionary { - guard cleanRhsDictionary.index(forKey: key) != nil else { return false } - if !deepEqualsEventChannelTests(cleanLhsValue, cleanRhsDictionary[key]!) { + case (let lhsArray, let rhsArray) as ([Double], [Double]): + guard lhsArray.count == rhsArray.count else { return false } + for (index, element) in lhsArray.enumerated() { + if !doubleEqualsEventChannelTests(element, rhsArray[index]) { return false } } return true + case (let lhsDictionary, let rhsDictionary) as ([AnyHashable: Any?], [AnyHashable: Any?]): + guard lhsDictionary.count == rhsDictionary.count else { return false } + for (lhsKey, lhsValue) in lhsDictionary { + var found = false + for (rhsKey, rhsValue) in rhsDictionary { + if deepEqualsEventChannelTests(lhsKey, rhsKey) { + if deepEqualsEventChannelTests(lhsValue, rhsValue) { + found = true + break + } else { + return false + } + } + } + if !found { return false } + } + return true + + case (let lhs as Double, let rhs as Double): + return doubleEqualsEventChannelTests(lhs, rhs) + + case (let lhsHashable, let rhsHashable) as (AnyHashable, AnyHashable): + return lhsHashable == rhsHashable + default: - // Any other type shouldn't be able to be used with pigeon. File an issue if you find this to be untrue. return false } } func deepHashEventChannelTests(value: Any?, hasher: inout Hasher) { - if let valueList = value as? [AnyHashable] { - for item in valueList { deepHashEventChannelTests(value: item, hasher: &hasher) } - return - } - - if let valueDict = value as? [AnyHashable: AnyHashable] { - for key in valueDict.keys { - hasher.combine(key) - deepHashEventChannelTests(value: valueDict[key]!, hasher: &hasher) + let cleanValue = nilOrValue(value) as Any? + if let cleanValue = cleanValue { + if let doubleValue = cleanValue as? Double { + doubleHashEventChannelTests(doubleValue, &hasher) + } else if let valueList = cleanValue as? [Any?] { + for item in valueList { + deepHashEventChannelTests(value: item, hasher: &hasher) + } + } else if let valueList = cleanValue as? [Double] { + for item in valueList { + doubleHashEventChannelTests(item, &hasher) + } + } else if let valueDict = cleanValue as? [AnyHashable: Any?] { + var result = 0 + for (key, value) in valueDict { + var entryKeyHasher = Hasher() + deepHashEventChannelTests(value: key, hasher: &entryKeyHasher) + var entryValueHasher = Hasher() + deepHashEventChannelTests(value: value, hasher: &entryValueHasher) + result = result &+ ((entryKeyHasher.finalize() &* 31) ^ entryValueHasher.finalize()) + } + hasher.combine(result) + } else if let hashableValue = cleanValue as? AnyHashable { + hasher.combine(hashableValue) + } else { + hasher.combine(String(describing: cleanValue)) } - return - } - - if let hashableValue = value as? AnyHashable { - hasher.combine(hashableValue.hashValue) + } else { + hasher.combine(0) } - - return hasher.combine(String(describing: value)) } enum EventEnum: Int { @@ -321,13 +368,78 @@ class EventAllNullableTypes: Hashable { ] } static func == (lhs: EventAllNullableTypes, rhs: EventAllNullableTypes) -> Bool { + if Swift.type(of: lhs) != Swift.type(of: rhs) { + return false + } if lhs === rhs { return true } - return deepEqualsEventChannelTests(lhs.toList(), rhs.toList()) + return deepEqualsEventChannelTests(lhs.aNullableBool, rhs.aNullableBool) + && deepEqualsEventChannelTests(lhs.aNullableInt, rhs.aNullableInt) + && deepEqualsEventChannelTests(lhs.aNullableInt64, rhs.aNullableInt64) + && deepEqualsEventChannelTests(lhs.aNullableDouble, rhs.aNullableDouble) + && deepEqualsEventChannelTests(lhs.aNullableByteArray, rhs.aNullableByteArray) + && deepEqualsEventChannelTests(lhs.aNullable4ByteArray, rhs.aNullable4ByteArray) + && deepEqualsEventChannelTests(lhs.aNullable8ByteArray, rhs.aNullable8ByteArray) + && deepEqualsEventChannelTests(lhs.aNullableFloatArray, rhs.aNullableFloatArray) + && deepEqualsEventChannelTests(lhs.aNullableEnum, rhs.aNullableEnum) + && deepEqualsEventChannelTests(lhs.anotherNullableEnum, rhs.anotherNullableEnum) + && deepEqualsEventChannelTests(lhs.aNullableString, rhs.aNullableString) + && deepEqualsEventChannelTests(lhs.aNullableObject, rhs.aNullableObject) + && deepEqualsEventChannelTests(lhs.allNullableTypes, rhs.allNullableTypes) + && deepEqualsEventChannelTests(lhs.list, rhs.list) + && deepEqualsEventChannelTests(lhs.stringList, rhs.stringList) + && deepEqualsEventChannelTests(lhs.intList, rhs.intList) + && deepEqualsEventChannelTests(lhs.doubleList, rhs.doubleList) + && deepEqualsEventChannelTests(lhs.boolList, rhs.boolList) + && deepEqualsEventChannelTests(lhs.enumList, rhs.enumList) + && deepEqualsEventChannelTests(lhs.objectList, rhs.objectList) + && deepEqualsEventChannelTests(lhs.listList, rhs.listList) + && deepEqualsEventChannelTests(lhs.mapList, rhs.mapList) + && deepEqualsEventChannelTests(lhs.recursiveClassList, rhs.recursiveClassList) + && deepEqualsEventChannelTests(lhs.map, rhs.map) + && deepEqualsEventChannelTests(lhs.stringMap, rhs.stringMap) + && deepEqualsEventChannelTests(lhs.intMap, rhs.intMap) + && deepEqualsEventChannelTests(lhs.enumMap, rhs.enumMap) + && deepEqualsEventChannelTests(lhs.objectMap, rhs.objectMap) + && deepEqualsEventChannelTests(lhs.listMap, rhs.listMap) + && deepEqualsEventChannelTests(lhs.mapMap, rhs.mapMap) + && deepEqualsEventChannelTests(lhs.recursiveClassMap, rhs.recursiveClassMap) } + func hash(into hasher: inout Hasher) { - deepHashEventChannelTests(value: toList(), hasher: &hasher) + hasher.combine("EventAllNullableTypes") + deepHashEventChannelTests(value: aNullableBool, hasher: &hasher) + deepHashEventChannelTests(value: aNullableInt, hasher: &hasher) + deepHashEventChannelTests(value: aNullableInt64, hasher: &hasher) + deepHashEventChannelTests(value: aNullableDouble, hasher: &hasher) + deepHashEventChannelTests(value: aNullableByteArray, hasher: &hasher) + deepHashEventChannelTests(value: aNullable4ByteArray, hasher: &hasher) + deepHashEventChannelTests(value: aNullable8ByteArray, hasher: &hasher) + deepHashEventChannelTests(value: aNullableFloatArray, hasher: &hasher) + deepHashEventChannelTests(value: aNullableEnum, hasher: &hasher) + deepHashEventChannelTests(value: anotherNullableEnum, hasher: &hasher) + deepHashEventChannelTests(value: aNullableString, hasher: &hasher) + deepHashEventChannelTests(value: aNullableObject, hasher: &hasher) + deepHashEventChannelTests(value: allNullableTypes, hasher: &hasher) + deepHashEventChannelTests(value: list, hasher: &hasher) + deepHashEventChannelTests(value: stringList, hasher: &hasher) + deepHashEventChannelTests(value: intList, hasher: &hasher) + deepHashEventChannelTests(value: doubleList, hasher: &hasher) + deepHashEventChannelTests(value: boolList, hasher: &hasher) + deepHashEventChannelTests(value: enumList, hasher: &hasher) + deepHashEventChannelTests(value: objectList, hasher: &hasher) + deepHashEventChannelTests(value: listList, hasher: &hasher) + deepHashEventChannelTests(value: mapList, hasher: &hasher) + deepHashEventChannelTests(value: recursiveClassList, hasher: &hasher) + deepHashEventChannelTests(value: map, hasher: &hasher) + deepHashEventChannelTests(value: stringMap, hasher: &hasher) + deepHashEventChannelTests(value: intMap, hasher: &hasher) + deepHashEventChannelTests(value: enumMap, hasher: &hasher) + deepHashEventChannelTests(value: objectMap, hasher: &hasher) + deepHashEventChannelTests(value: listMap, hasher: &hasher) + deepHashEventChannelTests(value: mapMap, hasher: &hasher) + deepHashEventChannelTests(value: recursiveClassMap, hasher: &hasher) } } @@ -355,10 +467,15 @@ struct IntEvent: PlatformEvent { ] } static func == (lhs: IntEvent, rhs: IntEvent) -> Bool { - return deepEqualsEventChannelTests(lhs.toList(), rhs.toList()) + if Swift.type(of: lhs) != Swift.type(of: rhs) { + return false + } + return deepEqualsEventChannelTests(lhs.value, rhs.value) } + func hash(into hasher: inout Hasher) { - deepHashEventChannelTests(value: toList(), hasher: &hasher) + hasher.combine("IntEvent") + deepHashEventChannelTests(value: value, hasher: &hasher) } } @@ -380,10 +497,15 @@ struct StringEvent: PlatformEvent { ] } static func == (lhs: StringEvent, rhs: StringEvent) -> Bool { - return deepEqualsEventChannelTests(lhs.toList(), rhs.toList()) + if Swift.type(of: lhs) != Swift.type(of: rhs) { + return false + } + return deepEqualsEventChannelTests(lhs.value, rhs.value) } + func hash(into hasher: inout Hasher) { - deepHashEventChannelTests(value: toList(), hasher: &hasher) + hasher.combine("StringEvent") + deepHashEventChannelTests(value: value, hasher: &hasher) } } @@ -405,10 +527,15 @@ struct BoolEvent: PlatformEvent { ] } static func == (lhs: BoolEvent, rhs: BoolEvent) -> Bool { - return deepEqualsEventChannelTests(lhs.toList(), rhs.toList()) + if Swift.type(of: lhs) != Swift.type(of: rhs) { + return false + } + return deepEqualsEventChannelTests(lhs.value, rhs.value) } + func hash(into hasher: inout Hasher) { - deepHashEventChannelTests(value: toList(), hasher: &hasher) + hasher.combine("BoolEvent") + deepHashEventChannelTests(value: value, hasher: &hasher) } } @@ -430,10 +557,15 @@ struct DoubleEvent: PlatformEvent { ] } static func == (lhs: DoubleEvent, rhs: DoubleEvent) -> Bool { - return deepEqualsEventChannelTests(lhs.toList(), rhs.toList()) + if Swift.type(of: lhs) != Swift.type(of: rhs) { + return false + } + return deepEqualsEventChannelTests(lhs.value, rhs.value) } + func hash(into hasher: inout Hasher) { - deepHashEventChannelTests(value: toList(), hasher: &hasher) + hasher.combine("DoubleEvent") + deepHashEventChannelTests(value: value, hasher: &hasher) } } @@ -455,10 +587,15 @@ struct ObjectsEvent: PlatformEvent { ] } static func == (lhs: ObjectsEvent, rhs: ObjectsEvent) -> Bool { - return deepEqualsEventChannelTests(lhs.toList(), rhs.toList()) + if Swift.type(of: lhs) != Swift.type(of: rhs) { + return false + } + return deepEqualsEventChannelTests(lhs.value, rhs.value) } + func hash(into hasher: inout Hasher) { - deepHashEventChannelTests(value: toList(), hasher: &hasher) + hasher.combine("ObjectsEvent") + deepHashEventChannelTests(value: value, hasher: &hasher) } } @@ -480,10 +617,15 @@ struct EnumEvent: PlatformEvent { ] } static func == (lhs: EnumEvent, rhs: EnumEvent) -> Bool { - return deepEqualsEventChannelTests(lhs.toList(), rhs.toList()) + if Swift.type(of: lhs) != Swift.type(of: rhs) { + return false + } + return deepEqualsEventChannelTests(lhs.value, rhs.value) } + func hash(into hasher: inout Hasher) { - deepHashEventChannelTests(value: toList(), hasher: &hasher) + hasher.combine("EnumEvent") + deepHashEventChannelTests(value: value, hasher: &hasher) } } @@ -505,10 +647,15 @@ struct ClassEvent: PlatformEvent { ] } static func == (lhs: ClassEvent, rhs: ClassEvent) -> Bool { - return deepEqualsEventChannelTests(lhs.toList(), rhs.toList()) + if Swift.type(of: lhs) != Swift.type(of: rhs) { + return false + } + return deepEqualsEventChannelTests(lhs.value, rhs.value) } + func hash(into hasher: inout Hasher) { - deepHashEventChannelTests(value: toList(), hasher: &hasher) + hasher.combine("ClassEvent") + deepHashEventChannelTests(value: value, hasher: &hasher) } } diff --git a/packages/pigeon/platform_tests/test_plugin/darwin/test_plugin/Sources/test_plugin/ProxyApiTests.gen.swift b/packages/pigeon/platform_tests/test_plugin/darwin/test_plugin/Sources/test_plugin/ProxyApiTests.gen.swift index 56de32c5cf13..5eb4b81803ad 100644 --- a/packages/pigeon/platform_tests/test_plugin/darwin/test_plugin/Sources/test_plugin/ProxyApiTests.gen.swift +++ b/packages/pigeon/platform_tests/test_plugin/darwin/test_plugin/Sources/test_plugin/ProxyApiTests.gen.swift @@ -54,7 +54,7 @@ private func wrapError(_ error: Any) -> [Any?] { } return [ "\(error)", - "\(type(of: error))", + "\(Swift.type(of: error))", "Stacktrace: \(Thread.callStackSymbols)", ] } @@ -2850,6 +2850,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterNoop` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -2885,6 +2894,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterThrowError` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -2921,6 +2939,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterThrowErrorFromVoid` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -2956,6 +2983,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterEchoBool` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -2998,6 +3034,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterEchoInt` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -3040,6 +3085,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterEchoDouble` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -3082,6 +3136,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterEchoString` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -3124,6 +3187,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterEchoUint8List` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -3166,6 +3238,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterEchoList` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -3209,6 +3290,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterEchoProxyApiList` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -3251,6 +3341,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterEchoMap` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -3295,6 +3394,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterEchoProxyApiMap` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -3337,6 +3445,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterEchoEnum` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -3379,6 +3496,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterEchoProxyApi` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -3421,6 +3547,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterEchoNullableBool` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -3457,6 +3592,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterEchoNullableInt` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -3493,6 +3637,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterEchoNullableDouble` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -3529,6 +3682,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterEchoNullableString` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -3565,6 +3727,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterEchoNullableUint8List` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -3601,6 +3772,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterEchoNullableList` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -3637,6 +3817,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterEchoNullableMap` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -3673,6 +3862,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterEchoNullableEnum` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -3710,6 +3908,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterEchoNullableProxyApi` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -3747,6 +3954,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterNoopAsync` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -3782,6 +3998,15 @@ final class PigeonApiProxyApiTestClass: PigeonApiProtocolProxyApiTestClass { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiTestClass.flutterEchoAsyncString` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec @@ -3987,6 +4212,15 @@ final class PigeonApiProxyApiInterface: PigeonApiProtocolProxyApiInterface { code: "ignore-calls-error", message: "Calls to Dart are being ignored.", details: ""))) return + } else if !pigeonRegistrar.instanceManager.containsInstance(pigeonInstanceArg as AnyObject) { + completion( + .failure( + ProxyApiTestsError( + code: "missing-instance-error", + message: + "Callback to `ProxyApiInterface.anInterfaceMethod` failed because native instance was not in the instance manager.", + details: ""))) + return } let binaryMessenger = pigeonRegistrar.binaryMessenger let codec = pigeonRegistrar.codec diff --git a/packages/pigeon/platform_tests/test_plugin/darwin/test_plugin/Sources/test_plugin/TestPlugin.swift b/packages/pigeon/platform_tests/test_plugin/darwin/test_plugin/Sources/test_plugin/TestPlugin.swift index a6e538b16180..89d25d32f58e 100644 --- a/packages/pigeon/platform_tests/test_plugin/darwin/test_plugin/Sources/test_plugin/TestPlugin.swift +++ b/packages/pigeon/platform_tests/test_plugin/darwin/test_plugin/Sources/test_plugin/TestPlugin.swift @@ -70,6 +70,22 @@ public class TestPlugin: NSObject, FlutterPlugin, HostIntegrationCoreApi { func echo(_ everything: AllNullableTypes?) -> AllNullableTypes? { return everything } + + func areAllNullableTypesEqual(a: AllNullableTypes, b: AllNullableTypes) -> Bool { + return a == b + } + + func getAllNullableTypesHash(value: AllNullableTypes) -> Int64 { + var hasher = Hasher() + value.hash(into: &hasher) + return Int64(hasher.finalize()) + } + + func getAllNullableTypesWithoutRecursionHash(value: AllNullableTypesWithoutRecursion) -> Int64 { + var hasher = Hasher() + value.hash(into: &hasher) + return Int64(hasher.finalize()) + } func echo(_ everything: AllNullableTypesWithoutRecursion?) throws -> AllNullableTypesWithoutRecursion? { @@ -1329,871 +1345,871 @@ class SendConsistentNumbers: StreamConsistentNumbersStreamHandler { } } -class ProxyApiDelegate: ProxyApiTestsPigeonProxyApiDelegate { - func pigeonApiProxyApiTestClass(_ registrar: ProxyApiTestsPigeonProxyApiRegistrar) - -> PigeonApiProxyApiTestClass +class ProxyApiTestClassDelegate: PigeonApiDelegateProxyApiTestClass { + func pigeonDefaultConstructor( + pigeonApi: PigeonApiProxyApiTestClass, aBool: Bool, anInt: Int64, aDouble: Double, + aString: String, aUint8List: FlutterStandardTypedData, aList: [Any?], aMap: [String?: Any?], + anEnum: ProxyApiTestEnum, aProxyApi: ProxyApiSuperClass, aNullableBool: Bool?, + aNullableInt: Int64?, aNullableDouble: Double?, aNullableString: String?, + aNullableUint8List: FlutterStandardTypedData?, aNullableList: [Any?]?, + aNullableMap: [String?: Any?]?, aNullableEnum: ProxyApiTestEnum?, + aNullableProxyApi: ProxyApiSuperClass?, boolParam: Bool, intParam: Int64, + doubleParam: Double, stringParam: String, aUint8ListParam: FlutterStandardTypedData, + listParam: [Any?], mapParam: [String?: Any?], enumParam: ProxyApiTestEnum, + proxyApiParam: ProxyApiSuperClass, nullableBoolParam: Bool?, nullableIntParam: Int64?, + nullableDoubleParam: Double?, nullableStringParam: String?, + nullableUint8ListParam: FlutterStandardTypedData?, nullableListParam: [Any?]?, + nullableMapParam: [String?: Any?]?, nullableEnumParam: ProxyApiTestEnum?, + nullableProxyApiParam: ProxyApiSuperClass? + ) throws -> ProxyApiTestClass { + return ProxyApiTestClass() + } + + func namedConstructor( + pigeonApi: PigeonApiProxyApiTestClass, aBool: Bool, anInt: Int64, aDouble: Double, + aString: String, aUint8List: FlutterStandardTypedData, aList: [Any?], aMap: [String?: Any?], + anEnum: ProxyApiTestEnum, aProxyApi: ProxyApiSuperClass, aNullableBool: Bool?, + aNullableInt: Int64?, aNullableDouble: Double?, aNullableString: String?, + aNullableUint8List: FlutterStandardTypedData?, aNullableList: [Any?]?, + aNullableMap: [String?: Any?]?, aNullableEnum: ProxyApiTestEnum?, + aNullableProxyApi: ProxyApiSuperClass? + ) throws -> ProxyApiTestClass { + return ProxyApiTestClass() + } + + func attachedField(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) + throws -> ProxyApiSuperClass { - class ProxyApiTestClassDelegate: PigeonApiDelegateProxyApiTestClass { - func pigeonDefaultConstructor( - pigeonApi: PigeonApiProxyApiTestClass, aBool: Bool, anInt: Int64, aDouble: Double, - aString: String, aUint8List: FlutterStandardTypedData, aList: [Any?], aMap: [String?: Any?], - anEnum: ProxyApiTestEnum, aProxyApi: ProxyApiSuperClass, aNullableBool: Bool?, - aNullableInt: Int64?, aNullableDouble: Double?, aNullableString: String?, - aNullableUint8List: FlutterStandardTypedData?, aNullableList: [Any?]?, - aNullableMap: [String?: Any?]?, aNullableEnum: ProxyApiTestEnum?, - aNullableProxyApi: ProxyApiSuperClass?, boolParam: Bool, intParam: Int64, - doubleParam: Double, stringParam: String, aUint8ListParam: FlutterStandardTypedData, - listParam: [Any?], mapParam: [String?: Any?], enumParam: ProxyApiTestEnum, - proxyApiParam: ProxyApiSuperClass, nullableBoolParam: Bool?, nullableIntParam: Int64?, - nullableDoubleParam: Double?, nullableStringParam: String?, - nullableUint8ListParam: FlutterStandardTypedData?, nullableListParam: [Any?]?, - nullableMapParam: [String?: Any?]?, nullableEnumParam: ProxyApiTestEnum?, - nullableProxyApiParam: ProxyApiSuperClass? - ) throws -> ProxyApiTestClass { - return ProxyApiTestClass() - } - - func namedConstructor( - pigeonApi: PigeonApiProxyApiTestClass, aBool: Bool, anInt: Int64, aDouble: Double, - aString: String, aUint8List: FlutterStandardTypedData, aList: [Any?], aMap: [String?: Any?], - anEnum: ProxyApiTestEnum, aProxyApi: ProxyApiSuperClass, aNullableBool: Bool?, - aNullableInt: Int64?, aNullableDouble: Double?, aNullableString: String?, - aNullableUint8List: FlutterStandardTypedData?, aNullableList: [Any?]?, - aNullableMap: [String?: Any?]?, aNullableEnum: ProxyApiTestEnum?, - aNullableProxyApi: ProxyApiSuperClass? - ) throws -> ProxyApiTestClass { - return ProxyApiTestClass() - } - - func attachedField(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) - throws -> ProxyApiSuperClass - { - return ProxyApiSuperClass() - } + return ProxyApiSuperClass() + } - func staticAttachedField(pigeonApi: PigeonApiProxyApiTestClass) throws -> ProxyApiSuperClass { - return ProxyApiSuperClass() - } + func staticAttachedField(pigeonApi: PigeonApiProxyApiTestClass) throws -> ProxyApiSuperClass { + return ProxyApiSuperClass() + } - func aBool(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) throws - -> Bool - { - return true - } + func aBool(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) throws + -> Bool + { + return true + } - func anInt(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) throws - -> Int64 - { - return 0 - } + func anInt(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) throws + -> Int64 + { + return 0 + } - func aDouble(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) throws - -> Double - { - return 0.0 - } + func aDouble(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) throws + -> Double + { + return 0.0 + } - func aString(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) throws - -> String - { - return "" - } + func aString(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) throws + -> String + { + return "" + } - func aUint8List(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) - throws -> FlutterStandardTypedData - { - return FlutterStandardTypedData(bytes: Data()) - } + func aUint8List(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) + throws -> FlutterStandardTypedData + { + return FlutterStandardTypedData(bytes: Data()) + } - func aList(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) throws - -> [Any?] - { - return [] - } + func aList(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) throws + -> [Any?] + { + return [] + } - func aMap(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) throws - -> [String?: Any?] - { - return [:] - } + func aMap(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) throws + -> [String?: Any?] + { + return [:] + } - func anEnum(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) throws - -> ProxyApiTestEnum - { - return ProxyApiTestEnum.one - } + func anEnum(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) throws + -> ProxyApiTestEnum + { + return ProxyApiTestEnum.one + } - func aProxyApi(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) - throws -> ProxyApiSuperClass - { - return ProxyApiSuperClass() - } + func aProxyApi(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) + throws -> ProxyApiSuperClass + { + return ProxyApiSuperClass() + } - func aNullableBool(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) - throws -> Bool? - { - return nil - } + func aNullableBool(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) + throws -> Bool? + { + return nil + } - func aNullableInt(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) - throws -> Int64? - { - return nil - } + func aNullableInt(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) + throws -> Int64? + { + return nil + } - func aNullableDouble(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) - throws -> Double? - { - return nil - } + func aNullableDouble(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) + throws -> Double? + { + return nil + } - func aNullableString(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) - throws -> String? - { - return nil - } + func aNullableString(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) + throws -> String? + { + return nil + } - func aNullableUint8List( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass - ) throws -> FlutterStandardTypedData? { - return nil - } + func aNullableUint8List( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass + ) throws -> FlutterStandardTypedData? { + return nil + } - func aNullableList(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) - throws -> [Any?]? - { - return nil - } + func aNullableList(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) + throws -> [Any?]? + { + return nil + } - func aNullableMap(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) - throws -> [String?: Any?]? - { - return nil - } + func aNullableMap(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) + throws -> [String?: Any?]? + { + return nil + } - func aNullableEnum(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) - throws -> ProxyApiTestEnum? - { - return nil - } + func aNullableEnum(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) + throws -> ProxyApiTestEnum? + { + return nil + } - func aNullableProxyApi( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass - ) throws -> ProxyApiSuperClass? { - return nil - } + func aNullableProxyApi( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass + ) throws -> ProxyApiSuperClass? { + return nil + } - func noop(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) throws { - } + func noop(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) throws { + } - func throwError(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) - throws -> Any? - { - throw ProxyApiTestsError(code: "code", message: "message", details: "details") - } + func throwError(pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass) + throws -> Any? + { + throw ProxyApiTestsError(code: "code", message: "message", details: "details") + } - func throwErrorFromVoid( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass - ) throws { - throw ProxyApiTestsError(code: "code", message: "message", details: "details") - } + func throwErrorFromVoid( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass + ) throws { + throw ProxyApiTestsError(code: "code", message: "message", details: "details") + } - func throwFlutterError( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass - ) throws -> Any? { - throw ProxyApiTestsError(code: "code", message: "message", details: "details") - } + func throwFlutterError( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass + ) throws -> Any? { + throw ProxyApiTestsError(code: "code", message: "message", details: "details") + } - func echoInt( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, anInt: Int64 - ) throws -> Int64 { - return anInt - } + func echoInt( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, anInt: Int64 + ) throws -> Int64 { + return anInt + } - func echoDouble( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aDouble: Double - ) throws -> Double { - return aDouble - } + func echoDouble( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aDouble: Double + ) throws -> Double { + return aDouble + } - func echoBool( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aBool: Bool - ) throws -> Bool { - return aBool - } + func echoBool( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aBool: Bool + ) throws -> Bool { + return aBool + } - func echoString( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aString: String - ) throws -> String { - return aString - } + func echoString( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aString: String + ) throws -> String { + return aString + } - func echoUint8List( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aUint8List: FlutterStandardTypedData - ) throws -> FlutterStandardTypedData { - return aUint8List - } + func echoUint8List( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aUint8List: FlutterStandardTypedData + ) throws -> FlutterStandardTypedData { + return aUint8List + } - func echoObject( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, anObject: Any - ) throws -> Any { - return anObject - } + func echoObject( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, anObject: Any + ) throws -> Any { + return anObject + } - func echoList( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aList: [Any?] - ) throws -> [Any?] { - return aList - } + func echoList( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aList: [Any?] + ) throws -> [Any?] { + return aList + } - func echoProxyApiList( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aList: [ProxyApiTestClass] - ) throws -> [ProxyApiTestClass] { - return aList - } + func echoProxyApiList( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aList: [ProxyApiTestClass] + ) throws -> [ProxyApiTestClass] { + return aList + } - func echoMap( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aMap: [String?: Any?] - ) throws -> [String?: Any?] { - return aMap - } + func echoMap( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aMap: [String?: Any?] + ) throws -> [String?: Any?] { + return aMap + } - func echoProxyApiMap( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aMap: [String: ProxyApiTestClass] - ) throws -> [String: ProxyApiTestClass] { - return aMap - } + func echoProxyApiMap( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aMap: [String: ProxyApiTestClass] + ) throws -> [String: ProxyApiTestClass] { + return aMap + } - func echoEnum( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - anEnum: ProxyApiTestEnum - ) throws -> ProxyApiTestEnum { - return anEnum - } + func echoEnum( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + anEnum: ProxyApiTestEnum + ) throws -> ProxyApiTestEnum { + return anEnum + } - func echoProxyApi( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aProxyApi: ProxyApiSuperClass - ) throws -> ProxyApiSuperClass { - return aProxyApi - } + func echoProxyApi( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aProxyApi: ProxyApiSuperClass + ) throws -> ProxyApiSuperClass { + return aProxyApi + } - func echoNullableInt( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aNullableInt: Int64? - ) throws -> Int64? { - return aNullableInt - } + func echoNullableInt( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aNullableInt: Int64? + ) throws -> Int64? { + return aNullableInt + } - func echoNullableDouble( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aNullableDouble: Double? - ) throws -> Double? { - return aNullableDouble - } + func echoNullableDouble( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aNullableDouble: Double? + ) throws -> Double? { + return aNullableDouble + } - func echoNullableBool( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aNullableBool: Bool? - ) throws -> Bool? { - return aNullableBool - } + func echoNullableBool( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aNullableBool: Bool? + ) throws -> Bool? { + return aNullableBool + } - func echoNullableString( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aNullableString: String? - ) throws -> String? { - return aNullableString - } + func echoNullableString( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aNullableString: String? + ) throws -> String? { + return aNullableString + } - func echoNullableUint8List( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aNullableUint8List: FlutterStandardTypedData? - ) throws -> FlutterStandardTypedData? { - return aNullableUint8List - } + func echoNullableUint8List( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aNullableUint8List: FlutterStandardTypedData? + ) throws -> FlutterStandardTypedData? { + return aNullableUint8List + } - func echoNullableObject( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aNullableObject: Any? - ) throws -> Any? { - return aNullableObject - } + func echoNullableObject( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aNullableObject: Any? + ) throws -> Any? { + return aNullableObject + } - func echoNullableList( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aNullableList: [Any?]? - ) throws -> [Any?]? { - return aNullableList - } + func echoNullableList( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aNullableList: [Any?]? + ) throws -> [Any?]? { + return aNullableList + } - func echoNullableMap( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aNullableMap: [String?: Any?]? - ) throws -> [String?: Any?]? { - return aNullableMap - } + func echoNullableMap( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aNullableMap: [String?: Any?]? + ) throws -> [String?: Any?]? { + return aNullableMap + } - func echoNullableEnum( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aNullableEnum: ProxyApiTestEnum? - ) throws -> ProxyApiTestEnum? { - return aNullableEnum - } + func echoNullableEnum( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aNullableEnum: ProxyApiTestEnum? + ) throws -> ProxyApiTestEnum? { + return aNullableEnum + } - func echoNullableProxyApi( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aNullableProxyApi: ProxyApiSuperClass? - ) throws -> ProxyApiSuperClass? { - return aNullableProxyApi - } + func echoNullableProxyApi( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aNullableProxyApi: ProxyApiSuperClass? + ) throws -> ProxyApiSuperClass? { + return aNullableProxyApi + } - func noopAsync( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - completion: @escaping (Result) -> Void - ) { - completion(.success(Void())) - } + func noopAsync( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + completion: @escaping (Result) -> Void + ) { + completion(.success(Void())) + } - func echoAsyncInt( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, anInt: Int64, - completion: @escaping (Result) -> Void - ) { - completion(.success(anInt)) - } + func echoAsyncInt( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, anInt: Int64, + completion: @escaping (Result) -> Void + ) { + completion(.success(anInt)) + } - func echoAsyncDouble( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aDouble: Double, - completion: @escaping (Result) -> Void - ) { - completion(.success(aDouble)) - } + func echoAsyncDouble( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aDouble: Double, + completion: @escaping (Result) -> Void + ) { + completion(.success(aDouble)) + } - func echoAsyncBool( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aBool: Bool, - completion: @escaping (Result) -> Void - ) { - completion(.success(aBool)) - } + func echoAsyncBool( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aBool: Bool, + completion: @escaping (Result) -> Void + ) { + completion(.success(aBool)) + } - func echoAsyncString( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aString: String, - completion: @escaping (Result) -> Void - ) { - completion(.success(aString)) - } + func echoAsyncString( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aString: String, + completion: @escaping (Result) -> Void + ) { + completion(.success(aString)) + } - func echoAsyncUint8List( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aUint8List: FlutterStandardTypedData, - completion: @escaping (Result) -> Void - ) { - completion(.success(aUint8List)) - } + func echoAsyncUint8List( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aUint8List: FlutterStandardTypedData, + completion: @escaping (Result) -> Void + ) { + completion(.success(aUint8List)) + } - func echoAsyncObject( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, anObject: Any, - completion: @escaping (Result) -> Void - ) { - completion(.success(anObject)) - } + func echoAsyncObject( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, anObject: Any, + completion: @escaping (Result) -> Void + ) { + completion(.success(anObject)) + } - func echoAsyncList( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aList: [Any?], - completion: @escaping (Result<[Any?], Error>) -> Void - ) { - completion(.success(aList)) - } + func echoAsyncList( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aList: [Any?], + completion: @escaping (Result<[Any?], Error>) -> Void + ) { + completion(.success(aList)) + } - func echoAsyncMap( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aMap: [String?: Any?], completion: @escaping (Result<[String?: Any?], Error>) -> Void - ) { - completion(.success(aMap)) - } + func echoAsyncMap( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aMap: [String?: Any?], completion: @escaping (Result<[String?: Any?], Error>) -> Void + ) { + completion(.success(aMap)) + } - func echoAsyncEnum( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - anEnum: ProxyApiTestEnum, completion: @escaping (Result) -> Void - ) { - completion(.success(anEnum)) - } + func echoAsyncEnum( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + anEnum: ProxyApiTestEnum, completion: @escaping (Result) -> Void + ) { + completion(.success(anEnum)) + } - func throwAsyncError( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - completion: @escaping (Result) -> Void - ) { - completion( - .failure(ProxyApiTestsError(code: "code", message: "message", details: "details"))) - } + func throwAsyncError( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + completion: @escaping (Result) -> Void + ) { + completion( + .failure(ProxyApiTestsError(code: "code", message: "message", details: "details"))) + } - func throwAsyncErrorFromVoid( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - completion: @escaping (Result) -> Void - ) { - completion( - .failure(ProxyApiTestsError(code: "code", message: "message", details: "details"))) - } + func throwAsyncErrorFromVoid( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + completion: @escaping (Result) -> Void + ) { + completion( + .failure(ProxyApiTestsError(code: "code", message: "message", details: "details"))) + } - func throwAsyncFlutterError( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - completion: @escaping (Result) -> Void - ) { - completion( - .failure(ProxyApiTestsError(code: "code", message: "message", details: "details"))) - } + func throwAsyncFlutterError( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + completion: @escaping (Result) -> Void + ) { + completion( + .failure(ProxyApiTestsError(code: "code", message: "message", details: "details"))) + } - func echoAsyncNullableInt( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, anInt: Int64?, - completion: @escaping (Result) -> Void - ) { - completion(.success(anInt)) - } + func echoAsyncNullableInt( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, anInt: Int64?, + completion: @escaping (Result) -> Void + ) { + completion(.success(anInt)) + } - func echoAsyncNullableDouble( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aDouble: Double?, - completion: @escaping (Result) -> Void - ) { - completion(.success(aDouble)) - } + func echoAsyncNullableDouble( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aDouble: Double?, + completion: @escaping (Result) -> Void + ) { + completion(.success(aDouble)) + } - func echoAsyncNullableBool( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aBool: Bool?, - completion: @escaping (Result) -> Void - ) { - completion(.success(aBool)) - } + func echoAsyncNullableBool( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aBool: Bool?, + completion: @escaping (Result) -> Void + ) { + completion(.success(aBool)) + } - func echoAsyncNullableString( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aString: String?, - completion: @escaping (Result) -> Void - ) { - completion(.success(aString)) - } + func echoAsyncNullableString( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aString: String?, + completion: @escaping (Result) -> Void + ) { + completion(.success(aString)) + } - func echoAsyncNullableUint8List( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aUint8List: FlutterStandardTypedData?, - completion: @escaping (Result) -> Void - ) { - completion(.success(aUint8List)) - } + func echoAsyncNullableUint8List( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aUint8List: FlutterStandardTypedData?, + completion: @escaping (Result) -> Void + ) { + completion(.success(aUint8List)) + } - func echoAsyncNullableObject( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, anObject: Any?, - completion: @escaping (Result) -> Void - ) { - completion(.success(anObject)) - } + func echoAsyncNullableObject( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, anObject: Any?, + completion: @escaping (Result) -> Void + ) { + completion(.success(anObject)) + } - func echoAsyncNullableList( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aList: [Any?]?, - completion: @escaping (Result<[Any?]?, Error>) -> Void - ) { - completion(.success(aList)) - } + func echoAsyncNullableList( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aList: [Any?]?, + completion: @escaping (Result<[Any?]?, Error>) -> Void + ) { + completion(.success(aList)) + } - func echoAsyncNullableMap( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aMap: [String?: Any?]?, completion: @escaping (Result<[String?: Any?]?, Error>) -> Void - ) { - completion(.success(aMap)) - } + func echoAsyncNullableMap( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aMap: [String?: Any?]?, completion: @escaping (Result<[String?: Any?]?, Error>) -> Void + ) { + completion(.success(aMap)) + } - func echoAsyncNullableEnum( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - anEnum: ProxyApiTestEnum?, completion: @escaping (Result) -> Void - ) { - completion(.success(anEnum)) - } + func echoAsyncNullableEnum( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + anEnum: ProxyApiTestEnum?, completion: @escaping (Result) -> Void + ) { + completion(.success(anEnum)) + } - func staticNoop(pigeonApi: PigeonApiProxyApiTestClass) throws { + func staticNoop(pigeonApi: PigeonApiProxyApiTestClass) throws { - } + } - func echoStaticString(pigeonApi: PigeonApiProxyApiTestClass, aString: String) throws -> String - { - return aString - } + func echoStaticString(pigeonApi: PigeonApiProxyApiTestClass, aString: String) throws -> String { + return aString + } + + func staticAsyncNoop( + pigeonApi: PigeonApiProxyApiTestClass, completion: @escaping (Result) -> Void + ) { + completion(.success(Void())) + } - func staticAsyncNoop( - pigeonApi: PigeonApiProxyApiTestClass, completion: @escaping (Result) -> Void - ) { - completion(.success(Void())) + func callFlutterNoop( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + completion: @escaping (Result) -> Void + ) { + pigeonApi.flutterNoop(pigeonInstance: pigeonInstance) { response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterNoop( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - completion: @escaping (Result) -> Void - ) { - pigeonApi.flutterNoop(pigeonInstance: pigeonInstance) { response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterThrowError( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + completion: @escaping (Result) -> Void + ) { + pigeonApi.flutterThrowError(pigeonInstance: pigeonInstance) { response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterThrowError( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - completion: @escaping (Result) -> Void - ) { - pigeonApi.flutterThrowError(pigeonInstance: pigeonInstance) { response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterThrowErrorFromVoid( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + completion: @escaping (Result) -> Void + ) { + pigeonApi.flutterThrowErrorFromVoid(pigeonInstance: pigeonInstance) { response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterThrowErrorFromVoid( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - completion: @escaping (Result) -> Void - ) { - pigeonApi.flutterThrowErrorFromVoid(pigeonInstance: pigeonInstance) { response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterEchoBool( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aBool: Bool, + completion: @escaping (Result) -> Void + ) { + pigeonApi.flutterEchoBool(pigeonInstance: pigeonInstance, aBool: aBool) { response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterEchoBool( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aBool: Bool, - completion: @escaping (Result) -> Void - ) { - pigeonApi.flutterEchoBool(pigeonInstance: pigeonInstance, aBool: aBool) { response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterEchoInt( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, anInt: Int64, + completion: @escaping (Result) -> Void + ) { + pigeonApi.flutterEchoInt(pigeonInstance: pigeonInstance, anInt: anInt) { response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterEchoInt( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, anInt: Int64, - completion: @escaping (Result) -> Void - ) { - pigeonApi.flutterEchoInt(pigeonInstance: pigeonInstance, anInt: anInt) { response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterEchoDouble( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aDouble: Double, + completion: @escaping (Result) -> Void + ) { + pigeonApi.flutterEchoDouble(pigeonInstance: pigeonInstance, aDouble: aDouble) { response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterEchoDouble( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aDouble: Double, - completion: @escaping (Result) -> Void - ) { - pigeonApi.flutterEchoDouble(pigeonInstance: pigeonInstance, aDouble: aDouble) { response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterEchoString( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aString: String, + completion: @escaping (Result) -> Void + ) { + pigeonApi.flutterEchoString(pigeonInstance: pigeonInstance, aString: aString) { response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterEchoString( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aString: String, - completion: @escaping (Result) -> Void - ) { - pigeonApi.flutterEchoString(pigeonInstance: pigeonInstance, aString: aString) { response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterEchoUint8List( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aUint8List: FlutterStandardTypedData, + completion: @escaping (Result) -> Void + ) { + pigeonApi.flutterEchoUint8List(pigeonInstance: pigeonInstance, aList: aUint8List) { + response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterEchoUint8List( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aUint8List: FlutterStandardTypedData, - completion: @escaping (Result) -> Void - ) { - pigeonApi.flutterEchoUint8List(pigeonInstance: pigeonInstance, aList: aUint8List) { - response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterEchoList( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aList: [Any?], + completion: @escaping (Result<[Any?], Error>) -> Void + ) { + pigeonApi.flutterEchoList(pigeonInstance: pigeonInstance, aList: aList) { response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterEchoList( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aList: [Any?], - completion: @escaping (Result<[Any?], Error>) -> Void - ) { - pigeonApi.flutterEchoList(pigeonInstance: pigeonInstance, aList: aList) { response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterEchoProxyApiList( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aList: [ProxyApiTestClass?], + completion: @escaping (Result<[ProxyApiTestClass?], Error>) -> Void + ) { + pigeonApi.flutterEchoProxyApiList(pigeonInstance: pigeonInstance, aList: aList) { + response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterEchoProxyApiList( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aList: [ProxyApiTestClass?], - completion: @escaping (Result<[ProxyApiTestClass?], Error>) -> Void - ) { - pigeonApi.flutterEchoProxyApiList(pigeonInstance: pigeonInstance, aList: aList) { - response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterEchoMap( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aMap: [String?: Any?], completion: @escaping (Result<[String?: Any?], Error>) -> Void + ) { + pigeonApi.flutterEchoMap(pigeonInstance: pigeonInstance, aMap: aMap) { response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterEchoMap( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aMap: [String?: Any?], completion: @escaping (Result<[String?: Any?], Error>) -> Void - ) { - pigeonApi.flutterEchoMap(pigeonInstance: pigeonInstance, aMap: aMap) { response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterEchoProxyApiMap( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aMap: [String?: ProxyApiTestClass?], + completion: @escaping (Result<[String?: ProxyApiTestClass?], Error>) -> Void + ) { + pigeonApi.flutterEchoProxyApiMap(pigeonInstance: pigeonInstance, aMap: aMap) { response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterEchoProxyApiMap( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aMap: [String?: ProxyApiTestClass?], - completion: @escaping (Result<[String?: ProxyApiTestClass?], Error>) -> Void - ) { - pigeonApi.flutterEchoProxyApiMap(pigeonInstance: pigeonInstance, aMap: aMap) { response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterEchoEnum( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + anEnum: ProxyApiTestEnum, completion: @escaping (Result) -> Void + ) { + pigeonApi.flutterEchoEnum(pigeonInstance: pigeonInstance, anEnum: anEnum) { response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterEchoEnum( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - anEnum: ProxyApiTestEnum, completion: @escaping (Result) -> Void - ) { - pigeonApi.flutterEchoEnum(pigeonInstance: pigeonInstance, anEnum: anEnum) { response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterEchoProxyApi( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aProxyApi: ProxyApiSuperClass, + completion: @escaping (Result) -> Void + ) { + pigeonApi.flutterEchoProxyApi(pigeonInstance: pigeonInstance, aProxyApi: aProxyApi) { + response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterEchoProxyApi( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aProxyApi: ProxyApiSuperClass, - completion: @escaping (Result) -> Void - ) { - pigeonApi.flutterEchoProxyApi(pigeonInstance: pigeonInstance, aProxyApi: aProxyApi) { - response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterEchoNullableBool( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aBool: Bool?, + completion: @escaping (Result) -> Void + ) { + pigeonApi.flutterEchoNullableBool(pigeonInstance: pigeonInstance, aBool: aBool) { + response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterEchoNullableBool( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aBool: Bool?, - completion: @escaping (Result) -> Void - ) { - pigeonApi.flutterEchoNullableBool(pigeonInstance: pigeonInstance, aBool: aBool) { - response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterEchoNullableInt( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, anInt: Int64?, + completion: @escaping (Result) -> Void + ) { + pigeonApi.flutterEchoNullableInt(pigeonInstance: pigeonInstance, anInt: anInt) { response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterEchoNullableInt( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, anInt: Int64?, - completion: @escaping (Result) -> Void - ) { - pigeonApi.flutterEchoNullableInt(pigeonInstance: pigeonInstance, anInt: anInt) { response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterEchoNullableDouble( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aDouble: Double?, + completion: @escaping (Result) -> Void + ) { + pigeonApi.flutterEchoNullableDouble(pigeonInstance: pigeonInstance, aDouble: aDouble) { + response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterEchoNullableDouble( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aDouble: Double?, - completion: @escaping (Result) -> Void - ) { - pigeonApi.flutterEchoNullableDouble(pigeonInstance: pigeonInstance, aDouble: aDouble) { - response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterEchoNullableString( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aString: String?, + completion: @escaping (Result) -> Void + ) { + pigeonApi.flutterEchoNullableString(pigeonInstance: pigeonInstance, aString: aString) { + response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterEchoNullableString( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aString: String?, - completion: @escaping (Result) -> Void - ) { - pigeonApi.flutterEchoNullableString(pigeonInstance: pigeonInstance, aString: aString) { - response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterEchoNullableUint8List( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aUint8List: FlutterStandardTypedData?, + completion: @escaping (Result) -> Void + ) { + pigeonApi.flutterEchoNullableUint8List(pigeonInstance: pigeonInstance, aList: aUint8List) { + response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterEchoNullableUint8List( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aUint8List: FlutterStandardTypedData?, - completion: @escaping (Result) -> Void - ) { - pigeonApi.flutterEchoNullableUint8List(pigeonInstance: pigeonInstance, aList: aUint8List) { - response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterEchoNullableList( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aList: [Any?]?, + completion: @escaping (Result<[Any?]?, Error>) -> Void + ) { + pigeonApi.flutterEchoNullableList(pigeonInstance: pigeonInstance, aList: aList) { + response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterEchoNullableList( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aList: [Any?]?, - completion: @escaping (Result<[Any?]?, Error>) -> Void - ) { - pigeonApi.flutterEchoNullableList(pigeonInstance: pigeonInstance, aList: aList) { - response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterEchoNullableMap( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aMap: [String?: Any?]?, completion: @escaping (Result<[String?: Any?]?, Error>) -> Void + ) { + pigeonApi.flutterEchoNullableMap(pigeonInstance: pigeonInstance, aMap: aMap) { response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterEchoNullableMap( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aMap: [String?: Any?]?, completion: @escaping (Result<[String?: Any?]?, Error>) -> Void - ) { - pigeonApi.flutterEchoNullableMap(pigeonInstance: pigeonInstance, aMap: aMap) { response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterEchoNullableEnum( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + anEnum: ProxyApiTestEnum?, completion: @escaping (Result) -> Void + ) { + pigeonApi.flutterEchoNullableEnum(pigeonInstance: pigeonInstance, anEnum: anEnum) { + response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterEchoNullableEnum( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - anEnum: ProxyApiTestEnum?, completion: @escaping (Result) -> Void - ) { - pigeonApi.flutterEchoNullableEnum(pigeonInstance: pigeonInstance, anEnum: anEnum) { - response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterEchoNullableProxyApi( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + aProxyApi: ProxyApiSuperClass?, + completion: @escaping (Result) -> Void + ) { + pigeonApi.flutterEchoNullableProxyApi(pigeonInstance: pigeonInstance, aProxyApi: aProxyApi) { + response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterEchoNullableProxyApi( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - aProxyApi: ProxyApiSuperClass?, - completion: @escaping (Result) -> Void - ) { - pigeonApi.flutterEchoNullableProxyApi(pigeonInstance: pigeonInstance, aProxyApi: aProxyApi) - { response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterNoopAsync( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, + completion: @escaping (Result) -> Void + ) { + pigeonApi.flutterNoopAsync(pigeonInstance: pigeonInstance) { response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterNoopAsync( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, - completion: @escaping (Result) -> Void - ) { - pigeonApi.flutterNoopAsync(pigeonInstance: pigeonInstance) { response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } + func callFlutterEchoAsyncString( + pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aString: String, + completion: @escaping (Result) -> Void + ) { + pigeonApi.flutterEchoAsyncString(pigeonInstance: pigeonInstance, aString: aString) { + response in + switch response { + case .success(let res): + completion(.success(res)) + case .failure(let error): + completion(.failure(error)) } + } + } - func callFlutterEchoAsyncString( - pigeonApi: PigeonApiProxyApiTestClass, pigeonInstance: ProxyApiTestClass, aString: String, - completion: @escaping (Result) -> Void - ) { - pigeonApi.flutterEchoAsyncString(pigeonInstance: pigeonInstance, aString: aString) { - response in - switch response { - case .success(let res): - completion(.success(res)) - case .failure(let error): - completion(.failure(error)) - } - } - } +} - } +class ProxyApiDelegate: ProxyApiTestsPigeonProxyApiDelegate { + func pigeonApiProxyApiTestClass(_ registrar: ProxyApiTestsPigeonProxyApiRegistrar) + -> PigeonApiProxyApiTestClass + { return PigeonApiProxyApiTestClass( pigeonRegistrar: registrar, delegate: ProxyApiTestClassDelegate()) } diff --git a/packages/pigeon/platform_tests/test_plugin/example/android/settings.gradle b/packages/pigeon/platform_tests/test_plugin/example/android/settings.gradle index 7be5709da0ca..b83203f03197 100644 --- a/packages/pigeon/platform_tests/test_plugin/example/android/settings.gradle +++ b/packages/pigeon/platform_tests/test_plugin/example/android/settings.gradle @@ -18,10 +18,10 @@ 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.11.0" apply false - id "org.jetbrains.kotlin.android" version "2.2.0" apply false - id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1" + id "dev.flutter.flutter-plugin-loader" version "1.0.0" + id "com.android.application" version "8.11.1" apply false + id "org.jetbrains.kotlin.android" version "2.2.20" apply false + id "com.google.cloud.artifactregistry.gradle-plugin" version "2.2.1" } include ":app" diff --git a/packages/pigeon/platform_tests/test_plugin/example/ios/Flutter/AppFrameworkInfo.plist b/packages/pigeon/platform_tests/test_plugin/example/ios/Flutter/AppFrameworkInfo.plist index 7c5696400627..391a902b2beb 100644 --- a/packages/pigeon/platform_tests/test_plugin/example/ios/Flutter/AppFrameworkInfo.plist +++ b/packages/pigeon/platform_tests/test_plugin/example/ios/Flutter/AppFrameworkInfo.plist @@ -20,7 +20,5 @@ ???? CFBundleVersion 1.0 - MinimumOSVersion - 12.0 diff --git a/packages/pigeon/platform_tests/test_plugin/example/ios/Flutter/Debug.xcconfig b/packages/pigeon/platform_tests/test_plugin/example/ios/Flutter/Debug.xcconfig index ec97fc6f3021..592ceee85b89 100644 --- a/packages/pigeon/platform_tests/test_plugin/example/ios/Flutter/Debug.xcconfig +++ b/packages/pigeon/platform_tests/test_plugin/example/ios/Flutter/Debug.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" diff --git a/packages/pigeon/platform_tests/test_plugin/example/ios/Flutter/Release.xcconfig b/packages/pigeon/platform_tests/test_plugin/example/ios/Flutter/Release.xcconfig index c4855bfe2000..592ceee85b89 100644 --- a/packages/pigeon/platform_tests/test_plugin/example/ios/Flutter/Release.xcconfig +++ b/packages/pigeon/platform_tests/test_plugin/example/ios/Flutter/Release.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" diff --git a/packages/pigeon/platform_tests/test_plugin/example/ios/Podfile b/packages/pigeon/platform_tests/test_plugin/example/ios/Podfile deleted file mode 100644 index 6f5730c5fed8..000000000000 --- a/packages/pigeon/platform_tests/test_plugin/example/ios/Podfile +++ /dev/null @@ -1,48 +0,0 @@ -# Uncomment this line to define a global platform for your project -# platform :ios, '12.0' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_ios_podfile_setup - -target 'Runner' do - use_frameworks! - - flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) - - target 'RunnerTests' do - inherit! :search_paths - end -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_ios_build_settings(target) - - target.build_configurations.each do |config| - config.build_settings['SWIFT_TREAT_WARNINGS_AS_ERRORS'] = 'YES' - end - end -end diff --git a/packages/pigeon/platform_tests/test_plugin/example/ios/Runner.xcodeproj/project.pbxproj b/packages/pigeon/platform_tests/test_plugin/example/ios/Runner.xcodeproj/project.pbxproj index 576c8070408d..1c93e5bc05f0 100644 --- a/packages/pigeon/platform_tests/test_plugin/example/ios/Runner.xcodeproj/project.pbxproj +++ b/packages/pigeon/platform_tests/test_plugin/example/ios/Runner.xcodeproj/project.pbxproj @@ -8,7 +8,6 @@ /* Begin PBXBuildFile section */ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; - 1A110B6716B0F8542A6A18D1 /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BC37C4E8AE005B445F208C02 /* Pods_RunnerTests.framework */; }; 33A341B8291ECCA100D34E0F /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33A341B7291ECCA100D34E0F /* RunnerTests.swift */; }; 33A341CB291ECDFD00D34E0F /* MultipleArityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33A341BF291ECDFD00D34E0F /* MultipleArityTests.swift */; }; 33A341CC291ECDFD00D34E0F /* AllDatatypesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33A341C0291ECDFD00D34E0F /* AllDatatypesTests.swift */; }; @@ -23,7 +22,6 @@ 33A341D5291ECDFD00D34E0F /* AsyncHandlersTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33A341C9291ECDFD00D34E0F /* AsyncHandlersTest.swift */; }; 33A341D6291ECDFD00D34E0F /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33A341CA291ECDFD00D34E0F /* Utils.swift */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; - 6885ADFFF3D912887C317B7C /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 786308B4AA81D1B6AA2FA10F /* Pods_Runner.framework */; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; 8F85C49D2BBB14F30053FB60 /* InstanceManagerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F85C49C2BBB14F30053FB60 /* InstanceManagerTests.swift */; }; @@ -31,6 +29,7 @@ 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; E04641FA2A46270400661C9E /* NSNullFieldTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E04641F92A46270400661C9E /* NSNullFieldTests.swift */; }; + F750BDEE2F28844900E3DB39 /* ProxyApiTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F750BDED2F28844900E3DB39 /* ProxyApiTests.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -57,7 +56,6 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 1003C19F4B2A0DDD9763A1E4 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; 33A341B5291ECCA100D34E0F /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -75,11 +73,11 @@ 33A341C9291ECDFD00D34E0F /* AsyncHandlersTest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AsyncHandlersTest.swift; sourceTree = ""; }; 33A341CA291ECDFD00D34E0F /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = ""; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; - 407DC1E57B864B3AC2D1D534 /* 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 = ""; }; - 4E640DBB26024C85BF85408E /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; - 786308B4AA81D1B6AA2FA10F /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 784666492D4C4C64000A1A5F /* FlutterFramework */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterFramework; path = Flutter/ephemeral/Packages/.packages/FlutterFramework; sourceTree = ""; }; + 78DABEA22ED26510000E7860 /* test_plugin */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = test_plugin; path = ../../darwin/test_plugin; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; 8F85C49C2BBB14F30053FB60 /* InstanceManagerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InstanceManagerTests.swift; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; @@ -89,11 +87,8 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 9808B6775522250A40D7D452 /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; - BC37C4E8AE005B445F208C02 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - BF5B776B52F984FB430C15A3 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; E04641F92A46270400661C9E /* NSNullFieldTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NSNullFieldTests.swift; sourceTree = ""; }; - EB04430DB6D43CCC08FA526B /* 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 = ""; }; + F750BDED2F28844900E3DB39 /* ProxyApiTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProxyApiTests.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -101,7 +96,6 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 1A110B6716B0F8542A6A18D1 /* Pods_RunnerTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -110,7 +104,6 @@ buildActionMask = 2147483647; files = ( 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, - 6885ADFFF3D912887C317B7C /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -131,6 +124,7 @@ 33A341C3291ECDFD00D34E0F /* NonNullFieldsTest.swift */, 33A341C6291ECDFD00D34E0F /* NullableReturnsTests.swift */, 33A341C7291ECDFD00D34E0F /* PrimitiveTests.swift */, + F750BDED2F28844900E3DB39 /* ProxyApiTests.swift */, 33A341B7291ECCA100D34E0F /* RunnerTests.swift */, E04641F92A46270400661C9E /* NSNullFieldTests.swift */, 33A341CA291ECDFD00D34E0F /* Utils.swift */, @@ -142,28 +136,16 @@ 388F17C8A0325528A352A807 /* Pods */ = { isa = PBXGroup; children = ( - 1003C19F4B2A0DDD9763A1E4 /* Pods-Runner.debug.xcconfig */, - 4E640DBB26024C85BF85408E /* Pods-Runner.release.xcconfig */, - BF5B776B52F984FB430C15A3 /* Pods-Runner.profile.xcconfig */, - EB04430DB6D43CCC08FA526B /* Pods-RunnerTests.debug.xcconfig */, - 407DC1E57B864B3AC2D1D534 /* Pods-RunnerTests.release.xcconfig */, - 9808B6775522250A40D7D452 /* Pods-RunnerTests.profile.xcconfig */, ); path = Pods; sourceTree = ""; }; - 8060760051E07AE47C40F036 /* Frameworks */ = { - isa = PBXGroup; - children = ( - 786308B4AA81D1B6AA2FA10F /* Pods_Runner.framework */, - BC37C4E8AE005B445F208C02 /* Pods_RunnerTests.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( + 78DABEA22ED26510000E7860 /* test_plugin */, + 784666492D4C4C64000A1A5F /* FlutterFramework */, + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, 9740EEB21CF90195004384FC /* Debug.xcconfig */, 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, @@ -180,7 +162,6 @@ 33A341B6291ECCA100D34E0F /* RunnerTests */, 97C146EF1CF9000F007C117D /* Products */, 388F17C8A0325528A352A807 /* Pods */, - 8060760051E07AE47C40F036 /* Frameworks */, ); sourceTree = ""; }; @@ -215,7 +196,6 @@ isa = PBXNativeTarget; buildConfigurationList = 33A341BE291ECCA100D34E0F /* Build configuration list for PBXNativeTarget "RunnerTests" */; buildPhases = ( - 68071F6E376CAAF900FEFD29 /* [CP] Check Pods Manifest.lock */, 33A341B1291ECCA100D34E0F /* Sources */, 33A341B2291ECCA100D34E0F /* Frameworks */, 33A341B3291ECCA100D34E0F /* Resources */, @@ -234,7 +214,6 @@ isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - 7E33641B55112906F49CAB0C /* [CP] Check Pods Manifest.lock */, 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, @@ -334,50 +313,6 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; }; - 68071F6E376CAAF900FEFD29 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - 7E33641B55112906F49CAB0C /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; 9740EEB61CF901F6004384FC /* Run Script */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; @@ -413,6 +348,7 @@ E04641FA2A46270400661C9E /* NSNullFieldTests.swift in Sources */, 33A341D1291ECDFD00D34E0F /* MockBinaryMessenger.swift in Sources */, 33A341CF291ECDFD00D34E0F /* NonNullFieldsTest.swift in Sources */, + F750BDEE2F28844900E3DB39 /* ProxyApiTests.swift in Sources */, 33A341CB291ECDFD00D34E0F /* MultipleArityTests.swift in Sources */, 33A341CC291ECDFD00D34E0F /* AllDatatypesTests.swift in Sources */, ); @@ -498,7 +434,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -530,7 +466,6 @@ }; 33A341BB291ECCA100D34E0F /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = EB04430DB6D43CCC08FA526B /* Pods-RunnerTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; @@ -541,14 +476,13 @@ SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_TREAT_WARNINGS_AS_ERRORS = YES; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 6.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; }; name = Debug; }; 33A341BC291ECCA100D34E0F /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 407DC1E57B864B3AC2D1D534 /* Pods-RunnerTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; @@ -557,14 +491,13 @@ PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_TREAT_WARNINGS_AS_ERRORS = YES; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 6.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; }; name = Release; }; 33A341BD291ECCA100D34E0F /* Profile */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 9808B6775522250A40D7D452 /* Pods-RunnerTests.profile.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; @@ -573,7 +506,7 @@ PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_TREAT_WARNINGS_AS_ERRORS = YES; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 6.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; }; name = Profile; @@ -625,7 +558,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -674,7 +607,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; diff --git a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/AllDatatypesTests.swift b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/AllDatatypesTests.swift index 4002c2349fdf..e855f673fd29 100644 --- a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/AllDatatypesTests.swift +++ b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/AllDatatypesTests.swift @@ -3,34 +3,34 @@ // found in the LICENSE file. import Flutter -import XCTest +import Testing @testable import test_plugin -class AllDatatypesTests: XCTestCase { +@MainActor +struct AllDatatypesTests { - func testAllNull() throws { + @Test + func allNull() async throws { let everything = AllNullableTypes() let binaryMessenger = EchoBinaryMessenger(codec: CoreTestsPigeonCodec.shared) let api = FlutterIntegrationCoreApi(binaryMessenger: binaryMessenger) - let expectation = XCTestExpectation(description: "callback") - - api.echoNullable(everything) { result in - switch result { - case .success(let res): - XCTAssert(everything == res!) - expectation.fulfill() - case .failure(_): - return - + await confirmation { confirmed in + api.echoNullable(everything) { result in + switch result { + case .success(let res): + #expect(everything == res) + confirmed() + case .failure(let error): + Issue.record("Failed with error: \(error)") + } } } - - wait(for: [expectation], timeout: 1.0) } - func testAllEquals() throws { + @Test + func allEquals() async throws { let everything = AllNullableTypes( aNullableBool: true, aNullableInt: 1, @@ -59,19 +59,17 @@ class AllDatatypesTests: XCTestCase { let binaryMessenger = EchoBinaryMessenger(codec: CoreTestsPigeonCodec.shared) let api = FlutterIntegrationCoreApi(binaryMessenger: binaryMessenger) - let expectation = XCTestExpectation(description: "callback") - - api.echoNullable(everything) { res in - switch res { - case .success(let res): - XCTAssert(everything == res!) - expectation.fulfill() - return - case .failure(_): - return + await confirmation { confirmed in + api.echoNullable(everything) { res in + switch res { + case .success(let res): + #expect(everything == res) + confirmed() + case .failure(let error): + Issue.record("Failed with error: \(error)") + } } } - wait(for: [expectation], timeout: 1.0) } private let correctList: [Any?] = ["a", 2, "three"] @@ -83,98 +81,247 @@ class AllDatatypesTests: XCTestCase { private let differentKeyMap: [AnyHashable: Any?] = ["a": 1, "b": 2, "d": "three"] private let differentValueMap: [AnyHashable: Any?] = ["a": 1, "b": 2, "c": "five"] - private lazy var correctListInMap: [AnyHashable: Any?] = ["a": 1, "b": 2, "c": correctList] - private lazy var matchingListInMap: [AnyHashable: Any?] = ["a": 1, "b": 2, "c": matchingList] - private lazy var differentListInMap: [AnyHashable: Any?] = ["a": 1, "b": 2, "c": differentList] + private var correctListInMap: [AnyHashable: Any?] { ["a": 1, "b": 2, "c": correctList] } + private var matchingListInMap: [AnyHashable: Any?] { ["a": 1, "b": 2, "c": matchingList] } + private var differentListInMap: [AnyHashable: Any?] { ["a": 1, "b": 2, "c": differentList] } - private lazy var correctMapInList: [Any?] = ["a", 2, correctMap] - private lazy var matchingMapInList: [Any?] = ["a", 2, matchingMap] - private lazy var differentKeyMapInList: [Any?] = ["a", 2, differentKeyMap] - private lazy var differentValueMapInList: [Any?] = ["a", 2, differentValueMap] + private var correctMapInList: [Any?] { ["a", 2, correctMap] } + private var matchingMapInList: [Any?] { ["a", 2, matchingMap] } + private var differentKeyMapInList: [Any?] { ["a", 2, differentKeyMap] } + private var differentValueMapInList: [Any?] { ["a", 2, differentValueMap] } - func testEqualityMethodCorrectlyChecksDeepEquality() { + @Test + func equalityMethodCorrectlyChecksDeepEquality() { let generic = AllNullableTypes(list: correctList, map: correctMap) let identical = generic - XCTAssertEqual(generic, identical, "Identical copies should be equal") + #expect(generic == identical, "Identical copies should be equal") } - func testEqualityMethodCorrectlyIdentifiesNonMatchingClasses() { + @Test + func equalityMethodCorrectlyIdentifiesNonMatchingClasses() { let generic = AllNullableTypes(list: correctList, map: correctMap) let allNull = AllNullableTypes() - XCTAssertNotEqual( - allNull, generic, "Instance with nil properties should not equal instance with values") + #expect( + allNull != generic, "Instance with nil properties should not equal instance with values") } - func testEqualityMethodCorrectlyIdentifiesNonMatchingListsInClasses() { + @Test + func equalityMethodCorrectlyIdentifiesNonMatchingListsInClasses() { let withList = AllNullableTypes(list: correctList) let withDifferentList = AllNullableTypes(list: differentList) - XCTAssertNotEqual( - withList, withDifferentList, "Instances with different lists should not be equal") + #expect( + withList != withDifferentList, "Instances with different lists should not be equal") } - func testEqualityMethodCorrectlyIdentifiesMatchingButUniqueListsInClasses() { + @Test + func equalityMethodCorrectlyIdentifiesMatchingButUniqueListsInClasses() { let withList = AllNullableTypes(list: correctList) let withMatchingList = AllNullableTypes(list: matchingList) - XCTAssertEqual(withList, withMatchingList, "Instances with equivalent lists should be equal") + #expect(withList == withMatchingList, "Instances with equivalent lists should be equal") } - func testEqualityMethodCorrectlyIdentifiesNonMatchingKeysInMapsInClasses() { + @Test + func equalityMethodCorrectlyIdentifiesNonMatchingKeysInMapsInClasses() { let withMap = AllNullableTypes(map: correctMap) let withDifferentMap = AllNullableTypes(map: differentKeyMap) - XCTAssertNotEqual( - withMap, withDifferentMap, "Instances with different map keys should not be equal") + #expect( + withMap != withDifferentMap, "Instances with different map keys should not be equal") } - func testEqualityMethodCorrectlyIdentifiesNonMatchingValuesInMapsInClasses() { + @Test + func equalityMethodCorrectlyIdentifiesNonMatchingValuesInMapsInClasses() { let withMap = AllNullableTypes(map: correctMap) let withDifferentMap = AllNullableTypes(map: differentValueMap) - XCTAssertNotEqual( - withMap, withDifferentMap, "Instances with different map values should not be equal") + #expect( + withMap != withDifferentMap, "Instances with different map values should not be equal") } - func testEqualityMethodCorrectlyIdentifiesMatchingButUniqueMapsInClasses() { + @Test + func equalityMethodCorrectlyIdentifiesMatchingButUniqueMapsInClasses() { let withMap = AllNullableTypes(map: correctMap) let withMatchingMap = AllNullableTypes(map: matchingMap) - XCTAssertEqual(withMap, withMatchingMap, "Instances with equivalent maps should be equal") + #expect(withMap == withMatchingMap, "Instances with equivalent maps should be equal") } - func testEqualityMethodCorrectlyIdentifiesNonMatchingListsNestedInMapsInClasses() { + @Test + func equalityMethodCorrectlyIdentifiesNonMatchingListsNestedInMapsInClasses() { let withListInMap = AllNullableTypes(map: correctListInMap) let withDifferentListInMap = AllNullableTypes(map: differentListInMap) - XCTAssertNotEqual( - withListInMap, withDifferentListInMap, + #expect( + withListInMap != withDifferentListInMap, "Instances with different nested lists in maps should not be equal") } - func testEqualityMethodCorrectlyIdentifiesMatchingButUniqueListsNestedInMapsInClasses() { + @Test + func equalityMethodCorrectlyIdentifiesMatchingButUniqueListsNestedInMapsInClasses() { let withListInMap = AllNullableTypes(map: correctListInMap) let withMatchingListInMap = AllNullableTypes(map: matchingListInMap) - XCTAssertEqual( - withListInMap, withMatchingListInMap, + #expect( + withListInMap == withMatchingListInMap, "Instances with equivalent nested lists in maps should be equal") } - func testEqualityMethodCorrectlyIdentifiesNonMatchingKeysInMapsNestedInListsInClasses() { + @Test + func equalityMethodCorrectlyIdentifiesNonMatchingKeysInMapsNestedInListsInClasses() { let withMapInList = AllNullableTypes(list: correctMapInList) let withDifferentMapInList = AllNullableTypes(list: differentKeyMapInList) - XCTAssertNotEqual( - withMapInList, withDifferentMapInList, + #expect( + withMapInList != withDifferentMapInList, "Instances with different nested map keys in lists should not be equal") } - func testEqualityMethodCorrectlyIdentifiesNonMatchingValuesInMapsNestedInListsInClasses() { + @Test + func equalityMethodCorrectlyIdentifiesNonMatchingValuesInMapsNestedInListsInClasses() { let withMapInList = AllNullableTypes(list: correctMapInList) let withDifferentMapInList = AllNullableTypes(list: differentValueMapInList) - XCTAssertNotEqual( - withMapInList, withDifferentMapInList, + #expect( + withMapInList != withDifferentMapInList, "Instances with different nested map values in lists should not be equal") } - func testEqualityMethodCorrectlyIdentifiesMatchingButUniqueMapsNestedInListsInClasses() { + @Test + func equalityMethodCorrectlyIdentifiesMatchingButUniqueMapsNestedInListsInClasses() { let withMapInList = AllNullableTypes(list: correctMapInList) let withMatchingMapInList = AllNullableTypes(list: matchingMapInList) - XCTAssertEqual( - withMapInList, withMatchingMapInList, + #expect( + withMapInList == withMatchingMapInList, "Instances with equivalent nested maps in lists should be equal") } + + @Test + func equalityWithNaN() throws { + let list = [Double.nan] + let map: [Int64: Double?] = [1: Double.nan] + let a = AllNullableTypes( + aNullableDouble: Double.nan, + doubleList: list, + recursiveClassList: [AllNullableTypes(aNullableDouble: Double.nan)], + map: map + ) + let b = AllNullableTypes( + aNullableDouble: Double.nan, + doubleList: list, + recursiveClassList: [AllNullableTypes(aNullableDouble: Double.nan)], + map: map + ) + #expect(a == b) + } + + @Test + func hashWithNaN() throws { + let a = AllNullableTypes(aNullableDouble: Double.nan) + let b = AllNullableTypes(aNullableDouble: Double.nan) + + var hasherA = Hasher() + a.hash(into: &hasherA) + let hashA = hasherA.finalize() + + var hasherB = Hasher() + b.hash(into: &hasherB) + let hashB = hasherB.finalize() + + #expect(hashA == hashB) + } + + @Test + func structEquality() { + let a = AllNullableTypesWithoutRecursion(aNullableInt: 1) + let b = AllNullableTypesWithoutRecursion(aNullableInt: 1) + let c = AllNullableTypesWithoutRecursion(aNullableInt: 2) + #expect(a == b) + #expect(a != c) + } + + @Test + func crossTypeEquality() { + let a = AllNullableTypes(aNullableInt: 1) + let b = AllNullableTypesWithoutRecursion(aNullableInt: 1) + // They are different types, so they shouldn't be equal even if we cast to Any + let anyA: Any = a + let anyB: Any = b + #expect(!(anyA as? AllNullableTypesWithoutRecursion == b)) + #expect(!(anyB as? AllNullableTypes == a)) + } + + @Test + func typedDataEquality() { + let data1 = "1234".data(using: .utf8)! + let data2 = "1234".data(using: .utf8)! + // Ensure they are different instances in memory if possible, + // though Data in Swift is a value type. + // FlutterStandardTypedData is a class. + let a = AllNullableTypes(aNullableByteArray: FlutterStandardTypedData(bytes: data1)) + let c = a + c.aNullableByteArray = FlutterStandardTypedData(bytes: data2) + + #expect(a == c) + } + + @Test + func signedZeroEquality() { + let a = AllNullableTypes(aNullableDouble: 0.0) + let b = AllNullableTypes(aNullableDouble: -0.0) + #expect(a == b) + + var hasherA = Hasher() + a.hash(into: &hasherA) + let hashA = hasherA.finalize() + + var hasherB = Hasher() + b.hash(into: &hasherB) + let hashB = hasherB.finalize() + + #expect(hashA == hashB) + } + + @Test + func nestedZeroListEquality() { + let a = AllNullableTypes(doubleList: [0.0]) + let b = AllNullableTypes(doubleList: [-0.0]) + #expect(a == b) + + var hasherA = Hasher() + a.hash(into: &hasherA) + let hashA = hasherA.finalize() + + var hasherB = Hasher() + b.hash(into: &hasherB) + let hashB = hasherB.finalize() + + #expect(hashA == hashB) + } + + @Test + func zeroMapKeyEquality() { + let a = AllNullableTypes(map: [0.0: "a"]) + let b = AllNullableTypes(map: [-0.0: "a"]) + #expect(a == b) + + var hasherA = Hasher() + a.hash(into: &hasherA) + let hashA = hasherA.finalize() + + var hasherB = Hasher() + b.hash(into: &hasherB) + let hashB = hasherB.finalize() + + #expect(hashA == hashB) + } + + @Test + func zeroMapValueEquality() { + let a = AllNullableTypes(map: ["a": 0.0]) + let b = AllNullableTypes(map: ["a": -0.0]) + #expect(a == b) + + var hasherA = Hasher() + a.hash(into: &hasherA) + let hashA = hasherA.finalize() + + var hasherB = Hasher() + b.hash(into: &hasherB) + let hashB = hasherB.finalize() + + #expect(hashA == hashB) + } } diff --git a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/AsyncHandlersTest.swift b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/AsyncHandlersTest.swift index 16419ec0cdfc..7a065ecfa551 100644 --- a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/AsyncHandlersTest.swift +++ b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/AsyncHandlersTest.swift @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import Flutter -import XCTest +import Testing @testable import test_plugin @@ -18,46 +18,49 @@ class MockHostSmallApi: HostSmallApi { } } -class AsyncHandlersTest: XCTestCase { +@MainActor +struct AsyncHandlersTest { - func testAsyncHost2Flutter() throws { + @Test + func asyncHost2Flutter() async throws { let value = "Test" let binaryMessenger = MockBinaryMessenger(codec: CoreTestsPigeonCodec.shared) binaryMessenger.result = value let flutterApi = FlutterIntegrationCoreApi(binaryMessenger: binaryMessenger) - let expectation = XCTestExpectation(description: "callback") - flutterApi.echo(value) { result in - switch result { - case .success(let res): - XCTAssertEqual(res, value) - expectation.fulfill() - case .failure(_): - return + await confirmation { confirmed in + flutterApi.echo(value) { result in + switch result { + case .success(let res): + #expect(res == value) + confirmed() + case .failure(let error): + Issue.record("Failed with error: \(error)") + } } - } - wait(for: [expectation], timeout: 1.0) } - func testAsyncFlutter2HostVoidVoid() throws { + @Test + func asyncFlutter2HostVoidVoid() async throws { let binaryMessenger = MockBinaryMessenger( codec: FlutterStandardMessageCodec.sharedInstance()) let mockHostSmallApi = MockHostSmallApi() HostSmallApiSetup.setUp(binaryMessenger: binaryMessenger, api: mockHostSmallApi) let channelName = "dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.voidVoid" - XCTAssertNotNil(binaryMessenger.handlers[channelName]) + #expect(binaryMessenger.handlers[channelName] != nil) - let expectation = XCTestExpectation(description: "voidvoid callback") - binaryMessenger.handlers[channelName]?(nil) { data in - let outputList = binaryMessenger.codec.decode(data) as? [Any] - XCTAssertEqual(outputList?.first as! NSNull, NSNull()) - expectation.fulfill() + await confirmation { confirmed in + binaryMessenger.handlers[channelName]?(nil) { data in + let outputList = binaryMessenger.codec.decode(data) as? [Any] + #expect(outputList?.first is NSNull) + confirmed() + } } - wait(for: [expectation], timeout: 1.0) } - func testAsyncFlutter2Host() throws { + @Test + func asyncFlutter2Host() async throws { let binaryMessenger = MockBinaryMessenger( codec: FlutterStandardMessageCodec.sharedInstance()) let mockHostSmallApi = MockHostSmallApi() @@ -65,17 +68,17 @@ class AsyncHandlersTest: XCTestCase { mockHostSmallApi.output = value HostSmallApiSetup.setUp(binaryMessenger: binaryMessenger, api: mockHostSmallApi) let channelName = "dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.echo" - XCTAssertNotNil(binaryMessenger.handlers[channelName]) + #expect(binaryMessenger.handlers[channelName] != nil) let inputEncoded = binaryMessenger.codec.encode([value]) - let expectation = XCTestExpectation(description: "echo callback") - binaryMessenger.handlers[channelName]?(inputEncoded) { data in - let outputList = binaryMessenger.codec.decode(data) as? [Any] - let output = outputList?.first as? String - XCTAssertEqual(output, value) - expectation.fulfill() + await confirmation { confirmed in + binaryMessenger.handlers[channelName]?(inputEncoded) { data in + let outputList = binaryMessenger.codec.decode(data) as? [Any] + let output = outputList?.first as? String + #expect(output == value) + confirmed() + } } - wait(for: [expectation], timeout: 1.0) } } diff --git a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/EnumTests.swift b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/EnumTests.swift index 3a1e958c0bc3..1e4526bf7b04 100644 --- a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/EnumTests.swift +++ b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/EnumTests.swift @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import XCTest +import Testing @testable import test_plugin @@ -12,46 +12,49 @@ class MockEnumApi2Host: EnumApi2Host { } } -class EnumTests: XCTestCase { +@MainActor +struct EnumTests { - func testEchoHost() throws { + @Test + func echoHost() async throws { let binaryMessenger = MockBinaryMessenger(codec: EnumPigeonCodec.shared) EnumApi2HostSetup.setUp(binaryMessenger: binaryMessenger, api: MockEnumApi2Host()) let channelName = "dev.flutter.pigeon.pigeon_integration_tests.EnumApi2Host.echo" - XCTAssertNotNil(binaryMessenger.handlers[channelName]) + #expect(binaryMessenger.handlers[channelName] != nil) let input = DataWithEnum(state: .success) let inputEncoded = binaryMessenger.codec.encode([input]) - let expectation = XCTestExpectation(description: "echo") - binaryMessenger.handlers[channelName]?(inputEncoded) { data in - let outputMap = binaryMessenger.codec.decode(data) as? [Any] - XCTAssertNotNil(outputMap) + await confirmation { confirmed in + binaryMessenger.handlers[channelName]?(inputEncoded) { data in + let outputMap = binaryMessenger.codec.decode(data) as? [Any] + #expect(outputMap != nil) - let output = outputMap?.first as? DataWithEnum - XCTAssertEqual(output, input) - XCTAssertTrue(outputMap?.count == 1) - expectation.fulfill() + let output = outputMap?.first as? DataWithEnum + #expect(output == input) + #expect(outputMap?.count == 1) + confirmed() + } } - wait(for: [expectation], timeout: 1.0) } - func testEchoFlutter() throws { + @Test + func echoFlutter() async throws { let data = DataWithEnum(state: .error) let binaryMessenger = EchoBinaryMessenger(codec: EnumPigeonCodec.shared) let api = EnumApi2Flutter(binaryMessenger: binaryMessenger) - let expectation = XCTestExpectation(description: "callback") - api.echo(data: data) { result in - switch result { - case .success(let res): - XCTAssertEqual(res.state, res.state) - expectation.fulfill() - case .failure(_): - return + await confirmation { confirmed in + api.echo(data: data) { result in + switch result { + case .success(let res): + #expect(res.state == data.state) + confirmed() + case .failure(let error): + Issue.record("Error: \(error) from data \(data)") + } } } - wait(for: [expectation], timeout: 1.0) } } diff --git a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/InstanceManagerTests.swift b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/InstanceManagerTests.swift index 716360ed50bb..372ac10802ed 100644 --- a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/InstanceManagerTests.swift +++ b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/InstanceManagerTests.swift @@ -4,43 +4,49 @@ import Flutter import Foundation -import XCTest +import Testing @testable import test_plugin -final class InstanceManagerTests: XCTestCase { - func testAddDartCreatedInstance() { +@MainActor +struct InstanceManagerTests { + @Test + func addDartCreatedInstance() { let finalizerDelegate = EmptyFinalizerDelegate() let instanceManager = ProxyApiTestsPigeonInstanceManager(finalizerDelegate: finalizerDelegate) let object = NSObject() instanceManager.addDartCreatedInstance(object, withIdentifier: 0) - XCTAssertEqual(instanceManager.instance(forIdentifier: 0), object) - XCTAssertEqual(instanceManager.identifierWithStrongReference(forInstance: object), 0) + #expect(instanceManager.instance(forIdentifier: 0) === object) + #expect(instanceManager.identifierWithStrongReference(forInstance: object) == 0) } - func testAddHostCreatedInstance() { + @Test + func addHostCreatedInstance() throws { let finalizerDelegate = EmptyFinalizerDelegate() let instanceManager = ProxyApiTestsPigeonInstanceManager(finalizerDelegate: finalizerDelegate) let object = NSObject() _ = instanceManager.addHostCreatedInstance(object) let identifier = instanceManager.identifierWithStrongReference(forInstance: object) - XCTAssertEqual(instanceManager.instance(forIdentifier: try XCTUnwrap(identifier)), object) + let unwrappedIdentifier = try #require(identifier) + #expect(instanceManager.instance(forIdentifier: unwrappedIdentifier) === object) } - func testRemoveInstance() { + @Test + func removeInstance() { let finalizerDelegate = EmptyFinalizerDelegate() let instanceManager = ProxyApiTestsPigeonInstanceManager(finalizerDelegate: finalizerDelegate) let object = NSObject() instanceManager.addDartCreatedInstance(object, withIdentifier: 0) - XCTAssertEqual(try! instanceManager.removeInstance(withIdentifier: 0), object) - XCTAssertEqual(instanceManager.strongInstanceCount, 0) + #expect(try! instanceManager.removeInstance(withIdentifier: 0) === object) + #expect(instanceManager.strongInstanceCount == 0) } - func testFinalizerCallsDelegateMethod() { + @Test + func finalizerCallsDelegateMethod() { let finalizerDelegate = TestFinalizerDelegate() var object: NSObject? = NSObject() @@ -48,10 +54,11 @@ final class InstanceManagerTests: XCTestCase { to: object!, identifier: 0, delegate: finalizerDelegate) object = nil - XCTAssertEqual(finalizerDelegate.lastHandledIdentifier, 0) + #expect(finalizerDelegate.lastHandledIdentifier == 0) } - func testRemoveAllObjects() { + @Test + func removeAllObjects() { let finalizerDelegate = EmptyFinalizerDelegate() let instanceManager = ProxyApiTestsPigeonInstanceManager(finalizerDelegate: finalizerDelegate) let object = NSObject() @@ -59,11 +66,12 @@ final class InstanceManagerTests: XCTestCase { instanceManager.addDartCreatedInstance(object, withIdentifier: 0) try? instanceManager.removeAllObjects() - XCTAssertEqual(instanceManager.strongInstanceCount, 0) - XCTAssertEqual(instanceManager.weakInstanceCount, 0) + #expect(instanceManager.strongInstanceCount == 0) + #expect(instanceManager.weakInstanceCount == 0) } - func testCanAddSameObjectWithAddDartCreatedInstance() { + @Test + func canAddSameObjectWithAddDartCreatedInstance() { let finalizerDelegate = EmptyFinalizerDelegate() let instanceManager = ProxyApiTestsPigeonInstanceManager(finalizerDelegate: finalizerDelegate) let object = NSObject() @@ -74,10 +82,11 @@ final class InstanceManagerTests: XCTestCase { let instance1: NSObject? = instanceManager.instance(forIdentifier: 0) let instance2: NSObject? = instanceManager.instance(forIdentifier: 1) - XCTAssertEqual(instance1, instance2) + #expect(instance1 === instance2) } - func testObjectsAreStoredWithPointerHashcode() { + @Test + func objectsAreStoredWithPointerHashcode() { let finalizerDelegate = EmptyFinalizerDelegate() let instanceManager = ProxyApiTestsPigeonInstanceManager(finalizerDelegate: finalizerDelegate) @@ -91,17 +100,18 @@ final class InstanceManagerTests: XCTestCase { let instance2 = EquatableClass() // Ensure instances are considered equal. - XCTAssertTrue(instance1 == instance2) + #expect(instance1 == instance2) _ = instanceManager.addHostCreatedInstance(instance1) _ = instanceManager.addHostCreatedInstance(instance2) - XCTAssertNotEqual( - instanceManager.identifierWithStrongReference(forInstance: instance1), - instanceManager.identifierWithStrongReference(forInstance: instance2)) + #expect( + instanceManager.identifierWithStrongReference(forInstance: instance1) + != instanceManager.identifierWithStrongReference(forInstance: instance2)) } - func testInstanceManagerCanBeDeallocated() { + @Test + func instanceManagerCanBeDeallocated() { let binaryMessenger = MockBinaryMessenger( codec: FlutterStandardMessageCodec.sharedInstance()) @@ -127,10 +137,11 @@ final class InstanceManagerTests: XCTestCase { ProxyApiTestsPigeonInternalFinalizer.attach( to: registrar!.instanceManager, identifier: 0, delegate: finalizerDelegate) registrar = nil - XCTAssertEqual(finalizerDelegate.lastHandledIdentifier, 0) + #expect(finalizerDelegate.lastHandledIdentifier == 0) } - func testRemoveAllObjectsRemovesFinalizersFromWeakInstances() { + @Test + func removeAllObjectsRemovesFinalizersFromWeakInstances() { let finalizerDelegate = TestFinalizerDelegate() let instanceManager = ProxyApiTestsPigeonInstanceManager(finalizerDelegate: finalizerDelegate) @@ -143,9 +154,10 @@ final class InstanceManagerTests: XCTestCase { let _: AnyObject? = try! instanceManager.removeInstance(withIdentifier: identifier) try? instanceManager.removeAllObjects() - XCTAssertNil(finalizer.delegate) - XCTAssertNil( - objc_getAssociatedObject(object!, ProxyApiTestsPigeonInternalFinalizer.associatedObjectKey)) + #expect(finalizer.delegate == nil) + #expect( + objc_getAssociatedObject(object!, ProxyApiTestsPigeonInternalFinalizer.associatedObjectKey) + == nil) } } diff --git a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/ListTests.swift b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/ListTests.swift index ed2edfd76de6..a681304291b2 100644 --- a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/ListTests.swift +++ b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/ListTests.swift @@ -2,31 +2,33 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import XCTest +import Testing @testable import test_plugin -class ListTests: XCTestCase { +@MainActor +struct ListTests { - func testListInList() throws { + @Test + func listInList() async throws { let inside = TestMessage(testList: [1, 2, 3]) let top = TestMessage(testList: [inside]) let binaryMessenger = EchoBinaryMessenger(codec: CoreTestsPigeonCodec.shared) let api = FlutterSmallApi(binaryMessenger: binaryMessenger) - let expectation = XCTestExpectation(description: "callback") - api.echo(top) { result in - switch result { - case .success(let res): - XCTAssertEqual(1, res.testList?.count) - XCTAssertTrue(res.testList?[0] is TestMessage) - XCTAssert(equalsList(inside.testList, (res.testList?[0] as! TestMessage).testList)) - expectation.fulfill() - case .failure(_): - return + await confirmation { confirmed in + api.echo(top) { result in + switch result { + case .success(let res): + #expect(res.testList?.count == 1) + #expect(res.testList?[0] is TestMessage) + #expect(equalsList(inside.testList, (res.testList?[0] as! TestMessage).testList)) + confirmed() + case .failure(let error): + Issue.record("Failed with error: \(error)") + } } } - wait(for: [expectation], timeout: 1.0) } } diff --git a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/MultipleArityTests.swift b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/MultipleArityTests.swift index 0a8b90e5d0ce..7a87a0052231 100644 --- a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/MultipleArityTests.swift +++ b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/MultipleArityTests.swift @@ -3,7 +3,7 @@ // found in the LICENSE file. import Flutter -import XCTest +import Testing @testable import test_plugin @@ -13,48 +13,52 @@ class MockMultipleArityHostApi: MultipleArityHostApi { } } -class MultipleArityTests: XCTestCase { - var codec = FlutterStandardMessageCodec.sharedInstance() - func testSimpleHost() throws { +@MainActor +struct MultipleArityTests { + let codec = FlutterStandardMessageCodec.sharedInstance() + + @Test + func simpleHost() async throws { let binaryMessenger = MockBinaryMessenger(codec: EnumPigeonCodec.shared) MultipleArityHostApiSetup.setUp( binaryMessenger: binaryMessenger, api: MockMultipleArityHostApi()) let channelName = "dev.flutter.pigeon.pigeon_integration_tests.MultipleArityHostApi.subtract" - XCTAssertNotNil(binaryMessenger.handlers[channelName]) + #expect(binaryMessenger.handlers[channelName] != nil) let inputX = 10 let inputY = 7 let inputEncoded = binaryMessenger.codec.encode([inputX, inputY]) - let expectation = XCTestExpectation(description: "subtraction") - binaryMessenger.handlers[channelName]?(inputEncoded) { data in - let outputList = binaryMessenger.codec.decode(data) as? [Any] - XCTAssertNotNil(outputList) + await confirmation { confirmed in + binaryMessenger.handlers[channelName]?(inputEncoded) { data in + let outputList = binaryMessenger.codec.decode(data) as? [Any] + #expect(outputList != nil) - let output = outputList![0] as? Int64 - XCTAssertEqual(3, output) - XCTAssertTrue(outputList?.count == 1) - expectation.fulfill() + let output = outputList![0] as? Int64 + #expect(output == 3) + #expect(outputList?.count == 1) + confirmed() + } } - wait(for: [expectation], timeout: 1.0) } - func testSimpleFlutter() throws { + @Test + func simpleFlutter() async throws { let binaryMessenger = HandlerBinaryMessenger(codec: codec) { args in return (args[0] as! Int) - (args[1] as! Int) } let api = MultipleArityFlutterApi(binaryMessenger: binaryMessenger) - let expectation = XCTestExpectation(description: "subtraction") - api.subtract(x: 30, y: 10) { result in - switch result { - case .success(let res): - XCTAssertEqual(20, res) - expectation.fulfill() - case .failure(_): - return + await confirmation { confirmed in + api.subtract(x: 30, y: 10) { result in + switch result { + case .success(let res): + #expect(res == 20) + confirmed() + case .failure(let error): + Issue.record("Failed with error: \(error)") + } } } - wait(for: [expectation], timeout: 1.0) } } diff --git a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/NSNullFieldTests.swift b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/NSNullFieldTests.swift index bfa599261954..67693851b2ad 100644 --- a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/NSNullFieldTests.swift +++ b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/NSNullFieldTests.swift @@ -2,14 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import XCTest +import Foundation +import Testing @testable import test_plugin /// Tests NSNull is correctly handled by `nilOrValue` helper, by manually setting nullable fields to NSNull. -final class NSNullFieldTests: XCTestCase { +struct NSNullFieldTests { - func testNSNull_nullListToCustomStructField() throws { + @Test + func nullListToCustomStructField() throws { let reply = NullFieldsSearchReply( result: nil, error: nil, @@ -20,11 +22,12 @@ final class NSNullFieldTests: XCTestCase { // request field list[3] = NSNull() let copy = NullFieldsSearchReply.fromList(list) - XCTAssertNotNil(copy) - XCTAssertNil(copy!.request) + #expect(copy != nil) + #expect(copy!.request == nil) } - func testNSNull_nullListField() { + @Test + func nullListField() { let reply = NullFieldsSearchReply( result: nil, error: nil, @@ -35,11 +38,12 @@ final class NSNullFieldTests: XCTestCase { // indices field list[2] = NSNull() let copy = NullFieldsSearchReply.fromList(list) - XCTAssertNotNil(copy) - XCTAssertNil(copy!.indices) + #expect(copy != nil) + #expect(copy!.indices == nil) } - func testNSNull_nullBasicFields() throws { + @Test + func nullBasicFields() throws { let reply = NullFieldsSearchReply( result: nil, error: nil, @@ -54,9 +58,9 @@ final class NSNullFieldTests: XCTestCase { // type field list[4] = NSNull() let copy = NullFieldsSearchReply.fromList(list) - XCTAssertNotNil(copy) - XCTAssertNil(copy!.result) - XCTAssertNil(copy!.error) - XCTAssertNil(copy!.type) + #expect(copy != nil) + #expect(copy!.result == nil) + #expect(copy!.error == nil) + #expect(copy!.type == nil) } } diff --git a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/NonNullFieldsTest.swift b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/NonNullFieldsTest.swift index 23c69565f7ca..bb06e1bbf2b2 100644 --- a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/NonNullFieldsTest.swift +++ b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/NonNullFieldsTest.swift @@ -2,13 +2,25 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import XCTest +import Testing @testable import test_plugin -class NonNullFieldsTests: XCTestCase { - func testMake() { +struct NonNullFieldsTests { + @Test + func make() { let request = NonNullFieldSearchRequest(query: "hello") - XCTAssertEqual("hello", request.query) + #expect(request.query == "hello") + } + + @Test + func testEquality() { + let request1 = NonNullFieldSearchRequest(query: "hello") + let request2 = NonNullFieldSearchRequest(query: "hello") + let request3 = NonNullFieldSearchRequest(query: "world") + + #expect(request1 == request2) + #expect(request1 != request3) + #expect(request1.hashValue == request2.hashValue) } } diff --git a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/NullableReturnsTests.swift b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/NullableReturnsTests.swift index ea0436e803e8..e2925038f6b9 100644 --- a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/NullableReturnsTests.swift +++ b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/NullableReturnsTests.swift @@ -3,7 +3,7 @@ // found in the LICENSE file. import Flutter -import XCTest +import Testing @testable import test_plugin @@ -18,44 +18,47 @@ class MockNullableArgHostApi: NullableArgHostApi { } } -class NullableReturnsTests: XCTestCase { - var codec = FlutterStandardMessageCodec.sharedInstance() - func testNullableParameterWithFlutterApi() { +@MainActor +struct NullableReturnsTests { + let codec = FlutterStandardMessageCodec.sharedInstance() + + @Test + func nullableParameterWithFlutterApi() async throws { let binaryMessenger = EchoBinaryMessenger(codec: codec) binaryMessenger.defaultReturn = 99 let api = NullableArgFlutterApi(binaryMessenger: binaryMessenger) - let expectation = XCTestExpectation(description: "callback") - api.doit(x: nil) { result in - switch result { - case .success(let res): - XCTAssertEqual(99, res) - expectation.fulfill() - case .failure(_): - return + await confirmation { confirmed in + api.doit(x: nil) { result in + switch result { + case .success(let res): + #expect(res == 99) + confirmed() + case .failure(let error): + Issue.record("Failed with error: \(error)") + } } } - wait(for: [expectation], timeout: 1.0) } - func testNullableParameterWithHostApi() { + @Test + func nullableParameterWithHostApi() async throws { let api = MockNullableArgHostApi() let binaryMessenger = MockBinaryMessenger(codec: codec) let channel = "dev.flutter.pigeon.pigeon_integration_tests.NullableArgHostApi.doit" NullableArgHostApiSetup.setUp(binaryMessenger: binaryMessenger, api: api) - XCTAssertNotNil(binaryMessenger.handlers[channel]) + #expect(binaryMessenger.handlers[channel] != nil) let inputEncoded = binaryMessenger.codec.encode([nil] as [Any?]) - let expectation = XCTestExpectation(description: "callback") - binaryMessenger.handlers[channel]?(inputEncoded) { _ in - expectation.fulfill() + await confirmation { confirmed in + binaryMessenger.handlers[channel]?(inputEncoded) { _ in + confirmed() + } } - XCTAssertTrue(api.didCall) - XCTAssertNil(api.x) - wait(for: [expectation], timeout: 1.0) - + #expect(api.didCall) + #expect(api.x == nil) } } diff --git a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/PrimitiveTests.swift b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/PrimitiveTests.swift index 7ad2c20013fa..0a3228e86eaf 100644 --- a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/PrimitiveTests.swift +++ b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/PrimitiveTests.swift @@ -3,7 +3,7 @@ // found in the LICENSE file. import Flutter -import XCTest +import Testing @testable import test_plugin @@ -19,247 +19,257 @@ class MockPrimitiveHostApi: PrimitiveHostApi { func aStringIntMap(value: [String?: Int64?]) -> [String?: Int64?] { value } } -class PrimitiveTests: XCTestCase { - var codec = FlutterStandardMessageCodec.sharedInstance() +@MainActor +struct PrimitiveTests { + let codec = FlutterStandardMessageCodec.sharedInstance() - func testIntPrimitiveHost() throws { + @Test + func intPrimitiveHost() async throws { let binaryMessenger = MockBinaryMessenger(codec: codec) PrimitiveHostApiSetup.setUp(binaryMessenger: binaryMessenger, api: MockPrimitiveHostApi()) let channelName = "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.anInt" - XCTAssertNotNil(binaryMessenger.handlers[channelName]) + #expect(binaryMessenger.handlers[channelName] != nil) let input = 1 let inputEncoded = binaryMessenger.codec.encode([input]) - let expectation = XCTestExpectation(description: "anInt") - binaryMessenger.handlers[channelName]?(inputEncoded) { data in - let outputList = binaryMessenger.codec.decode(data) as? [Any] - XCTAssertNotNil(outputList) + await confirmation { confirmed in + binaryMessenger.handlers[channelName]?(inputEncoded) { data in + let outputList = binaryMessenger.codec.decode(data) as? [Any] + #expect(outputList != nil) - let output = outputList!.first as? Int64 - XCTAssertEqual(1, output) - XCTAssertTrue(outputList!.count == 1) - expectation.fulfill() + let output = outputList!.first as? Int64 + #expect(output == 1) + #expect(outputList!.count == 1) + confirmed() + } } - wait(for: [expectation], timeout: 1.0) } - func testIntPrimitiveFlutter() throws { + @Test + func intPrimitiveFlutter() async throws { let binaryMessenger = EchoBinaryMessenger(codec: codec) let api = PrimitiveFlutterApi(binaryMessenger: binaryMessenger) - let expectation = XCTestExpectation(description: "callback") - api.anInt(value: 1) { result in - switch result { - case .success(let res): - XCTAssertEqual(1, res) - expectation.fulfill() - case .failure(_): - return - + await confirmation { confirmed in + api.anInt(value: 1) { result in + switch result { + case .success(let res): + #expect(res == 1) + confirmed() + case .failure(let error): + Issue.record("Failed with error: \(error)") + } } } - wait(for: [expectation], timeout: 1.0) } - func testBoolPrimitiveHost() throws { + @Test + func boolPrimitiveHost() async throws { let binaryMessenger = MockBinaryMessenger(codec: codec) PrimitiveHostApiSetup.setUp(binaryMessenger: binaryMessenger, api: MockPrimitiveHostApi()) let channelName = "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aBool" - XCTAssertNotNil(binaryMessenger.handlers[channelName]) + #expect(binaryMessenger.handlers[channelName] != nil) let input = true let inputEncoded = binaryMessenger.codec.encode([input]) - let expectation = XCTestExpectation(description: "aBool") - binaryMessenger.handlers[channelName]?(inputEncoded) { data in - let outputList = binaryMessenger.codec.decode(data) as? [Any] - XCTAssertNotNil(outputList) + await confirmation { confirmed in + binaryMessenger.handlers[channelName]?(inputEncoded) { data in + let outputList = binaryMessenger.codec.decode(data) as? [Any] + #expect(outputList != nil) - let output = outputList!.first as? Bool - XCTAssertEqual(true, output) - XCTAssertTrue(outputList!.count == 1) - expectation.fulfill() + let output = outputList!.first as? Bool + #expect(output == true) + #expect(outputList!.count == 1) + confirmed() + } } - wait(for: [expectation], timeout: 1.0) } - func testBoolPrimitiveFlutter() throws { + @Test + func boolPrimitiveFlutter() async throws { let binaryMessenger = EchoBinaryMessenger(codec: codec) let api = PrimitiveFlutterApi(binaryMessenger: binaryMessenger) - let expectation = XCTestExpectation(description: "callback") - api.aBool(value: true) { result in - switch result { - case .success(let res): - XCTAssertEqual(true, res) - expectation.fulfill() - case .failure(_): - return + await confirmation { confirmed in + api.aBool(value: true) { result in + switch result { + case .success(let res): + #expect(res == true) + confirmed() + case .failure(let error): + Issue.record("Failed with error: \(error)") + } } } - wait(for: [expectation], timeout: 1.0) } - func testDoublePrimitiveHost() throws { + @Test + func doublePrimitiveHost() async throws { let binaryMessenger = MockBinaryMessenger(codec: codec) PrimitiveHostApiSetup.setUp(binaryMessenger: binaryMessenger, api: MockPrimitiveHostApi()) let channelName = "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aDouble" - XCTAssertNotNil(binaryMessenger.handlers[channelName]) + #expect(binaryMessenger.handlers[channelName] != nil) let input: Double = 1.0 let inputEncoded = binaryMessenger.codec.encode([input]) - let expectation = XCTestExpectation(description: "aDouble") - binaryMessenger.handlers[channelName]?(inputEncoded) { data in - let outputList = binaryMessenger.codec.decode(data) as? [Any] - XCTAssertNotNil(outputList) + await confirmation { confirmed in + binaryMessenger.handlers[channelName]?(inputEncoded) { data in + let outputList = binaryMessenger.codec.decode(data) as? [Any] + #expect(outputList != nil) - let output = outputList!.first as? Double - XCTAssertEqual(1.0, output) - XCTAssertTrue(outputList!.count == 1) - expectation.fulfill() + let output = outputList!.first as? Double + #expect(output == 1.0) + #expect(outputList!.count == 1) + confirmed() + } } - wait(for: [expectation], timeout: 1.0) } - func testDoublePrimitiveFlutter() throws { + @Test + func doublePrimitiveFlutter() async throws { let binaryMessenger = EchoBinaryMessenger(codec: codec) let api = PrimitiveFlutterApi(binaryMessenger: binaryMessenger) - let expectation = XCTestExpectation(description: "callback") - let arg: Double = 1.5 - api.aDouble(value: arg) { result in - switch result { - case .success(let res): - XCTAssertEqual(arg, res) - expectation.fulfill() - case .failure(_): - return + await confirmation { confirmed in + let arg: Double = 1.5 + api.aDouble(value: arg) { result in + switch result { + case .success(let res): + #expect(res == arg) + confirmed() + case .failure(let error): + Issue.record("Failed with error: \(error)") + } } } - wait(for: [expectation], timeout: 1.0) } - func testStringPrimitiveHost() throws { + @Test + func stringPrimitiveHost() async throws { let binaryMessenger = MockBinaryMessenger(codec: codec) PrimitiveHostApiSetup.setUp(binaryMessenger: binaryMessenger, api: MockPrimitiveHostApi()) let channelName = "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aString" - XCTAssertNotNil(binaryMessenger.handlers[channelName]) + #expect(binaryMessenger.handlers[channelName] != nil) let input: String = "hello" let inputEncoded = binaryMessenger.codec.encode([input]) - let expectation = XCTestExpectation(description: "aString") - binaryMessenger.handlers[channelName]?(inputEncoded) { data in - let outputList = binaryMessenger.codec.decode(data) as? [Any] - XCTAssertNotNil(outputList) + await confirmation { confirmed in + binaryMessenger.handlers[channelName]?(inputEncoded) { data in + let outputList = binaryMessenger.codec.decode(data) as? [Any] + #expect(outputList != nil) - let output = outputList!.first as? String - XCTAssertEqual("hello", output) - XCTAssertTrue(outputList!.count == 1) - expectation.fulfill() + let output = outputList!.first as? String + #expect(output == "hello") + #expect(outputList!.count == 1) + confirmed() + } } - wait(for: [expectation], timeout: 1.0) } - func testStringPrimitiveFlutter() throws { + @Test + func stringPrimitiveFlutter() async throws { let binaryMessenger = EchoBinaryMessenger(codec: codec) let api = PrimitiveFlutterApi(binaryMessenger: binaryMessenger) - let expectation = XCTestExpectation(description: "callback") - let arg: String = "hello" - api.aString(value: arg) { result in - switch result { - case .success(let res): - XCTAssertEqual(arg, res) - expectation.fulfill() - case .failure(_): - return + await confirmation { confirmed in + let arg: String = "hello" + api.aString(value: arg) { result in + switch result { + case .success(let res): + #expect(res == arg) + confirmed() + case .failure(let error): + Issue.record("Failed with error: \(error)") + } } } - wait(for: [expectation], timeout: 1.0) } - func testListPrimitiveHost() throws { + @Test + func listPrimitiveHost() async throws { let binaryMessenger = MockBinaryMessenger<[Int]>(codec: codec) PrimitiveHostApiSetup.setUp(binaryMessenger: binaryMessenger, api: MockPrimitiveHostApi()) let channelName = "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aList" - XCTAssertNotNil(binaryMessenger.handlers[channelName]) + #expect(binaryMessenger.handlers[channelName] != nil) let input: [Int] = [1, 2, 3] let inputEncoded = binaryMessenger.codec.encode([input]) - let expectation = XCTestExpectation(description: "aList") - binaryMessenger.handlers[channelName]?(inputEncoded) { data in - let outputList = binaryMessenger.codec.decode(data) as? [Any] - XCTAssertNotNil(outputList) + await confirmation { confirmed in + binaryMessenger.handlers[channelName]?(inputEncoded) { data in + let outputList = binaryMessenger.codec.decode(data) as? [Any] + #expect(outputList != nil) - let output = outputList!.first as? [Int] - XCTAssertEqual([1, 2, 3], output) - XCTAssertTrue(outputList!.count == 1) - expectation.fulfill() + let output = outputList!.first as? [Int] + #expect(output == [1, 2, 3]) + #expect(outputList!.count == 1) + confirmed() + } } - wait(for: [expectation], timeout: 1.0) } - func testListPrimitiveFlutter() throws { + @Test + func listPrimitiveFlutter() async throws { let binaryMessenger = EchoBinaryMessenger(codec: codec) let api = PrimitiveFlutterApi(binaryMessenger: binaryMessenger) - let expectation = XCTestExpectation(description: "callback") - let arg = ["hello"] - api.aList(value: arg) { result in - switch result { - case .success(let res): - XCTAssert(equalsList(arg, res)) - expectation.fulfill() - case .failure(_): - return + await confirmation { confirmed in + let arg = ["hello"] + api.aList(value: arg) { result in + switch result { + case .success(let res): + #expect(equalsList(arg, res)) + confirmed() + case .failure(let error): + Issue.record("Failed with error: \(error)") + } } } - wait(for: [expectation], timeout: 1.0) } - func testMapPrimitiveHost() throws { + @Test + func mapPrimitiveHost() async throws { let binaryMessenger = MockBinaryMessenger<[String: Int]>(codec: codec) PrimitiveHostApiSetup.setUp(binaryMessenger: binaryMessenger, api: MockPrimitiveHostApi()) let channelName = "dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aMap" - XCTAssertNotNil(binaryMessenger.handlers[channelName]) + #expect(binaryMessenger.handlers[channelName] != nil) let input: [String: Int] = ["hello": 1, "world": 2] let inputEncoded = binaryMessenger.codec.encode([input]) - let expectation = XCTestExpectation(description: "aMap") - binaryMessenger.handlers[channelName]?(inputEncoded) { data in - let output = binaryMessenger.codec.decode(data) as? [Any] - XCTAssertTrue(output?.count == 1) + await confirmation { confirmed in + binaryMessenger.handlers[channelName]?(inputEncoded) { data in + let output = binaryMessenger.codec.decode(data) as? [Any] + #expect(output?.count == 1) - let outputMap = output?.first as? [String: Int] - XCTAssertNotNil(outputMap) - XCTAssertEqual(["hello": 1, "world": 2], outputMap) - expectation.fulfill() + let outputMap = output?.first as? [String: Int] + #expect(outputMap != nil) + #expect(outputMap == ["hello": 1, "world": 2]) + confirmed() + } } - wait(for: [expectation], timeout: 1.0) } - func testMapPrimitiveFlutter() throws { + @Test + func mapPrimitiveFlutter() async throws { let binaryMessenger = EchoBinaryMessenger(codec: codec) let api = PrimitiveFlutterApi(binaryMessenger: binaryMessenger) - let expectation = XCTestExpectation(description: "callback") - let arg = ["hello": 1] - api.aMap(value: arg) { result in - switch result { - case .success(let res): - XCTAssert(equalsDictionary(arg, res)) - expectation.fulfill() - case .failure(_): - return + await confirmation { confirmed in + let arg = ["hello": 1] + api.aMap(value: arg) { result in + switch result { + case .success(let res): + #expect(equalsDictionary(arg, res)) + confirmed() + case .failure(let error): + Issue.record("Failed with error: \(error)") + } } - } - wait(for: [expectation], timeout: 1.0) } - } diff --git a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/ProxyApiTests.swift b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/ProxyApiTests.swift new file mode 100644 index 000000000000..c265da8aa255 --- /dev/null +++ b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/ProxyApiTests.swift @@ -0,0 +1,39 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import Flutter +import Testing + +@testable import test_plugin + +@MainActor +struct ProxyApiTests { + @Test + func callsToDartFailIfTheInstanceIsNotInTheInstanceManager() async { + let testObject = ProxyApiTestClass() + + let binaryMessenger = MockBinaryMessenger( + codec: FlutterStandardMessageCodec.sharedInstance()) + let registrar = ProxyApiTestsPigeonProxyApiRegistrar( + binaryMessenger: binaryMessenger, apiDelegate: ProxyApiDelegate()) + + _ = registrar.instanceManager.addHostCreatedInstance(testObject) + try? registrar.instanceManager.removeAllObjects() + + let api = PigeonApiProxyApiTestClass( + pigeonRegistrar: registrar, delegate: ProxyApiTestClassDelegate()) + + await confirmation { confirmed in + api.flutterNoop(pigeonInstance: testObject) { response in + if case .failure(let error) = response { + #expect( + error.message + == "Callback to `ProxyApiTestClass.flutterNoop` failed because native instance was not in the instance manager." + ) + confirmed() + } + } + } + } +} diff --git a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/RunnerTests.swift b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/RunnerTests.swift index 1f848d3bff9d..7eacd6195fc3 100644 --- a/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/RunnerTests.swift +++ b/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/RunnerTests.swift @@ -4,44 +4,52 @@ import Flutter import Foundation -import XCTest +import Testing @testable import test_plugin -class RunnerTests: XCTestCase { +@MainActor +struct RunnerTests { - func testToListAndBack() throws { + @Test + func toListAndBack() throws { let reply = MessageSearchReply(result: "foobar") let dict = reply.toList() let copy = MessageSearchReply.fromList(dict) - XCTAssertEqual(reply.result, copy?.result) + #expect(reply.result == copy?.result) } - func testHandlesNull() throws { + @Test + func handlesNull() throws { let reply = MessageSearchReply() let dict = reply.toList() let copy = MessageSearchReply.fromList(dict) - XCTAssertNil(copy?.result) + #expect(copy?.result == nil) } - func testHandlesNullFirst() throws { + @Test + func handlesNullFirst() throws { let reply = MessageSearchReply(error: "foobar") let dict = reply.toList() let copy = MessageSearchReply.fromList(dict) - XCTAssertEqual(reply.error, copy?.error) + #expect(reply.error == copy?.error) } /// This validates that pigeon clients can easily write tests that mock out Flutter API /// calls using a pigeon-generated protocol. - func testEchoStringFromProtocol() throws { + @Test + func echoStringFromProtocol() async throws { let api: FlutterApiFromProtocol = FlutterApiFromProtocol() let aString = "aString" - api.echo(string: aString) { response in - switch response { - case .success(let res): - XCTAssertEqual(aString, res) - case .failure(let error): - XCTFail(error.code) + await confirmation { confirmed in + api.echo(string: aString) { response in + switch response { + case .success(let res): + #expect(aString == res) + case .failure(let error): + Issue.record("Failed with error: \(error)") + } + confirmed() } } } diff --git a/packages/pigeon/platform_tests/test_plugin/example/macos/Flutter/Flutter-Debug.xcconfig b/packages/pigeon/platform_tests/test_plugin/example/macos/Flutter/Flutter-Debug.xcconfig index 4b81f9b2d200..c2efd0b608ba 100644 --- a/packages/pigeon/platform_tests/test_plugin/example/macos/Flutter/Flutter-Debug.xcconfig +++ b/packages/pigeon/platform_tests/test_plugin/example/macos/Flutter/Flutter-Debug.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" diff --git a/packages/pigeon/platform_tests/test_plugin/example/macos/Flutter/Flutter-Release.xcconfig b/packages/pigeon/platform_tests/test_plugin/example/macos/Flutter/Flutter-Release.xcconfig index 5caa9d1579e4..c2efd0b608ba 100644 --- a/packages/pigeon/platform_tests/test_plugin/example/macos/Flutter/Flutter-Release.xcconfig +++ b/packages/pigeon/platform_tests/test_plugin/example/macos/Flutter/Flutter-Release.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" diff --git a/packages/pigeon/platform_tests/test_plugin/example/macos/Podfile b/packages/pigeon/platform_tests/test_plugin/example/macos/Podfile deleted file mode 100644 index 71619503cdb0..000000000000 --- a/packages/pigeon/platform_tests/test_plugin/example/macos/Podfile +++ /dev/null @@ -1,47 +0,0 @@ -platform :osx, '10.14' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\"" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_macos_podfile_setup - -target 'Runner' do - use_frameworks! - - flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__)) - - target 'RunnerTests' do - inherit! :search_paths - end -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_macos_build_settings(target) - - target.build_configurations.each do |config| - config.build_settings['SWIFT_TREAT_WARNINGS_AS_ERRORS'] = 'YES' - end - end -end diff --git a/packages/pigeon/platform_tests/test_plugin/example/macos/Runner.xcodeproj/project.pbxproj b/packages/pigeon/platform_tests/test_plugin/example/macos/Runner.xcodeproj/project.pbxproj index 55a5621471dc..30471781624a 100644 --- a/packages/pigeon/platform_tests/test_plugin/example/macos/Runner.xcodeproj/project.pbxproj +++ b/packages/pigeon/platform_tests/test_plugin/example/macos/Runner.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 54; + objectVersion = 60; objects = { /* Begin PBXAggregateTarget section */ @@ -27,9 +27,7 @@ 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; - 6315A7A2721DA1118B8E9021 /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 29E004D53850EB57FB6837A5 /* Pods_RunnerTests.framework */; }; 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; - 875D4A972362F737CAF2FE4C /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9FC0DA6B36ADE41CB6E0674E /* Pods_Runner.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -63,8 +61,6 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 1D1B345C7A308AD53319BFE8 /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; - 29E004D53850EB57FB6837A5 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; 33A341DB291ED36900D34E0F /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -81,14 +77,11 @@ 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; - 34C7F8E51A95DED51F18178C /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + 784666492D4C4C64000A1A5F /* FlutterFramework */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterFramework; path = ephemeral/Packages/.packages/FlutterFramework; sourceTree = ""; }; + 78DABEA22ED26510000E7860 /* test_plugin */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = test_plugin; path = ../../../darwin/test_plugin; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; - 84F9F76B1CDA5A3EA34A53A9 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; - 9FC0DA6B36ADE41CB6E0674E /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - CE9F6321D99B81775C2E58F7 /* 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 = ""; }; - D883C1052351847D8F8C1AC6 /* 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 = ""; }; - E2C8B3AD8F4C88A8093956DB /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -96,7 +89,6 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 6315A7A2721DA1118B8E9021 /* Pods_RunnerTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -105,7 +97,6 @@ buildActionMask = 2147483647; files = ( 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, - 875D4A972362F737CAF2FE4C /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -138,7 +129,6 @@ 33CEB47122A05771004F2AC0 /* Flutter */, 33A341DC291ED36900D34E0F /* RunnerTests */, 33CC10EE2044A3C60003C045 /* Products */, - D73912EC22F37F3D000D13A0 /* Frameworks */, CA1DCAF3D143850A6677D34A /* Pods */, ); sourceTree = ""; @@ -166,6 +156,9 @@ 33CEB47122A05771004F2AC0 /* Flutter */ = { isa = PBXGroup; children = ( + 78DABEA22ED26510000E7860 /* test_plugin */, + 784666492D4C4C64000A1A5F /* FlutterFramework */, + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, @@ -190,24 +183,8 @@ CA1DCAF3D143850A6677D34A /* Pods */ = { isa = PBXGroup; children = ( - 34C7F8E51A95DED51F18178C /* Pods-Runner.debug.xcconfig */, - 84F9F76B1CDA5A3EA34A53A9 /* Pods-Runner.release.xcconfig */, - E2C8B3AD8F4C88A8093956DB /* Pods-Runner.profile.xcconfig */, - CE9F6321D99B81775C2E58F7 /* Pods-RunnerTests.debug.xcconfig */, - D883C1052351847D8F8C1AC6 /* Pods-RunnerTests.release.xcconfig */, - 1D1B345C7A308AD53319BFE8 /* Pods-RunnerTests.profile.xcconfig */, - ); - name = Pods; - path = Pods; - sourceTree = ""; - }; - D73912EC22F37F3D000D13A0 /* Frameworks */ = { - isa = PBXGroup; - children = ( - 9FC0DA6B36ADE41CB6E0674E /* Pods_Runner.framework */, - 29E004D53850EB57FB6837A5 /* Pods_RunnerTests.framework */, ); - name = Frameworks; + path = Pods; sourceTree = ""; }; /* End PBXGroup section */ @@ -217,7 +194,6 @@ isa = PBXNativeTarget; buildConfigurationList = 33A341E4291ED36900D34E0F /* Build configuration list for PBXNativeTarget "RunnerTests" */; buildPhases = ( - D8A37CA9DC49F3BACCA22E13 /* [CP] Check Pods Manifest.lock */, 33A341D7291ED36900D34E0F /* Sources */, 33A341D8291ED36900D34E0F /* Frameworks */, 33A341D9291ED36900D34E0F /* Resources */, @@ -236,7 +212,6 @@ isa = PBXNativeTarget; buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - D30FEEB3988449C1EC3D1DBF /* [CP] Check Pods Manifest.lock */, 33CC10E92044A3C60003C045 /* Sources */, 33CC10EA2044A3C60003C045 /* Frameworks */, 33CC10EB2044A3C60003C045 /* Resources */, @@ -367,50 +342,6 @@ shellPath = /bin/sh; shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; }; - D30FEEB3988449C1EC3D1DBF /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - D8A37CA9DC49F3BACCA22E13 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -498,7 +429,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; + MACOSX_DEPLOYMENT_TARGET = 10.15; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; @@ -535,7 +466,6 @@ }; 33A341E1291ED36900D34E0F /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = CE9F6321D99B81775C2E58F7 /* Pods-RunnerTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; @@ -543,14 +473,13 @@ MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 6.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/test_plugin_example.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/test_plugin_example"; }; name = Debug; }; 33A341E2291ED36900D34E0F /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = D883C1052351847D8F8C1AC6 /* Pods-RunnerTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; @@ -558,14 +487,13 @@ MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 6.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/test_plugin_example.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/test_plugin_example"; }; name = Release; }; 33A341E3291ED36900D34E0F /* Profile */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 1D1B345C7A308AD53319BFE8 /* Pods-RunnerTests.profile.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; @@ -573,7 +501,7 @@ MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 6.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/test_plugin_example.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/test_plugin_example"; }; name = Profile; @@ -622,7 +550,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; + MACOSX_DEPLOYMENT_TARGET = 10.15; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = macosx; @@ -669,7 +597,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; + MACOSX_DEPLOYMENT_TARGET = 10.15; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; diff --git a/packages/pigeon/platform_tests/test_plugin/example/macos/RunnerTests/BasicCompileTest.swift b/packages/pigeon/platform_tests/test_plugin/example/macos/RunnerTests/BasicCompileTest.swift index 460ca44580f0..29490574aec1 100644 --- a/packages/pigeon/platform_tests/test_plugin/example/macos/RunnerTests/BasicCompileTest.swift +++ b/packages/pigeon/platform_tests/test_plugin/example/macos/RunnerTests/BasicCompileTest.swift @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import XCTest +import Testing @testable import test_plugin @@ -13,9 +13,10 @@ class MyApi: HostTrivialApi { // Since the generator is almost entirely shared with iOS, this is currently // just testing that the generated code compiles for macOS (e.g., that the // Flutter framework import is correct). -class BasicCompileTest: XCTestCase { - func testMakeApi() { +struct BasicCompileTest { + @Test + func makeApi() { let api = MyApi() - XCTAssertNotNil(api) + #expect(api as Any? != nil) } } diff --git a/packages/pigeon/platform_tests/test_plugin/linux/CMakeLists.txt b/packages/pigeon/platform_tests/test_plugin/linux/CMakeLists.txt index 3d2845f8d3e4..c2cdee101723 100644 --- a/packages/pigeon/platform_tests/test_plugin/linux/CMakeLists.txt +++ b/packages/pigeon/platform_tests/test_plugin/linux/CMakeLists.txt @@ -100,6 +100,7 @@ add_executable(${TEST_RUNNER} test/nullable_returns_test.cc test/null_fields_test.cc test/primitive_test.cc + test/equality_test.cc # Test utilities. test/utils/fake_host_messenger.cc test/utils/fake_host_messenger.h diff --git a/packages/pigeon/platform_tests/test_plugin/linux/pigeon/core_tests.gen.cc b/packages/pigeon/platform_tests/test_plugin/linux/pigeon/core_tests.gen.cc index ae3763bf5e0e..023cd1ed85db 100644 --- a/packages/pigeon/platform_tests/test_plugin/linux/pigeon/core_tests.gen.cc +++ b/packages/pigeon/platform_tests/test_plugin/linux/pigeon/core_tests.gen.cc @@ -7,6 +7,197 @@ #include "core_tests.gen.h" +#include + +#include +static guint G_GNUC_UNUSED flpigeon_hash_double(double v) { + if (std::isnan(v)) { + return static_cast(0x7FF80000); + } + if (v == 0.0) { + v = 0.0; + } + union { + double d; + uint64_t u; + } u; + u.d = v; + return static_cast(u.u ^ (u.u >> 32)); +} +static gboolean G_GNUC_UNUSED flpigeon_equals_double(double a, double b) { + return (a == b) || (std::isnan(a) && std::isnan(b)); +} +static gboolean G_GNUC_UNUSED flpigeon_deep_equals(FlValue* a, FlValue* b) { + if (a == b) { + return TRUE; + } + if (a == nullptr || b == nullptr) { + return FALSE; + } + if (fl_value_get_type(a) != fl_value_get_type(b)) { + return FALSE; + } + switch (fl_value_get_type(a)) { + case FL_VALUE_TYPE_NULL: + return TRUE; + case FL_VALUE_TYPE_BOOL: + return fl_value_get_bool(a) == fl_value_get_bool(b); + case FL_VALUE_TYPE_INT: + return fl_value_get_int(a) == fl_value_get_int(b); + case FL_VALUE_TYPE_FLOAT: { + return flpigeon_equals_double(fl_value_get_float(a), + fl_value_get_float(b)); + } + case FL_VALUE_TYPE_STRING: + return g_strcmp0(fl_value_get_string(a), fl_value_get_string(b)) == 0; + case FL_VALUE_TYPE_UINT8_LIST: + return fl_value_get_length(a) == fl_value_get_length(b) && + memcmp(fl_value_get_uint8_list(a), fl_value_get_uint8_list(b), + fl_value_get_length(a)) == 0; + case FL_VALUE_TYPE_INT32_LIST: + return fl_value_get_length(a) == fl_value_get_length(b) && + memcmp(fl_value_get_int32_list(a), fl_value_get_int32_list(b), + fl_value_get_length(a) * sizeof(int32_t)) == 0; + case FL_VALUE_TYPE_INT64_LIST: + return fl_value_get_length(a) == fl_value_get_length(b) && + memcmp(fl_value_get_int64_list(a), fl_value_get_int64_list(b), + fl_value_get_length(a) * sizeof(int64_t)) == 0; + case FL_VALUE_TYPE_FLOAT_LIST: { + size_t len = fl_value_get_length(a); + if (len != fl_value_get_length(b)) { + return FALSE; + } + const double* a_data = fl_value_get_float_list(a); + const double* b_data = fl_value_get_float_list(b); + for (size_t i = 0; i < len; i++) { + if (!flpigeon_equals_double(a_data[i], b_data[i])) { + return FALSE; + } + } + return TRUE; + } + case FL_VALUE_TYPE_LIST: { + size_t len = fl_value_get_length(a); + if (len != fl_value_get_length(b)) { + return FALSE; + } + for (size_t i = 0; i < len; i++) { + if (!flpigeon_deep_equals(fl_value_get_list_value(a, i), + fl_value_get_list_value(b, i))) { + return FALSE; + } + } + return TRUE; + } + case FL_VALUE_TYPE_MAP: { + size_t len = fl_value_get_length(a); + if (len != fl_value_get_length(b)) { + return FALSE; + } + for (size_t i = 0; i < len; i++) { + FlValue* key = fl_value_get_map_key(a, i); + FlValue* val = fl_value_get_map_value(a, i); + gboolean found = FALSE; + for (size_t j = 0; j < len; j++) { + FlValue* b_key = fl_value_get_map_key(b, j); + if (flpigeon_deep_equals(key, b_key)) { + FlValue* b_val = fl_value_get_map_value(b, j); + if (flpigeon_deep_equals(val, b_val)) { + found = TRUE; + break; + } else { + return FALSE; + } + } + } + if (!found) { + return FALSE; + } + } + return TRUE; + } + default: + return FALSE; + } + return FALSE; +} +static guint G_GNUC_UNUSED flpigeon_deep_hash(FlValue* value) { + if (value == nullptr) { + return 0; + } + switch (fl_value_get_type(value)) { + case FL_VALUE_TYPE_NULL: + return 0; + case FL_VALUE_TYPE_BOOL: + return fl_value_get_bool(value) ? 1231 : 1237; + case FL_VALUE_TYPE_INT: { + int64_t v = fl_value_get_int(value); + return static_cast(v ^ (v >> 32)); + } + case FL_VALUE_TYPE_FLOAT: + return flpigeon_hash_double(fl_value_get_float(value)); + case FL_VALUE_TYPE_STRING: + return g_str_hash(fl_value_get_string(value)); + case FL_VALUE_TYPE_UINT8_LIST: { + guint result = 1; + size_t len = fl_value_get_length(value); + const uint8_t* data = fl_value_get_uint8_list(value); + for (size_t i = 0; i < len; i++) { + result = result * 31 + data[i]; + } + return result; + } + case FL_VALUE_TYPE_INT32_LIST: { + guint result = 1; + size_t len = fl_value_get_length(value); + const int32_t* data = fl_value_get_int32_list(value); + for (size_t i = 0; i < len; i++) { + result = result * 31 + static_cast(data[i]); + } + return result; + } + case FL_VALUE_TYPE_INT64_LIST: { + guint result = 1; + size_t len = fl_value_get_length(value); + const int64_t* data = fl_value_get_int64_list(value); + for (size_t i = 0; i < len; i++) { + result = result * 31 + static_cast(data[i] ^ (data[i] >> 32)); + } + return result; + } + case FL_VALUE_TYPE_FLOAT_LIST: { + guint result = 1; + size_t len = fl_value_get_length(value); + const double* data = fl_value_get_float_list(value); + for (size_t i = 0; i < len; i++) { + result = result * 31 + flpigeon_hash_double(data[i]); + } + return result; + } + case FL_VALUE_TYPE_LIST: { + guint result = 1; + size_t len = fl_value_get_length(value); + for (size_t i = 0; i < len; i++) { + result = + result * 31 + flpigeon_deep_hash(fl_value_get_list_value(value, i)); + } + return result; + } + case FL_VALUE_TYPE_MAP: { + guint result = 0; + size_t len = fl_value_get_length(value); + for (size_t i = 0; i < len; i++) { + result += ((flpigeon_deep_hash(fl_value_get_map_key(value, i)) * 31) ^ + flpigeon_deep_hash(fl_value_get_map_value(value, i))); + } + return result; + } + default: + return static_cast(fl_value_get_type(value)); + } + return 0; +} + struct _CoreTestsPigeonTestUnusedClass { GObject parent_instance; @@ -69,6 +260,28 @@ core_tests_pigeon_test_unused_class_new_from_list(FlValue* values) { return core_tests_pigeon_test_unused_class_new(a_field); } +gboolean core_tests_pigeon_test_unused_class_equals( + CoreTestsPigeonTestUnusedClass* a, CoreTestsPigeonTestUnusedClass* b) { + if (a == b) { + return TRUE; + } + if (a == nullptr || b == nullptr) { + return FALSE; + } + if (!flpigeon_deep_equals(a->a_field, b->a_field)) { + return FALSE; + } + return TRUE; +} + +guint core_tests_pigeon_test_unused_class_hash( + CoreTestsPigeonTestUnusedClass* self) { + g_return_val_if_fail(CORE_TESTS_PIGEON_TEST_IS_UNUSED_CLASS(self), 0); + guint result = 0; + result = result * 31 + flpigeon_deep_hash(self->a_field); + return result; +} + struct _CoreTestsPigeonTestAllTypes { GObject parent_instance; @@ -497,6 +710,205 @@ core_tests_pigeon_test_all_types_new_from_list(FlValue* values) { object_map, list_map, map_map); } +gboolean core_tests_pigeon_test_all_types_equals( + CoreTestsPigeonTestAllTypes* a, CoreTestsPigeonTestAllTypes* b) { + if (a == b) { + return TRUE; + } + if (a == nullptr || b == nullptr) { + return FALSE; + } + if (a->a_bool != b->a_bool) { + return FALSE; + } + if (a->an_int != b->an_int) { + return FALSE; + } + if (a->an_int64 != b->an_int64) { + return FALSE; + } + if (!flpigeon_equals_double(a->a_double, b->a_double)) { + return FALSE; + } + if (a->a_byte_array != b->a_byte_array) { + if (a->a_byte_array == nullptr || b->a_byte_array == nullptr) { + return FALSE; + } + if (a->a_byte_array_length != b->a_byte_array_length) { + return FALSE; + } + if (memcmp(a->a_byte_array, b->a_byte_array, + a->a_byte_array_length * sizeof(uint8_t)) != 0) { + return FALSE; + } + } + if (a->a4_byte_array != b->a4_byte_array) { + if (a->a4_byte_array == nullptr || b->a4_byte_array == nullptr) { + return FALSE; + } + if (a->a4_byte_array_length != b->a4_byte_array_length) { + return FALSE; + } + if (memcmp(a->a4_byte_array, b->a4_byte_array, + a->a4_byte_array_length * sizeof(int32_t)) != 0) { + return FALSE; + } + } + if (a->a8_byte_array != b->a8_byte_array) { + if (a->a8_byte_array == nullptr || b->a8_byte_array == nullptr) { + return FALSE; + } + if (a->a8_byte_array_length != b->a8_byte_array_length) { + return FALSE; + } + if (memcmp(a->a8_byte_array, b->a8_byte_array, + a->a8_byte_array_length * sizeof(int64_t)) != 0) { + return FALSE; + } + } + if (a->a_float_array != b->a_float_array) { + if (a->a_float_array == nullptr || b->a_float_array == nullptr) { + return FALSE; + } + if (a->a_float_array_length != b->a_float_array_length) { + return FALSE; + } + for (size_t i = 0; i < a->a_float_array_length; i++) { + if (!flpigeon_equals_double(a->a_float_array[i], b->a_float_array[i])) { + return FALSE; + } + } + } + if (a->an_enum != b->an_enum) { + return FALSE; + } + if (a->another_enum != b->another_enum) { + return FALSE; + } + if (g_strcmp0(a->a_string, b->a_string) != 0) { + return FALSE; + } + if (!flpigeon_deep_equals(a->an_object, b->an_object)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->list, b->list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->string_list, b->string_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->int_list, b->int_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->double_list, b->double_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->bool_list, b->bool_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->enum_list, b->enum_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->object_list, b->object_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->list_list, b->list_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->map_list, b->map_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->map, b->map)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->string_map, b->string_map)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->int_map, b->int_map)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->enum_map, b->enum_map)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->object_map, b->object_map)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->list_map, b->list_map)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->map_map, b->map_map)) { + return FALSE; + } + return TRUE; +} + +guint core_tests_pigeon_test_all_types_hash(CoreTestsPigeonTestAllTypes* self) { + g_return_val_if_fail(CORE_TESTS_PIGEON_TEST_IS_ALL_TYPES(self), 0); + guint result = 0; + result = result * 31 + static_cast(self->a_bool); + result = result * 31 + static_cast(self->an_int); + result = result * 31 + static_cast(self->an_int64); + result = result * 31 + flpigeon_hash_double(self->a_double); + { + size_t len = self->a_byte_array_length; + const uint8_t* data = self->a_byte_array; + if (data != nullptr) { + for (size_t i = 0; i < len; i++) { + result = result * 31 + static_cast(data[i]); + } + } + } + { + size_t len = self->a4_byte_array_length; + const int32_t* data = self->a4_byte_array; + if (data != nullptr) { + for (size_t i = 0; i < len; i++) { + result = result * 31 + static_cast(data[i]); + } + } + } + { + size_t len = self->a8_byte_array_length; + const int64_t* data = self->a8_byte_array; + if (data != nullptr) { + for (size_t i = 0; i < len; i++) { + result = result * 31 + static_cast(data[i] ^ (data[i] >> 32)); + } + } + } + { + size_t len = self->a_float_array_length; + const double* data = self->a_float_array; + if (data != nullptr) { + for (size_t i = 0; i < len; i++) { + result = result * 31 + flpigeon_hash_double(data[i]); + } + } + } + result = result * 31 + static_cast(self->an_enum); + result = result * 31 + static_cast(self->another_enum); + result = result * 31 + + (self->a_string != nullptr ? g_str_hash(self->a_string) : 0); + result = result * 31 + flpigeon_deep_hash(self->an_object); + result = result * 31 + flpigeon_deep_hash(self->list); + result = result * 31 + flpigeon_deep_hash(self->string_list); + result = result * 31 + flpigeon_deep_hash(self->int_list); + result = result * 31 + flpigeon_deep_hash(self->double_list); + result = result * 31 + flpigeon_deep_hash(self->bool_list); + result = result * 31 + flpigeon_deep_hash(self->enum_list); + result = result * 31 + flpigeon_deep_hash(self->object_list); + result = result * 31 + flpigeon_deep_hash(self->list_list); + result = result * 31 + flpigeon_deep_hash(self->map_list); + result = result * 31 + flpigeon_deep_hash(self->map); + result = result * 31 + flpigeon_deep_hash(self->string_map); + result = result * 31 + flpigeon_deep_hash(self->int_map); + result = result * 31 + flpigeon_deep_hash(self->enum_map); + result = result * 31 + flpigeon_deep_hash(self->object_map); + result = result * 31 + flpigeon_deep_hash(self->list_map); + result = result * 31 + flpigeon_deep_hash(self->map_map); + return result; +} + struct _CoreTestsPigeonTestAllNullableTypes { GObject parent_instance; @@ -1331,6 +1743,264 @@ core_tests_pigeon_test_all_nullable_types_new_from_list(FlValue* values) { recursive_class_map); } +gboolean core_tests_pigeon_test_all_nullable_types_equals( + CoreTestsPigeonTestAllNullableTypes* a, + CoreTestsPigeonTestAllNullableTypes* b) { + if (a == b) { + return TRUE; + } + if (a == nullptr || b == nullptr) { + return FALSE; + } + if ((a->a_nullable_bool == nullptr) != (b->a_nullable_bool == nullptr)) { + return FALSE; + } + if (a->a_nullable_bool != nullptr && + *a->a_nullable_bool != *b->a_nullable_bool) { + return FALSE; + } + if ((a->a_nullable_int == nullptr) != (b->a_nullable_int == nullptr)) { + return FALSE; + } + if (a->a_nullable_int != nullptr && + *a->a_nullable_int != *b->a_nullable_int) { + return FALSE; + } + if ((a->a_nullable_int64 == nullptr) != (b->a_nullable_int64 == nullptr)) { + return FALSE; + } + if (a->a_nullable_int64 != nullptr && + *a->a_nullable_int64 != *b->a_nullable_int64) { + return FALSE; + } + if ((a->a_nullable_double == nullptr) != (b->a_nullable_double == nullptr)) { + return FALSE; + } + if (a->a_nullable_double != nullptr && + !flpigeon_equals_double(*a->a_nullable_double, *b->a_nullable_double)) { + return FALSE; + } + if (a->a_nullable_byte_array != b->a_nullable_byte_array) { + if (a->a_nullable_byte_array == nullptr || + b->a_nullable_byte_array == nullptr) { + return FALSE; + } + if (a->a_nullable_byte_array_length != b->a_nullable_byte_array_length) { + return FALSE; + } + if (memcmp(a->a_nullable_byte_array, b->a_nullable_byte_array, + a->a_nullable_byte_array_length * sizeof(uint8_t)) != 0) { + return FALSE; + } + } + if (a->a_nullable4_byte_array != b->a_nullable4_byte_array) { + if (a->a_nullable4_byte_array == nullptr || + b->a_nullable4_byte_array == nullptr) { + return FALSE; + } + if (a->a_nullable4_byte_array_length != b->a_nullable4_byte_array_length) { + return FALSE; + } + if (memcmp(a->a_nullable4_byte_array, b->a_nullable4_byte_array, + a->a_nullable4_byte_array_length * sizeof(int32_t)) != 0) { + return FALSE; + } + } + if (a->a_nullable8_byte_array != b->a_nullable8_byte_array) { + if (a->a_nullable8_byte_array == nullptr || + b->a_nullable8_byte_array == nullptr) { + return FALSE; + } + if (a->a_nullable8_byte_array_length != b->a_nullable8_byte_array_length) { + return FALSE; + } + if (memcmp(a->a_nullable8_byte_array, b->a_nullable8_byte_array, + a->a_nullable8_byte_array_length * sizeof(int64_t)) != 0) { + return FALSE; + } + } + if (a->a_nullable_float_array != b->a_nullable_float_array) { + if (a->a_nullable_float_array == nullptr || + b->a_nullable_float_array == nullptr) { + return FALSE; + } + if (a->a_nullable_float_array_length != b->a_nullable_float_array_length) { + return FALSE; + } + for (size_t i = 0; i < a->a_nullable_float_array_length; i++) { + if (!flpigeon_equals_double(a->a_nullable_float_array[i], + b->a_nullable_float_array[i])) { + return FALSE; + } + } + } + if ((a->a_nullable_enum == nullptr) != (b->a_nullable_enum == nullptr)) { + return FALSE; + } + if (a->a_nullable_enum != nullptr && + *a->a_nullable_enum != *b->a_nullable_enum) { + return FALSE; + } + if ((a->another_nullable_enum == nullptr) != + (b->another_nullable_enum == nullptr)) { + return FALSE; + } + if (a->another_nullable_enum != nullptr && + *a->another_nullable_enum != *b->another_nullable_enum) { + return FALSE; + } + if (g_strcmp0(a->a_nullable_string, b->a_nullable_string) != 0) { + return FALSE; + } + if (!flpigeon_deep_equals(a->a_nullable_object, b->a_nullable_object)) { + return FALSE; + } + if (!core_tests_pigeon_test_all_nullable_types_equals( + a->all_nullable_types, b->all_nullable_types)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->list, b->list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->string_list, b->string_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->int_list, b->int_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->double_list, b->double_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->bool_list, b->bool_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->enum_list, b->enum_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->object_list, b->object_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->list_list, b->list_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->map_list, b->map_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->recursive_class_list, b->recursive_class_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->map, b->map)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->string_map, b->string_map)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->int_map, b->int_map)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->enum_map, b->enum_map)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->object_map, b->object_map)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->list_map, b->list_map)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->map_map, b->map_map)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->recursive_class_map, b->recursive_class_map)) { + return FALSE; + } + return TRUE; +} + +guint core_tests_pigeon_test_all_nullable_types_hash( + CoreTestsPigeonTestAllNullableTypes* self) { + g_return_val_if_fail(CORE_TESTS_PIGEON_TEST_IS_ALL_NULLABLE_TYPES(self), 0); + guint result = 0; + result = result * 31 + (self->a_nullable_bool != nullptr + ? static_cast(*self->a_nullable_bool) + : 0); + result = result * 31 + (self->a_nullable_int != nullptr + ? static_cast(*self->a_nullable_int) + : 0); + result = result * 31 + (self->a_nullable_int64 != nullptr + ? static_cast(*self->a_nullable_int64) + : 0); + result = result * 31 + (self->a_nullable_double != nullptr + ? flpigeon_hash_double(*self->a_nullable_double) + : 0); + { + size_t len = self->a_nullable_byte_array_length; + const uint8_t* data = self->a_nullable_byte_array; + if (data != nullptr) { + for (size_t i = 0; i < len; i++) { + result = result * 31 + static_cast(data[i]); + } + } + } + { + size_t len = self->a_nullable4_byte_array_length; + const int32_t* data = self->a_nullable4_byte_array; + if (data != nullptr) { + for (size_t i = 0; i < len; i++) { + result = result * 31 + static_cast(data[i]); + } + } + } + { + size_t len = self->a_nullable8_byte_array_length; + const int64_t* data = self->a_nullable8_byte_array; + if (data != nullptr) { + for (size_t i = 0; i < len; i++) { + result = result * 31 + static_cast(data[i] ^ (data[i] >> 32)); + } + } + } + { + size_t len = self->a_nullable_float_array_length; + const double* data = self->a_nullable_float_array; + if (data != nullptr) { + for (size_t i = 0; i < len; i++) { + result = result * 31 + flpigeon_hash_double(data[i]); + } + } + } + result = result * 31 + (self->a_nullable_enum != nullptr + ? static_cast(*self->a_nullable_enum) + : 0); + result = result * 31 + (self->another_nullable_enum != nullptr + ? static_cast(*self->another_nullable_enum) + : 0); + result = result * 31 + (self->a_nullable_string != nullptr + ? g_str_hash(self->a_nullable_string) + : 0); + result = result * 31 + flpigeon_deep_hash(self->a_nullable_object); + result = result * 31 + core_tests_pigeon_test_all_nullable_types_hash( + self->all_nullable_types); + result = result * 31 + flpigeon_deep_hash(self->list); + result = result * 31 + flpigeon_deep_hash(self->string_list); + result = result * 31 + flpigeon_deep_hash(self->int_list); + result = result * 31 + flpigeon_deep_hash(self->double_list); + result = result * 31 + flpigeon_deep_hash(self->bool_list); + result = result * 31 + flpigeon_deep_hash(self->enum_list); + result = result * 31 + flpigeon_deep_hash(self->object_list); + result = result * 31 + flpigeon_deep_hash(self->list_list); + result = result * 31 + flpigeon_deep_hash(self->map_list); + result = result * 31 + flpigeon_deep_hash(self->recursive_class_list); + result = result * 31 + flpigeon_deep_hash(self->map); + result = result * 31 + flpigeon_deep_hash(self->string_map); + result = result * 31 + flpigeon_deep_hash(self->int_map); + result = result * 31 + flpigeon_deep_hash(self->enum_map); + result = result * 31 + flpigeon_deep_hash(self->object_map); + result = result * 31 + flpigeon_deep_hash(self->list_map); + result = result * 31 + flpigeon_deep_hash(self->map_map); + result = result * 31 + flpigeon_deep_hash(self->recursive_class_map); + return result; +} + struct _CoreTestsPigeonTestAllNullableTypesWithoutRecursion { GObject parent_instance; @@ -2145,6 +2815,251 @@ core_tests_pigeon_test_all_nullable_types_without_recursion_new_from_list( list_map, map_map); } +gboolean core_tests_pigeon_test_all_nullable_types_without_recursion_equals( + CoreTestsPigeonTestAllNullableTypesWithoutRecursion* a, + CoreTestsPigeonTestAllNullableTypesWithoutRecursion* b) { + if (a == b) { + return TRUE; + } + if (a == nullptr || b == nullptr) { + return FALSE; + } + if ((a->a_nullable_bool == nullptr) != (b->a_nullable_bool == nullptr)) { + return FALSE; + } + if (a->a_nullable_bool != nullptr && + *a->a_nullable_bool != *b->a_nullable_bool) { + return FALSE; + } + if ((a->a_nullable_int == nullptr) != (b->a_nullable_int == nullptr)) { + return FALSE; + } + if (a->a_nullable_int != nullptr && + *a->a_nullable_int != *b->a_nullable_int) { + return FALSE; + } + if ((a->a_nullable_int64 == nullptr) != (b->a_nullable_int64 == nullptr)) { + return FALSE; + } + if (a->a_nullable_int64 != nullptr && + *a->a_nullable_int64 != *b->a_nullable_int64) { + return FALSE; + } + if ((a->a_nullable_double == nullptr) != (b->a_nullable_double == nullptr)) { + return FALSE; + } + if (a->a_nullable_double != nullptr && + !flpigeon_equals_double(*a->a_nullable_double, *b->a_nullable_double)) { + return FALSE; + } + if (a->a_nullable_byte_array != b->a_nullable_byte_array) { + if (a->a_nullable_byte_array == nullptr || + b->a_nullable_byte_array == nullptr) { + return FALSE; + } + if (a->a_nullable_byte_array_length != b->a_nullable_byte_array_length) { + return FALSE; + } + if (memcmp(a->a_nullable_byte_array, b->a_nullable_byte_array, + a->a_nullable_byte_array_length * sizeof(uint8_t)) != 0) { + return FALSE; + } + } + if (a->a_nullable4_byte_array != b->a_nullable4_byte_array) { + if (a->a_nullable4_byte_array == nullptr || + b->a_nullable4_byte_array == nullptr) { + return FALSE; + } + if (a->a_nullable4_byte_array_length != b->a_nullable4_byte_array_length) { + return FALSE; + } + if (memcmp(a->a_nullable4_byte_array, b->a_nullable4_byte_array, + a->a_nullable4_byte_array_length * sizeof(int32_t)) != 0) { + return FALSE; + } + } + if (a->a_nullable8_byte_array != b->a_nullable8_byte_array) { + if (a->a_nullable8_byte_array == nullptr || + b->a_nullable8_byte_array == nullptr) { + return FALSE; + } + if (a->a_nullable8_byte_array_length != b->a_nullable8_byte_array_length) { + return FALSE; + } + if (memcmp(a->a_nullable8_byte_array, b->a_nullable8_byte_array, + a->a_nullable8_byte_array_length * sizeof(int64_t)) != 0) { + return FALSE; + } + } + if (a->a_nullable_float_array != b->a_nullable_float_array) { + if (a->a_nullable_float_array == nullptr || + b->a_nullable_float_array == nullptr) { + return FALSE; + } + if (a->a_nullable_float_array_length != b->a_nullable_float_array_length) { + return FALSE; + } + for (size_t i = 0; i < a->a_nullable_float_array_length; i++) { + if (!flpigeon_equals_double(a->a_nullable_float_array[i], + b->a_nullable_float_array[i])) { + return FALSE; + } + } + } + if ((a->a_nullable_enum == nullptr) != (b->a_nullable_enum == nullptr)) { + return FALSE; + } + if (a->a_nullable_enum != nullptr && + *a->a_nullable_enum != *b->a_nullable_enum) { + return FALSE; + } + if ((a->another_nullable_enum == nullptr) != + (b->another_nullable_enum == nullptr)) { + return FALSE; + } + if (a->another_nullable_enum != nullptr && + *a->another_nullable_enum != *b->another_nullable_enum) { + return FALSE; + } + if (g_strcmp0(a->a_nullable_string, b->a_nullable_string) != 0) { + return FALSE; + } + if (!flpigeon_deep_equals(a->a_nullable_object, b->a_nullable_object)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->list, b->list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->string_list, b->string_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->int_list, b->int_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->double_list, b->double_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->bool_list, b->bool_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->enum_list, b->enum_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->object_list, b->object_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->list_list, b->list_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->map_list, b->map_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->map, b->map)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->string_map, b->string_map)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->int_map, b->int_map)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->enum_map, b->enum_map)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->object_map, b->object_map)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->list_map, b->list_map)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->map_map, b->map_map)) { + return FALSE; + } + return TRUE; +} + +guint core_tests_pigeon_test_all_nullable_types_without_recursion_hash( + CoreTestsPigeonTestAllNullableTypesWithoutRecursion* self) { + g_return_val_if_fail( + CORE_TESTS_PIGEON_TEST_IS_ALL_NULLABLE_TYPES_WITHOUT_RECURSION(self), 0); + guint result = 0; + result = result * 31 + (self->a_nullable_bool != nullptr + ? static_cast(*self->a_nullable_bool) + : 0); + result = result * 31 + (self->a_nullable_int != nullptr + ? static_cast(*self->a_nullable_int) + : 0); + result = result * 31 + (self->a_nullable_int64 != nullptr + ? static_cast(*self->a_nullable_int64) + : 0); + result = result * 31 + (self->a_nullable_double != nullptr + ? flpigeon_hash_double(*self->a_nullable_double) + : 0); + { + size_t len = self->a_nullable_byte_array_length; + const uint8_t* data = self->a_nullable_byte_array; + if (data != nullptr) { + for (size_t i = 0; i < len; i++) { + result = result * 31 + static_cast(data[i]); + } + } + } + { + size_t len = self->a_nullable4_byte_array_length; + const int32_t* data = self->a_nullable4_byte_array; + if (data != nullptr) { + for (size_t i = 0; i < len; i++) { + result = result * 31 + static_cast(data[i]); + } + } + } + { + size_t len = self->a_nullable8_byte_array_length; + const int64_t* data = self->a_nullable8_byte_array; + if (data != nullptr) { + for (size_t i = 0; i < len; i++) { + result = result * 31 + static_cast(data[i] ^ (data[i] >> 32)); + } + } + } + { + size_t len = self->a_nullable_float_array_length; + const double* data = self->a_nullable_float_array; + if (data != nullptr) { + for (size_t i = 0; i < len; i++) { + result = result * 31 + flpigeon_hash_double(data[i]); + } + } + } + result = result * 31 + (self->a_nullable_enum != nullptr + ? static_cast(*self->a_nullable_enum) + : 0); + result = result * 31 + (self->another_nullable_enum != nullptr + ? static_cast(*self->another_nullable_enum) + : 0); + result = result * 31 + (self->a_nullable_string != nullptr + ? g_str_hash(self->a_nullable_string) + : 0); + result = result * 31 + flpigeon_deep_hash(self->a_nullable_object); + result = result * 31 + flpigeon_deep_hash(self->list); + result = result * 31 + flpigeon_deep_hash(self->string_list); + result = result * 31 + flpigeon_deep_hash(self->int_list); + result = result * 31 + flpigeon_deep_hash(self->double_list); + result = result * 31 + flpigeon_deep_hash(self->bool_list); + result = result * 31 + flpigeon_deep_hash(self->enum_list); + result = result * 31 + flpigeon_deep_hash(self->object_list); + result = result * 31 + flpigeon_deep_hash(self->list_list); + result = result * 31 + flpigeon_deep_hash(self->map_list); + result = result * 31 + flpigeon_deep_hash(self->map); + result = result * 31 + flpigeon_deep_hash(self->string_map); + result = result * 31 + flpigeon_deep_hash(self->int_map); + result = result * 31 + flpigeon_deep_hash(self->enum_map); + result = result * 31 + flpigeon_deep_hash(self->object_map); + result = result * 31 + flpigeon_deep_hash(self->list_map); + result = result * 31 + flpigeon_deep_hash(self->map_map); + return result; +} + struct _CoreTestsPigeonTestAllClassesWrapper { GObject parent_instance; @@ -2347,6 +3262,59 @@ core_tests_pigeon_test_all_classes_wrapper_new_from_list(FlValue* values) { class_list, nullable_class_list, class_map, nullable_class_map); } +gboolean core_tests_pigeon_test_all_classes_wrapper_equals( + CoreTestsPigeonTestAllClassesWrapper* a, + CoreTestsPigeonTestAllClassesWrapper* b) { + if (a == b) { + return TRUE; + } + if (a == nullptr || b == nullptr) { + return FALSE; + } + if (!core_tests_pigeon_test_all_nullable_types_equals( + a->all_nullable_types, b->all_nullable_types)) { + return FALSE; + } + if (!core_tests_pigeon_test_all_nullable_types_without_recursion_equals( + a->all_nullable_types_without_recursion, + b->all_nullable_types_without_recursion)) { + return FALSE; + } + if (!core_tests_pigeon_test_all_types_equals(a->all_types, b->all_types)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->class_list, b->class_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->nullable_class_list, b->nullable_class_list)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->class_map, b->class_map)) { + return FALSE; + } + if (!flpigeon_deep_equals(a->nullable_class_map, b->nullable_class_map)) { + return FALSE; + } + return TRUE; +} + +guint core_tests_pigeon_test_all_classes_wrapper_hash( + CoreTestsPigeonTestAllClassesWrapper* self) { + g_return_val_if_fail(CORE_TESTS_PIGEON_TEST_IS_ALL_CLASSES_WRAPPER(self), 0); + guint result = 0; + result = result * 31 + core_tests_pigeon_test_all_nullable_types_hash( + self->all_nullable_types); + result = result * 31 + + core_tests_pigeon_test_all_nullable_types_without_recursion_hash( + self->all_nullable_types_without_recursion); + result = result * 31 + core_tests_pigeon_test_all_types_hash(self->all_types); + result = result * 31 + flpigeon_deep_hash(self->class_list); + result = result * 31 + flpigeon_deep_hash(self->nullable_class_list); + result = result * 31 + flpigeon_deep_hash(self->class_map); + result = result * 31 + flpigeon_deep_hash(self->nullable_class_map); + return result; +} + struct _CoreTestsPigeonTestTestMessage { GObject parent_instance; @@ -2409,6 +3377,28 @@ core_tests_pigeon_test_test_message_new_from_list(FlValue* values) { return core_tests_pigeon_test_test_message_new(test_list); } +gboolean core_tests_pigeon_test_test_message_equals( + CoreTestsPigeonTestTestMessage* a, CoreTestsPigeonTestTestMessage* b) { + if (a == b) { + return TRUE; + } + if (a == nullptr || b == nullptr) { + return FALSE; + } + if (!flpigeon_deep_equals(a->test_list, b->test_list)) { + return FALSE; + } + return TRUE; +} + +guint core_tests_pigeon_test_test_message_hash( + CoreTestsPigeonTestTestMessage* self) { + g_return_val_if_fail(CORE_TESTS_PIGEON_TEST_IS_TEST_MESSAGE(self), 0); + guint result = 0; + result = result * 31 + flpigeon_deep_hash(self->test_list); + return result; +} + struct _CoreTestsPigeonTestMessageCodec { FlStandardMessageCodec parent_instance; }; @@ -4840,6 +5830,208 @@ core_tests_pigeon_test_host_integration_core_api_echo_required_int_response_new_ return self; } +struct + _CoreTestsPigeonTestHostIntegrationCoreApiAreAllNullableTypesEqualResponse { + GObject parent_instance; + + FlValue* value; +}; + +G_DEFINE_TYPE( + CoreTestsPigeonTestHostIntegrationCoreApiAreAllNullableTypesEqualResponse, + core_tests_pigeon_test_host_integration_core_api_are_all_nullable_types_equal_response, + G_TYPE_OBJECT) + +static void +core_tests_pigeon_test_host_integration_core_api_are_all_nullable_types_equal_response_dispose( + GObject* object) { + CoreTestsPigeonTestHostIntegrationCoreApiAreAllNullableTypesEqualResponse* self = + CORE_TESTS_PIGEON_TEST_HOST_INTEGRATION_CORE_API_ARE_ALL_NULLABLE_TYPES_EQUAL_RESPONSE( + object); + g_clear_pointer(&self->value, fl_value_unref); + G_OBJECT_CLASS( + core_tests_pigeon_test_host_integration_core_api_are_all_nullable_types_equal_response_parent_class) + ->dispose(object); +} + +static void +core_tests_pigeon_test_host_integration_core_api_are_all_nullable_types_equal_response_init( + CoreTestsPigeonTestHostIntegrationCoreApiAreAllNullableTypesEqualResponse* + self) {} + +static void +core_tests_pigeon_test_host_integration_core_api_are_all_nullable_types_equal_response_class_init( + CoreTestsPigeonTestHostIntegrationCoreApiAreAllNullableTypesEqualResponseClass* + klass) { + G_OBJECT_CLASS(klass)->dispose = + core_tests_pigeon_test_host_integration_core_api_are_all_nullable_types_equal_response_dispose; +} + +CoreTestsPigeonTestHostIntegrationCoreApiAreAllNullableTypesEqualResponse* +core_tests_pigeon_test_host_integration_core_api_are_all_nullable_types_equal_response_new( + gboolean return_value) { + CoreTestsPigeonTestHostIntegrationCoreApiAreAllNullableTypesEqualResponse* self = + CORE_TESTS_PIGEON_TEST_HOST_INTEGRATION_CORE_API_ARE_ALL_NULLABLE_TYPES_EQUAL_RESPONSE( + g_object_new( + core_tests_pigeon_test_host_integration_core_api_are_all_nullable_types_equal_response_get_type(), + nullptr)); + self->value = fl_value_new_list(); + fl_value_append_take(self->value, fl_value_new_bool(return_value)); + return self; +} + +CoreTestsPigeonTestHostIntegrationCoreApiAreAllNullableTypesEqualResponse* +core_tests_pigeon_test_host_integration_core_api_are_all_nullable_types_equal_response_new_error( + const gchar* code, const gchar* message, FlValue* details) { + CoreTestsPigeonTestHostIntegrationCoreApiAreAllNullableTypesEqualResponse* self = + CORE_TESTS_PIGEON_TEST_HOST_INTEGRATION_CORE_API_ARE_ALL_NULLABLE_TYPES_EQUAL_RESPONSE( + g_object_new( + core_tests_pigeon_test_host_integration_core_api_are_all_nullable_types_equal_response_get_type(), + nullptr)); + self->value = fl_value_new_list(); + fl_value_append_take(self->value, fl_value_new_string(code)); + fl_value_append_take(self->value, + fl_value_new_string(message != nullptr ? message : "")); + fl_value_append_take(self->value, details != nullptr ? fl_value_ref(details) + : fl_value_new_null()); + return self; +} + +struct + _CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesHashResponse { + GObject parent_instance; + + FlValue* value; +}; + +G_DEFINE_TYPE( + CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesHashResponse, + core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_hash_response, + G_TYPE_OBJECT) + +static void +core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_hash_response_dispose( + GObject* object) { + CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesHashResponse* self = + CORE_TESTS_PIGEON_TEST_HOST_INTEGRATION_CORE_API_GET_ALL_NULLABLE_TYPES_HASH_RESPONSE( + object); + g_clear_pointer(&self->value, fl_value_unref); + G_OBJECT_CLASS( + core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_hash_response_parent_class) + ->dispose(object); +} + +static void +core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_hash_response_init( + CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesHashResponse* + self) {} + +static void +core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_hash_response_class_init( + CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesHashResponseClass* + klass) { + G_OBJECT_CLASS(klass)->dispose = + core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_hash_response_dispose; +} + +CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesHashResponse* +core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_hash_response_new( + int64_t return_value) { + CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesHashResponse* self = + CORE_TESTS_PIGEON_TEST_HOST_INTEGRATION_CORE_API_GET_ALL_NULLABLE_TYPES_HASH_RESPONSE( + g_object_new( + core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_hash_response_get_type(), + nullptr)); + self->value = fl_value_new_list(); + fl_value_append_take(self->value, fl_value_new_int(return_value)); + return self; +} + +CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesHashResponse* +core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_hash_response_new_error( + const gchar* code, const gchar* message, FlValue* details) { + CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesHashResponse* self = + CORE_TESTS_PIGEON_TEST_HOST_INTEGRATION_CORE_API_GET_ALL_NULLABLE_TYPES_HASH_RESPONSE( + g_object_new( + core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_hash_response_get_type(), + nullptr)); + self->value = fl_value_new_list(); + fl_value_append_take(self->value, fl_value_new_string(code)); + fl_value_append_take(self->value, + fl_value_new_string(message != nullptr ? message : "")); + fl_value_append_take(self->value, details != nullptr ? fl_value_ref(details) + : fl_value_new_null()); + return self; +} + +struct + _CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesWithoutRecursionHashResponse { + GObject parent_instance; + + FlValue* value; +}; + +G_DEFINE_TYPE( + CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesWithoutRecursionHashResponse, + core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_without_recursion_hash_response, + G_TYPE_OBJECT) + +static void +core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_without_recursion_hash_response_dispose( + GObject* object) { + CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesWithoutRecursionHashResponse* + self = + CORE_TESTS_PIGEON_TEST_HOST_INTEGRATION_CORE_API_GET_ALL_NULLABLE_TYPES_WITHOUT_RECURSION_HASH_RESPONSE( + object); + g_clear_pointer(&self->value, fl_value_unref); + G_OBJECT_CLASS( + core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_without_recursion_hash_response_parent_class) + ->dispose(object); +} + +static void +core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_without_recursion_hash_response_init( + CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesWithoutRecursionHashResponse* + self) {} + +static void +core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_without_recursion_hash_response_class_init( + CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesWithoutRecursionHashResponseClass* + klass) { + G_OBJECT_CLASS(klass)->dispose = + core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_without_recursion_hash_response_dispose; +} + +CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesWithoutRecursionHashResponse* +core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_without_recursion_hash_response_new( + int64_t return_value) { + CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesWithoutRecursionHashResponse* + self = CORE_TESTS_PIGEON_TEST_HOST_INTEGRATION_CORE_API_GET_ALL_NULLABLE_TYPES_WITHOUT_RECURSION_HASH_RESPONSE( + g_object_new( + core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_without_recursion_hash_response_get_type(), + nullptr)); + self->value = fl_value_new_list(); + fl_value_append_take(self->value, fl_value_new_int(return_value)); + return self; +} + +CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesWithoutRecursionHashResponse* +core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_without_recursion_hash_response_new_error( + const gchar* code, const gchar* message, FlValue* details) { + CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesWithoutRecursionHashResponse* + self = CORE_TESTS_PIGEON_TEST_HOST_INTEGRATION_CORE_API_GET_ALL_NULLABLE_TYPES_WITHOUT_RECURSION_HASH_RESPONSE( + g_object_new( + core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_without_recursion_hash_response_get_type(), + nullptr)); + self->value = fl_value_new_list(); + fl_value_append_take(self->value, fl_value_new_string(code)); + fl_value_append_take(self->value, + fl_value_new_string(message != nullptr ? message : "")); + fl_value_append_take(self->value, details != nullptr ? fl_value_ref(details) + : fl_value_new_null()); + return self; +} + struct _CoreTestsPigeonTestHostIntegrationCoreApiEchoAllNullableTypesResponse { GObject parent_instance; @@ -14726,6 +15918,112 @@ core_tests_pigeon_test_host_integration_core_api_echo_required_int_cb( } } +static void +core_tests_pigeon_test_host_integration_core_api_are_all_nullable_types_equal_cb( + FlBasicMessageChannel* channel, FlValue* message_, + FlBasicMessageChannelResponseHandle* response_handle, gpointer user_data) { + CoreTestsPigeonTestHostIntegrationCoreApi* self = + CORE_TESTS_PIGEON_TEST_HOST_INTEGRATION_CORE_API(user_data); + + if (self->vtable == nullptr || + self->vtable->are_all_nullable_types_equal == nullptr) { + return; + } + + FlValue* value0 = fl_value_get_list_value(message_, 0); + CoreTestsPigeonTestAllNullableTypes* a = + CORE_TESTS_PIGEON_TEST_ALL_NULLABLE_TYPES( + fl_value_get_custom_value_object(value0)); + FlValue* value1 = fl_value_get_list_value(message_, 1); + CoreTestsPigeonTestAllNullableTypes* b = + CORE_TESTS_PIGEON_TEST_ALL_NULLABLE_TYPES( + fl_value_get_custom_value_object(value1)); + g_autoptr( + CoreTestsPigeonTestHostIntegrationCoreApiAreAllNullableTypesEqualResponse) + response = + self->vtable->are_all_nullable_types_equal(a, b, self->user_data); + if (response == nullptr) { + g_warning("No response returned to %s.%s", "HostIntegrationCoreApi", + "areAllNullableTypesEqual"); + return; + } + + g_autoptr(GError) error = NULL; + if (!fl_basic_message_channel_respond(channel, response_handle, + response->value, &error)) { + g_warning("Failed to send response to %s.%s: %s", "HostIntegrationCoreApi", + "areAllNullableTypesEqual", error->message); + } +} + +static void +core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_hash_cb( + FlBasicMessageChannel* channel, FlValue* message_, + FlBasicMessageChannelResponseHandle* response_handle, gpointer user_data) { + CoreTestsPigeonTestHostIntegrationCoreApi* self = + CORE_TESTS_PIGEON_TEST_HOST_INTEGRATION_CORE_API(user_data); + + if (self->vtable == nullptr || + self->vtable->get_all_nullable_types_hash == nullptr) { + return; + } + + FlValue* value0 = fl_value_get_list_value(message_, 0); + CoreTestsPigeonTestAllNullableTypes* value = + CORE_TESTS_PIGEON_TEST_ALL_NULLABLE_TYPES( + fl_value_get_custom_value_object(value0)); + g_autoptr( + CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesHashResponse) + response = + self->vtable->get_all_nullable_types_hash(value, self->user_data); + if (response == nullptr) { + g_warning("No response returned to %s.%s", "HostIntegrationCoreApi", + "getAllNullableTypesHash"); + return; + } + + g_autoptr(GError) error = NULL; + if (!fl_basic_message_channel_respond(channel, response_handle, + response->value, &error)) { + g_warning("Failed to send response to %s.%s: %s", "HostIntegrationCoreApi", + "getAllNullableTypesHash", error->message); + } +} + +static void +core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_without_recursion_hash_cb( + FlBasicMessageChannel* channel, FlValue* message_, + FlBasicMessageChannelResponseHandle* response_handle, gpointer user_data) { + CoreTestsPigeonTestHostIntegrationCoreApi* self = + CORE_TESTS_PIGEON_TEST_HOST_INTEGRATION_CORE_API(user_data); + + if (self->vtable == nullptr || + self->vtable->get_all_nullable_types_without_recursion_hash == nullptr) { + return; + } + + FlValue* value0 = fl_value_get_list_value(message_, 0); + CoreTestsPigeonTestAllNullableTypesWithoutRecursion* value = + CORE_TESTS_PIGEON_TEST_ALL_NULLABLE_TYPES_WITHOUT_RECURSION( + fl_value_get_custom_value_object(value0)); + g_autoptr( + CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesWithoutRecursionHashResponse) + response = self->vtable->get_all_nullable_types_without_recursion_hash( + value, self->user_data); + if (response == nullptr) { + g_warning("No response returned to %s.%s", "HostIntegrationCoreApi", + "getAllNullableTypesWithoutRecursionHash"); + return; + } + + g_autoptr(GError) error = NULL; + if (!fl_basic_message_channel_respond(channel, response_handle, + response->value, &error)) { + g_warning("Failed to send response to %s.%s: %s", "HostIntegrationCoreApi", + "getAllNullableTypesWithoutRecursionHash", error->message); + } +} + static void core_tests_pigeon_test_host_integration_core_api_echo_all_nullable_types_cb( FlBasicMessageChannel* channel, FlValue* message_, @@ -18082,6 +19380,45 @@ void core_tests_pigeon_test_host_integration_core_api_set_method_handlers( echo_required_int_channel, core_tests_pigeon_test_host_integration_core_api_echo_required_int_cb, g_object_ref(api_data), g_object_unref); + g_autofree gchar* are_all_nullable_types_equal_channel_name = g_strdup_printf( + "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." + "areAllNullableTypesEqual%s", + dot_suffix); + g_autoptr(FlBasicMessageChannel) are_all_nullable_types_equal_channel = + fl_basic_message_channel_new(messenger, + are_all_nullable_types_equal_channel_name, + FL_MESSAGE_CODEC(codec)); + fl_basic_message_channel_set_message_handler( + are_all_nullable_types_equal_channel, + core_tests_pigeon_test_host_integration_core_api_are_all_nullable_types_equal_cb, + g_object_ref(api_data), g_object_unref); + g_autofree gchar* get_all_nullable_types_hash_channel_name = g_strdup_printf( + "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." + "getAllNullableTypesHash%s", + dot_suffix); + g_autoptr(FlBasicMessageChannel) get_all_nullable_types_hash_channel = + fl_basic_message_channel_new(messenger, + get_all_nullable_types_hash_channel_name, + FL_MESSAGE_CODEC(codec)); + fl_basic_message_channel_set_message_handler( + get_all_nullable_types_hash_channel, + core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_hash_cb, + g_object_ref(api_data), g_object_unref); + g_autofree gchar* get_all_nullable_types_without_recursion_hash_channel_name = + g_strdup_printf( + "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." + "getAllNullableTypesWithoutRecursionHash%s", + dot_suffix); + g_autoptr(FlBasicMessageChannel) + get_all_nullable_types_without_recursion_hash_channel = + fl_basic_message_channel_new( + messenger, + get_all_nullable_types_without_recursion_hash_channel_name, + FL_MESSAGE_CODEC(codec)); + fl_basic_message_channel_set_message_handler( + get_all_nullable_types_without_recursion_hash_channel, + core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_without_recursion_hash_cb, + g_object_ref(api_data), g_object_unref); g_autofree gchar* echo_all_nullable_types_channel_name = g_strdup_printf( "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "echoAllNullableTypes%s", @@ -19917,6 +21254,40 @@ void core_tests_pigeon_test_host_integration_core_api_clear_method_handlers( FL_MESSAGE_CODEC(codec)); fl_basic_message_channel_set_message_handler(echo_required_int_channel, nullptr, nullptr, nullptr); + g_autofree gchar* are_all_nullable_types_equal_channel_name = g_strdup_printf( + "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." + "areAllNullableTypesEqual%s", + dot_suffix); + g_autoptr(FlBasicMessageChannel) are_all_nullable_types_equal_channel = + fl_basic_message_channel_new(messenger, + are_all_nullable_types_equal_channel_name, + FL_MESSAGE_CODEC(codec)); + fl_basic_message_channel_set_message_handler( + are_all_nullable_types_equal_channel, nullptr, nullptr, nullptr); + g_autofree gchar* get_all_nullable_types_hash_channel_name = g_strdup_printf( + "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." + "getAllNullableTypesHash%s", + dot_suffix); + g_autoptr(FlBasicMessageChannel) get_all_nullable_types_hash_channel = + fl_basic_message_channel_new(messenger, + get_all_nullable_types_hash_channel_name, + FL_MESSAGE_CODEC(codec)); + fl_basic_message_channel_set_message_handler( + get_all_nullable_types_hash_channel, nullptr, nullptr, nullptr); + g_autofree gchar* get_all_nullable_types_without_recursion_hash_channel_name = + g_strdup_printf( + "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." + "getAllNullableTypesWithoutRecursionHash%s", + dot_suffix); + g_autoptr(FlBasicMessageChannel) + get_all_nullable_types_without_recursion_hash_channel = + fl_basic_message_channel_new( + messenger, + get_all_nullable_types_without_recursion_hash_channel_name, + FL_MESSAGE_CODEC(codec)); + fl_basic_message_channel_set_message_handler( + get_all_nullable_types_without_recursion_hash_channel, nullptr, nullptr, + nullptr); g_autofree gchar* echo_all_nullable_types_channel_name = g_strdup_printf( "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "echoAllNullableTypes%s", diff --git a/packages/pigeon/platform_tests/test_plugin/linux/pigeon/core_tests.gen.h b/packages/pigeon/platform_tests/test_plugin/linux/pigeon/core_tests.gen.h index f0f342e75439..322b9bc8a6b5 100644 --- a/packages/pigeon/platform_tests/test_plugin/linux/pigeon/core_tests.gen.h +++ b/packages/pigeon/platform_tests/test_plugin/linux/pigeon/core_tests.gen.h @@ -69,6 +69,29 @@ CoreTestsPigeonTestUnusedClass* core_tests_pigeon_test_unused_class_new( FlValue* core_tests_pigeon_test_unused_class_get_a_field( CoreTestsPigeonTestUnusedClass* object); +/** + * core_tests_pigeon_test_unused_class_equals: + * @a: a #CoreTestsPigeonTestUnusedClass. + * @b: another #CoreTestsPigeonTestUnusedClass. + * + * Checks if two #CoreTestsPigeonTestUnusedClass objects are equal. + * + * Returns: TRUE if @a and @b are equal. + */ +gboolean core_tests_pigeon_test_unused_class_equals( + CoreTestsPigeonTestUnusedClass* a, CoreTestsPigeonTestUnusedClass* b); + +/** + * core_tests_pigeon_test_unused_class_hash: + * @object: a #CoreTestsPigeonTestUnusedClass. + * + * Calculates a hash code for a #CoreTestsPigeonTestUnusedClass object. + * + * Returns: the hash code. + */ +guint core_tests_pigeon_test_unused_class_hash( + CoreTestsPigeonTestUnusedClass* object); + /** * CoreTestsPigeonTestAllTypes: * @@ -445,6 +468,29 @@ FlValue* core_tests_pigeon_test_all_types_get_list_map( FlValue* core_tests_pigeon_test_all_types_get_map_map( CoreTestsPigeonTestAllTypes* object); +/** + * core_tests_pigeon_test_all_types_equals: + * @a: a #CoreTestsPigeonTestAllTypes. + * @b: another #CoreTestsPigeonTestAllTypes. + * + * Checks if two #CoreTestsPigeonTestAllTypes objects are equal. + * + * Returns: TRUE if @a and @b are equal. + */ +gboolean core_tests_pigeon_test_all_types_equals( + CoreTestsPigeonTestAllTypes* a, CoreTestsPigeonTestAllTypes* b); + +/** + * core_tests_pigeon_test_all_types_hash: + * @object: a #CoreTestsPigeonTestAllTypes. + * + * Calculates a hash code for a #CoreTestsPigeonTestAllTypes object. + * + * Returns: the hash code. + */ +guint core_tests_pigeon_test_all_types_hash( + CoreTestsPigeonTestAllTypes* object); + /** * CoreTestsPigeonTestAllNullableTypes: * @@ -868,6 +914,30 @@ FlValue* core_tests_pigeon_test_all_nullable_types_get_map_map( FlValue* core_tests_pigeon_test_all_nullable_types_get_recursive_class_map( CoreTestsPigeonTestAllNullableTypes* object); +/** + * core_tests_pigeon_test_all_nullable_types_equals: + * @a: a #CoreTestsPigeonTestAllNullableTypes. + * @b: another #CoreTestsPigeonTestAllNullableTypes. + * + * Checks if two #CoreTestsPigeonTestAllNullableTypes objects are equal. + * + * Returns: TRUE if @a and @b are equal. + */ +gboolean core_tests_pigeon_test_all_nullable_types_equals( + CoreTestsPigeonTestAllNullableTypes* a, + CoreTestsPigeonTestAllNullableTypes* b); + +/** + * core_tests_pigeon_test_all_nullable_types_hash: + * @object: a #CoreTestsPigeonTestAllNullableTypes. + * + * Calculates a hash code for a #CoreTestsPigeonTestAllNullableTypes object. + * + * Returns: the hash code. + */ +guint core_tests_pigeon_test_all_nullable_types_hash( + CoreTestsPigeonTestAllNullableTypes* object); + /** * CoreTestsPigeonTestAllNullableTypesWithoutRecursion: * @@ -1279,6 +1349,32 @@ FlValue* core_tests_pigeon_test_all_nullable_types_without_recursion_get_map_map( CoreTestsPigeonTestAllNullableTypesWithoutRecursion* object); +/** + * core_tests_pigeon_test_all_nullable_types_without_recursion_equals: + * @a: a #CoreTestsPigeonTestAllNullableTypesWithoutRecursion. + * @b: another #CoreTestsPigeonTestAllNullableTypesWithoutRecursion. + * + * Checks if two #CoreTestsPigeonTestAllNullableTypesWithoutRecursion objects + * are equal. + * + * Returns: TRUE if @a and @b are equal. + */ +gboolean core_tests_pigeon_test_all_nullable_types_without_recursion_equals( + CoreTestsPigeonTestAllNullableTypesWithoutRecursion* a, + CoreTestsPigeonTestAllNullableTypesWithoutRecursion* b); + +/** + * core_tests_pigeon_test_all_nullable_types_without_recursion_hash: + * @object: a #CoreTestsPigeonTestAllNullableTypesWithoutRecursion. + * + * Calculates a hash code for a + * #CoreTestsPigeonTestAllNullableTypesWithoutRecursion object. + * + * Returns: the hash code. + */ +guint core_tests_pigeon_test_all_nullable_types_without_recursion_hash( + CoreTestsPigeonTestAllNullableTypesWithoutRecursion* object); + /** * CoreTestsPigeonTestAllClassesWrapper: * @@ -1396,6 +1492,30 @@ FlValue* core_tests_pigeon_test_all_classes_wrapper_get_class_map( FlValue* core_tests_pigeon_test_all_classes_wrapper_get_nullable_class_map( CoreTestsPigeonTestAllClassesWrapper* object); +/** + * core_tests_pigeon_test_all_classes_wrapper_equals: + * @a: a #CoreTestsPigeonTestAllClassesWrapper. + * @b: another #CoreTestsPigeonTestAllClassesWrapper. + * + * Checks if two #CoreTestsPigeonTestAllClassesWrapper objects are equal. + * + * Returns: TRUE if @a and @b are equal. + */ +gboolean core_tests_pigeon_test_all_classes_wrapper_equals( + CoreTestsPigeonTestAllClassesWrapper* a, + CoreTestsPigeonTestAllClassesWrapper* b); + +/** + * core_tests_pigeon_test_all_classes_wrapper_hash: + * @object: a #CoreTestsPigeonTestAllClassesWrapper. + * + * Calculates a hash code for a #CoreTestsPigeonTestAllClassesWrapper object. + * + * Returns: the hash code. + */ +guint core_tests_pigeon_test_all_classes_wrapper_hash( + CoreTestsPigeonTestAllClassesWrapper* object); + /** * CoreTestsPigeonTestTestMessage: * @@ -1428,6 +1548,29 @@ CoreTestsPigeonTestTestMessage* core_tests_pigeon_test_test_message_new( FlValue* core_tests_pigeon_test_test_message_get_test_list( CoreTestsPigeonTestTestMessage* object); +/** + * core_tests_pigeon_test_test_message_equals: + * @a: a #CoreTestsPigeonTestTestMessage. + * @b: another #CoreTestsPigeonTestTestMessage. + * + * Checks if two #CoreTestsPigeonTestTestMessage objects are equal. + * + * Returns: TRUE if @a and @b are equal. + */ +gboolean core_tests_pigeon_test_test_message_equals( + CoreTestsPigeonTestTestMessage* a, CoreTestsPigeonTestTestMessage* b); + +/** + * core_tests_pigeon_test_test_message_hash: + * @object: a #CoreTestsPigeonTestTestMessage. + * + * Calculates a hash code for a #CoreTestsPigeonTestTestMessage object. + * + * Returns: the hash code. + */ +guint core_tests_pigeon_test_test_message_hash( + CoreTestsPigeonTestTestMessage* object); + G_DECLARE_FINAL_TYPE(CoreTestsPigeonTestMessageCodec, core_tests_pigeon_test_message_codec, CORE_TESTS_PIGEON_TEST, MESSAGE_CODEC, @@ -2451,6 +2594,110 @@ CoreTestsPigeonTestHostIntegrationCoreApiEchoRequiredIntResponse* core_tests_pigeon_test_host_integration_core_api_echo_required_int_response_new_error( const gchar* code, const gchar* message, FlValue* details); +G_DECLARE_FINAL_TYPE( + CoreTestsPigeonTestHostIntegrationCoreApiAreAllNullableTypesEqualResponse, + core_tests_pigeon_test_host_integration_core_api_are_all_nullable_types_equal_response, + CORE_TESTS_PIGEON_TEST, + HOST_INTEGRATION_CORE_API_ARE_ALL_NULLABLE_TYPES_EQUAL_RESPONSE, GObject) + +/** + * core_tests_pigeon_test_host_integration_core_api_are_all_nullable_types_equal_response_new: + * + * Creates a new response to HostIntegrationCoreApi.areAllNullableTypesEqual. + * + * Returns: a new + * #CoreTestsPigeonTestHostIntegrationCoreApiAreAllNullableTypesEqualResponse + */ +CoreTestsPigeonTestHostIntegrationCoreApiAreAllNullableTypesEqualResponse* +core_tests_pigeon_test_host_integration_core_api_are_all_nullable_types_equal_response_new( + gboolean return_value); + +/** + * core_tests_pigeon_test_host_integration_core_api_are_all_nullable_types_equal_response_new_error: + * @code: error code. + * @message: error message. + * @details: (allow-none): error details or %NULL. + * + * Creates a new error response to + * HostIntegrationCoreApi.areAllNullableTypesEqual. + * + * Returns: a new + * #CoreTestsPigeonTestHostIntegrationCoreApiAreAllNullableTypesEqualResponse + */ +CoreTestsPigeonTestHostIntegrationCoreApiAreAllNullableTypesEqualResponse* +core_tests_pigeon_test_host_integration_core_api_are_all_nullable_types_equal_response_new_error( + const gchar* code, const gchar* message, FlValue* details); + +G_DECLARE_FINAL_TYPE( + CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesHashResponse, + core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_hash_response, + CORE_TESTS_PIGEON_TEST, + HOST_INTEGRATION_CORE_API_GET_ALL_NULLABLE_TYPES_HASH_RESPONSE, GObject) + +/** + * core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_hash_response_new: + * + * Creates a new response to HostIntegrationCoreApi.getAllNullableTypesHash. + * + * Returns: a new + * #CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesHashResponse + */ +CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesHashResponse* +core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_hash_response_new( + int64_t return_value); + +/** + * core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_hash_response_new_error: + * @code: error code. + * @message: error message. + * @details: (allow-none): error details or %NULL. + * + * Creates a new error response to + * HostIntegrationCoreApi.getAllNullableTypesHash. + * + * Returns: a new + * #CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesHashResponse + */ +CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesHashResponse* +core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_hash_response_new_error( + const gchar* code, const gchar* message, FlValue* details); + +G_DECLARE_FINAL_TYPE( + CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesWithoutRecursionHashResponse, + core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_without_recursion_hash_response, + CORE_TESTS_PIGEON_TEST, + HOST_INTEGRATION_CORE_API_GET_ALL_NULLABLE_TYPES_WITHOUT_RECURSION_HASH_RESPONSE, + GObject) + +/** + * core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_without_recursion_hash_response_new: + * + * Creates a new response to + * HostIntegrationCoreApi.getAllNullableTypesWithoutRecursionHash. + * + * Returns: a new + * #CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesWithoutRecursionHashResponse + */ +CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesWithoutRecursionHashResponse* +core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_without_recursion_hash_response_new( + int64_t return_value); + +/** + * core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_without_recursion_hash_response_new_error: + * @code: error code. + * @message: error message. + * @details: (allow-none): error details or %NULL. + * + * Creates a new error response to + * HostIntegrationCoreApi.getAllNullableTypesWithoutRecursionHash. + * + * Returns: a new + * #CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesWithoutRecursionHashResponse + */ +CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesWithoutRecursionHashResponse* +core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_without_recursion_hash_response_new_error( + const gchar* code, const gchar* message, FlValue* details); + G_DECLARE_FINAL_TYPE( CoreTestsPigeonTestHostIntegrationCoreApiEchoAllNullableTypesResponse, core_tests_pigeon_test_host_integration_core_api_echo_all_nullable_types_response, @@ -3605,6 +3852,17 @@ typedef struct { *echo_optional_default_double)(double a_double, gpointer user_data); CoreTestsPigeonTestHostIntegrationCoreApiEchoRequiredIntResponse* ( *echo_required_int)(int64_t an_int, gpointer user_data); + CoreTestsPigeonTestHostIntegrationCoreApiAreAllNullableTypesEqualResponse* ( + *are_all_nullable_types_equal)(CoreTestsPigeonTestAllNullableTypes* a, + CoreTestsPigeonTestAllNullableTypes* b, + gpointer user_data); + CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesHashResponse* ( + *get_all_nullable_types_hash)(CoreTestsPigeonTestAllNullableTypes* value, + gpointer user_data); + CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesWithoutRecursionHashResponse* ( + *get_all_nullable_types_without_recursion_hash)( + CoreTestsPigeonTestAllNullableTypesWithoutRecursion* value, + gpointer user_data); CoreTestsPigeonTestHostIntegrationCoreApiEchoAllNullableTypesResponse* ( *echo_all_nullable_types)(CoreTestsPigeonTestAllNullableTypes* everything, gpointer user_data); diff --git a/packages/pigeon/platform_tests/test_plugin/linux/test/equality_test.cc b/packages/pigeon/platform_tests/test_plugin/linux/test/equality_test.cc new file mode 100644 index 000000000000..349c4bdd34cb --- /dev/null +++ b/packages/pigeon/platform_tests/test_plugin/linux/test/equality_test.cc @@ -0,0 +1,238 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include + +#include "pigeon/core_tests.gen.h" + +static CoreTestsPigeonTestAllNullableTypes* create_empty_all_nullable_types() { + return core_tests_pigeon_test_all_nullable_types_new( + nullptr, nullptr, nullptr, nullptr, nullptr, 0, nullptr, 0, nullptr, 0, + nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); +} + +TEST(Equality, AllNullableTypesNaN) { + double nan_val = NAN; + g_autoptr(CoreTestsPigeonTestAllNullableTypes) all1 = + core_tests_pigeon_test_all_nullable_types_new( + nullptr, nullptr, nullptr, &nan_val, nullptr, 0, nullptr, 0, nullptr, + 0, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr); + g_autoptr(CoreTestsPigeonTestAllNullableTypes) all2 = + core_tests_pigeon_test_all_nullable_types_new( + nullptr, nullptr, nullptr, &nan_val, nullptr, 0, nullptr, 0, nullptr, + 0, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr); + + EXPECT_TRUE(core_tests_pigeon_test_all_nullable_types_equals(all1, all2)); + EXPECT_EQ(core_tests_pigeon_test_all_nullable_types_hash(all1), + core_tests_pigeon_test_all_nullable_types_hash(all2)); +} + +TEST(Equality, AllNullableTypesCollectionNaN) { + g_autoptr(FlValue) list1 = fl_value_new_list(); + fl_value_append_take(list1, fl_value_new_float(NAN)); + + g_autoptr(FlValue) list2 = fl_value_new_list(); + fl_value_append_take(list2, fl_value_new_float(NAN)); + + g_autoptr(CoreTestsPigeonTestAllNullableTypes) all1 = + core_tests_pigeon_test_all_nullable_types_new( + nullptr, nullptr, nullptr, nullptr, nullptr, 0, nullptr, 0, nullptr, + 0, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, list1, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr); + g_autoptr(CoreTestsPigeonTestAllNullableTypes) all2 = + core_tests_pigeon_test_all_nullable_types_new( + nullptr, nullptr, nullptr, nullptr, nullptr, 0, nullptr, 0, nullptr, + 0, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, list2, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr); + + EXPECT_TRUE(core_tests_pigeon_test_all_nullable_types_equals(all1, all2)); + EXPECT_EQ(core_tests_pigeon_test_all_nullable_types_hash(all1), + core_tests_pigeon_test_all_nullable_types_hash(all2)); +} + +TEST(Equality, AllNullableTypesRecursive) { + g_autoptr(CoreTestsPigeonTestAllNullableTypes) nested1 = + create_empty_all_nullable_types(); + g_autoptr(CoreTestsPigeonTestAllNullableTypes) all1 = + core_tests_pigeon_test_all_nullable_types_new( + nullptr, nullptr, nullptr, nullptr, nullptr, 0, nullptr, 0, nullptr, + 0, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nested1, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr); + + g_autoptr(CoreTestsPigeonTestAllNullableTypes) nested2 = + create_empty_all_nullable_types(); + g_autoptr(CoreTestsPigeonTestAllNullableTypes) all2 = + core_tests_pigeon_test_all_nullable_types_new( + nullptr, nullptr, nullptr, nullptr, nullptr, 0, nullptr, 0, nullptr, + 0, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nested2, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr); + + EXPECT_TRUE(core_tests_pigeon_test_all_nullable_types_equals(all1, all2)); + EXPECT_EQ(core_tests_pigeon_test_all_nullable_types_hash(all1), + core_tests_pigeon_test_all_nullable_types_hash(all2)); +} + +TEST(Equality, AllTypesNumericLists) { + uint8_t bytes[] = {1, 2, 3}; + int32_t ints32[] = {4, 5}; + double doubles[] = {1.1, 2.2}; + + g_autoptr(CoreTestsPigeonTestAllTypes) all1 = + core_tests_pigeon_test_all_types_new( + TRUE, 1, 2, 3.3, bytes, 3, ints32, 2, nullptr, 0, doubles, 2, + PIGEON_INTEGRATION_TESTS_AN_ENUM_ONE, + PIGEON_INTEGRATION_TESTS_ANOTHER_ENUM_JUST_IN_CASE, "hello", nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr); + + g_autoptr(CoreTestsPigeonTestAllTypes) all2 = + core_tests_pigeon_test_all_types_new( + TRUE, 1, 2, 3.3, bytes, 3, ints32, 2, nullptr, 0, doubles, 2, + PIGEON_INTEGRATION_TESTS_AN_ENUM_ONE, + PIGEON_INTEGRATION_TESTS_ANOTHER_ENUM_JUST_IN_CASE, "hello", nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr); + + EXPECT_TRUE(core_tests_pigeon_test_all_types_equals(all1, all2)); + EXPECT_EQ(core_tests_pigeon_test_all_types_hash(all1), + core_tests_pigeon_test_all_types_hash(all2)); + + // Change one element in a numeric list + doubles[1] = 2.3; + g_autoptr(CoreTestsPigeonTestAllTypes) all3 = + core_tests_pigeon_test_all_types_new( + TRUE, 1, 2, 3.3, bytes, 3, ints32, 2, nullptr, 0, doubles, 2, + PIGEON_INTEGRATION_TESTS_AN_ENUM_ONE, + PIGEON_INTEGRATION_TESTS_ANOTHER_ENUM_JUST_IN_CASE, "hello", nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr); + + EXPECT_FALSE(core_tests_pigeon_test_all_types_equals(all1, all3)); + EXPECT_NE(core_tests_pigeon_test_all_types_hash(all1), + core_tests_pigeon_test_all_types_hash(all3)); +} + +TEST(Equality, SignedZero) { + double p_zero = 0.0; + double n_zero = -0.0; + g_autoptr(CoreTestsPigeonTestAllNullableTypes) all1 = + core_tests_pigeon_test_all_nullable_types_new( + nullptr, nullptr, nullptr, &p_zero, nullptr, 0, nullptr, 0, nullptr, + 0, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr); + g_autoptr(CoreTestsPigeonTestAllNullableTypes) all2 = + core_tests_pigeon_test_all_nullable_types_new( + nullptr, nullptr, nullptr, &n_zero, nullptr, 0, nullptr, 0, nullptr, + 0, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr); + + EXPECT_TRUE(core_tests_pigeon_test_all_nullable_types_equals(all1, all2)); + EXPECT_EQ(core_tests_pigeon_test_all_nullable_types_hash(all1), + core_tests_pigeon_test_all_nullable_types_hash(all2)); +} + +TEST(Equality, SignedZeroMapKey) { + double p_zero = 0.0; + double n_zero = -0.0; + g_autoptr(FlValue) map1 = fl_value_new_map(); + fl_value_set_take(map1, fl_value_new_float(p_zero), fl_value_new_string("a")); + g_autoptr(FlValue) map2 = fl_value_new_map(); + fl_value_set_take(map2, fl_value_new_float(n_zero), fl_value_new_string("a")); + + g_autoptr(CoreTestsPigeonTestAllNullableTypes) all1 = + core_tests_pigeon_test_all_nullable_types_new( + nullptr, nullptr, nullptr, nullptr, nullptr, 0, nullptr, 0, nullptr, + 0, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, map1, nullptr, + nullptr, nullptr); + g_autoptr(CoreTestsPigeonTestAllNullableTypes) all2 = + core_tests_pigeon_test_all_nullable_types_new( + nullptr, nullptr, nullptr, nullptr, nullptr, 0, nullptr, 0, nullptr, + 0, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, map2, nullptr, + nullptr, nullptr); + + EXPECT_TRUE(core_tests_pigeon_test_all_nullable_types_equals(all1, all2)); + EXPECT_EQ(core_tests_pigeon_test_all_nullable_types_hash(all1), + core_tests_pigeon_test_all_nullable_types_hash(all2)); +} + +TEST(Equality, SignedZeroList) { + g_autoptr(FlValue) list1 = fl_value_new_list(); + fl_value_append_take(list1, fl_value_new_float(0.0)); + g_autoptr(FlValue) list2 = fl_value_new_list(); + fl_value_append_take(list2, fl_value_new_float(-0.0)); + + g_autoptr(CoreTestsPigeonTestAllNullableTypes) all1 = + core_tests_pigeon_test_all_nullable_types_new( + nullptr, nullptr, nullptr, nullptr, nullptr, 0, nullptr, 0, nullptr, + 0, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, list1, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr); + g_autoptr(CoreTestsPigeonTestAllNullableTypes) all2 = + core_tests_pigeon_test_all_nullable_types_new( + nullptr, nullptr, nullptr, nullptr, nullptr, 0, nullptr, 0, nullptr, + 0, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, list2, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr); + + EXPECT_TRUE(core_tests_pigeon_test_all_nullable_types_equals(all1, all2)); + EXPECT_EQ(core_tests_pigeon_test_all_nullable_types_hash(all1), + core_tests_pigeon_test_all_nullable_types_hash(all2)); +} + +TEST(Equality, SignedZeroMapValue) { + g_autoptr(FlValue) map1 = fl_value_new_map(); + fl_value_set_take(map1, fl_value_new_string("a"), fl_value_new_float(0.0)); + g_autoptr(FlValue) map2 = fl_value_new_map(); + fl_value_set_take(map2, fl_value_new_string("a"), fl_value_new_float(-0.0)); + + g_autoptr(CoreTestsPigeonTestAllNullableTypes) all1 = + core_tests_pigeon_test_all_nullable_types_new( + nullptr, nullptr, nullptr, nullptr, nullptr, 0, nullptr, 0, nullptr, + 0, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, map1, nullptr, + nullptr, nullptr); + g_autoptr(CoreTestsPigeonTestAllNullableTypes) all2 = + core_tests_pigeon_test_all_nullable_types_new( + nullptr, nullptr, nullptr, nullptr, nullptr, 0, nullptr, 0, nullptr, + 0, nullptr, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, map2, nullptr, + nullptr, nullptr); + + EXPECT_TRUE(core_tests_pigeon_test_all_nullable_types_equals(all1, all2)); + EXPECT_EQ(core_tests_pigeon_test_all_nullable_types_hash(all1), + core_tests_pigeon_test_all_nullable_types_hash(all2)); +} diff --git a/packages/pigeon/platform_tests/test_plugin/linux/test_plugin.cc b/packages/pigeon/platform_tests/test_plugin/linux/test_plugin.cc index 95c7aa410da0..693bb17eefee 100644 --- a/packages/pigeon/platform_tests/test_plugin/linux/test_plugin.cc +++ b/packages/pigeon/platform_tests/test_plugin/linux/test_plugin.cc @@ -253,6 +253,29 @@ echo_all_nullable_types(CoreTestsPigeonTestAllNullableTypes* everything, everything); } +static CoreTestsPigeonTestHostIntegrationCoreApiAreAllNullableTypesEqualResponse* +are_all_nullable_types_equal(CoreTestsPigeonTestAllNullableTypes* a, + CoreTestsPigeonTestAllNullableTypes* b, + gpointer user_data) { + return core_tests_pigeon_test_host_integration_core_api_are_all_nullable_types_equal_response_new( + core_tests_pigeon_test_all_nullable_types_equals(a, b)); +} + +static CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesHashResponse* +get_all_nullable_types_hash(CoreTestsPigeonTestAllNullableTypes* value, + gpointer user_data) { + return core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_hash_response_new( + core_tests_pigeon_test_all_nullable_types_hash(value)); +} + +static CoreTestsPigeonTestHostIntegrationCoreApiGetAllNullableTypesWithoutRecursionHashResponse* +get_all_nullable_types_without_recursion_hash( + CoreTestsPigeonTestAllNullableTypesWithoutRecursion* value, + gpointer user_data) { + return core_tests_pigeon_test_host_integration_core_api_get_all_nullable_types_without_recursion_hash_response_new( + core_tests_pigeon_test_all_nullable_types_without_recursion_hash(value)); +} + static CoreTestsPigeonTestHostIntegrationCoreApiEchoAllNullableTypesWithoutRecursionResponse* echo_all_nullable_types_without_recursion( @@ -3224,6 +3247,10 @@ static CoreTestsPigeonTestHostIntegrationCoreApiVTable host_core_api_vtable = { .echo_named_default_string = echo_named_default_string, .echo_optional_default_double = echo_optional_default_double, .echo_required_int = echo_required_int, + .are_all_nullable_types_equal = are_all_nullable_types_equal, + .get_all_nullable_types_hash = get_all_nullable_types_hash, + .get_all_nullable_types_without_recursion_hash = + get_all_nullable_types_without_recursion_hash, .echo_all_nullable_types = echo_all_nullable_types, .echo_all_nullable_types_without_recursion = echo_all_nullable_types_without_recursion, diff --git a/packages/pigeon/platform_tests/test_plugin/windows/CMakeLists.txt b/packages/pigeon/platform_tests/test_plugin/windows/CMakeLists.txt index e69e6bc75130..fff3f37c5d5c 100644 --- a/packages/pigeon/platform_tests/test_plugin/windows/CMakeLists.txt +++ b/packages/pigeon/platform_tests/test_plugin/windows/CMakeLists.txt @@ -66,6 +66,9 @@ target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin) # https://developercommunity.visualstudio.com/t/stdany-doesnt-link-when-exceptions-are-disabled/376072 # TODO(stuartmorgan): Remove this once CI is using VS 2022 or later. target_compile_definitions(${PLUGIN_NAME} PRIVATE "_HAS_EXCEPTIONS=1") +if (MSVC) + target_compile_options(${PLUGIN_NAME} PRIVATE "/bigobj") +endif() # List of absolute paths to libraries that should be bundled with the plugin. # This list could contain prebuilt libraries, or libraries created by an @@ -126,6 +129,9 @@ add_custom_command(TARGET ${TEST_RUNNER} POST_BUILD # https://developercommunity.visualstudio.com/t/stdany-doesnt-link-when-exceptions-are-disabled/376072 # TODO(stuartmorgan): Remove this once CI is using VS 2022 or later. target_compile_definitions(${TEST_RUNNER} PRIVATE "_HAS_EXCEPTIONS=1") +if (MSVC) + target_compile_options(${TEST_RUNNER} PRIVATE "/bigobj") +endif() include(GoogleTest) gtest_discover_tests(${TEST_RUNNER}) diff --git a/packages/pigeon/platform_tests/test_plugin/windows/pigeon/core_tests.gen.cpp b/packages/pigeon/platform_tests/test_plugin/windows/pigeon/core_tests.gen.cpp index b8c9e6860572..f50c8eff918c 100644 --- a/packages/pigeon/platform_tests/test_plugin/windows/pigeon/core_tests.gen.cpp +++ b/packages/pigeon/platform_tests/test_plugin/windows/pigeon/core_tests.gen.cpp @@ -14,16 +14,18 @@ #include #include +#include +#include #include #include #include namespace core_tests_pigeontest { -using flutter::BasicMessageChannel; -using flutter::CustomEncodableValue; -using flutter::EncodableList; -using flutter::EncodableMap; -using flutter::EncodableValue; +using ::flutter::BasicMessageChannel; +using ::flutter::CustomEncodableValue; +using ::flutter::EncodableList; +using ::flutter::EncodableMap; +using ::flutter::EncodableValue; FlutterError CreateConnectionError(const std::string channel_name) { return FlutterError( @@ -32,6 +34,212 @@ FlutterError CreateConnectionError(const std::string channel_name) { EncodableValue("")); } +namespace { +template +bool PigeonInternalDeepEquals(const T& a, const T& b); + +bool PigeonInternalDeepEquals(const double& a, const double& b); + +template +bool PigeonInternalDeepEquals(const std::vector& a, const std::vector& b); + +template +bool PigeonInternalDeepEquals(const std::map& a, const std::map& b); + +template +bool PigeonInternalDeepEquals(const std::optional& a, + const std::optional& b); + +template +bool PigeonInternalDeepEquals(const std::unique_ptr& a, + const std::unique_ptr& b); + +bool PigeonInternalDeepEquals(const ::flutter::EncodableValue& a, + const ::flutter::EncodableValue& b); + +template +bool PigeonInternalDeepEquals(const T& a, const T& b) { + return a == b; +} + +template +bool PigeonInternalDeepEquals(const std::vector& a, + const std::vector& b) { + if (a.size() != b.size()) { + return false; + } + for (size_t i = 0; i < a.size(); ++i) { + if (!PigeonInternalDeepEquals(a[i], b[i])) { + return false; + } + } + return true; +} + +template +bool PigeonInternalDeepEquals(const std::map& a, + const std::map& b) { + if (a.size() != b.size()) { + return false; + } + for (const auto& kv : a) { + bool found = false; + for (const auto& b_kv : b) { + if (PigeonInternalDeepEquals(kv.first, b_kv.first)) { + if (PigeonInternalDeepEquals(kv.second, b_kv.second)) { + found = true; + break; + } else { + return false; + } + } + } + if (!found) { + return false; + } + } + return true; +} + +bool PigeonInternalDeepEquals(const double& a, const double& b) { + // Normalize -0.0 to 0.0 and handle NaN equality. + return (a == b) || (std::isnan(a) && std::isnan(b)); +} + +template +bool PigeonInternalDeepEquals(const std::optional& a, + const std::optional& b) { + if (!a && !b) { + return true; + } + if (!a || !b) { + return false; + } + return PigeonInternalDeepEquals(*a, *b); +} + +template +bool PigeonInternalDeepEquals(const std::unique_ptr& a, + const std::unique_ptr& b) { + if (a.get() == b.get()) { + return true; + } + if (!a || !b) { + return false; + } + return PigeonInternalDeepEquals(*a, *b); +} + +bool PigeonInternalDeepEquals(const ::flutter::EncodableValue& a, + const ::flutter::EncodableValue& b) { + if (a.index() != b.index()) { + return false; + } + if (const double* da = std::get_if(&a)) { + return PigeonInternalDeepEquals(*da, std::get(b)); + } else if (const ::flutter::EncodableList* la = + std::get_if<::flutter::EncodableList>(&a)) { + return PigeonInternalDeepEquals(*la, std::get<::flutter::EncodableList>(b)); + } else if (const ::flutter::EncodableMap* ma = + std::get_if<::flutter::EncodableMap>(&a)) { + return PigeonInternalDeepEquals(*ma, std::get<::flutter::EncodableMap>(b)); + } + return a == b; +} + +template +size_t PigeonInternalDeepHash(const T& v); + +size_t PigeonInternalDeepHash(const double& v); + +template +size_t PigeonInternalDeepHash(const std::vector& v); + +template +size_t PigeonInternalDeepHash(const std::map& v); + +template +size_t PigeonInternalDeepHash(const std::optional& v); + +template +size_t PigeonInternalDeepHash(const std::unique_ptr& v); + +size_t PigeonInternalDeepHash(const ::flutter::EncodableValue& v); + +template +size_t PigeonInternalDeepHash(const T& v) { + return std::hash()(v); +} + +template +size_t PigeonInternalDeepHash(const std::vector& v) { + size_t result = 1; + for (const auto& item : v) { + result = result * 31 + PigeonInternalDeepHash(item); + } + return result; +} + +template +size_t PigeonInternalDeepHash(const std::map& v) { + size_t result = 0; + for (const auto& kv : v) { + result += ((PigeonInternalDeepHash(kv.first) * 31) ^ + PigeonInternalDeepHash(kv.second)); + } + return result; +} + +size_t PigeonInternalDeepHash(const double& v) { + if (std::isnan(v)) { + // Normalize NaN to a consistent hash. + return std::hash()(std::numeric_limits::quiet_NaN()); + } + if (v == 0.0) { + // Normalize -0.0 to 0.0 so they have the same hash code. + return std::hash()(0.0); + } + return std::hash()(v); +} + +template +size_t PigeonInternalDeepHash(const std::optional& v) { + return v ? PigeonInternalDeepHash(*v) : 0; +} + +template +size_t PigeonInternalDeepHash(const std::unique_ptr& v) { + return v ? PigeonInternalDeepHash(*v) : 0; +} + +size_t PigeonInternalDeepHash(const ::flutter::EncodableValue& v) { + size_t result = v.index(); + if (const double* dv = std::get_if(&v)) { + result = result * 31 + PigeonInternalDeepHash(*dv); + } else if (const ::flutter::EncodableList* lv = + std::get_if<::flutter::EncodableList>(&v)) { + result = result * 31 + PigeonInternalDeepHash(*lv); + } else if (const ::flutter::EncodableMap* mv = + std::get_if<::flutter::EncodableMap>(&v)) { + result = result * 31 + PigeonInternalDeepHash(*mv); + } else { + std::visit( + [&result](const auto& val) { + using T = std::decay_t; + if constexpr (!std::is_same_v && + !std::is_same_v && + !std::is_same_v && + !std::is_same_v && + !std::is_same_v) { + result = result * 31 + PigeonInternalDeepHash(val); + } + }, + v); + } + return result; +} + +} // namespace // UnusedClass UnusedClass::UnusedClass() {} @@ -69,6 +277,22 @@ UnusedClass UnusedClass::FromEncodableList(const EncodableList& list) { return decoded; } +bool UnusedClass::operator==(const UnusedClass& other) const { + return PigeonInternalDeepEquals(a_field_, other.a_field_); +} + +bool UnusedClass::operator!=(const UnusedClass& other) const { + return !(*this == other); +} + +size_t UnusedClass::Hash() const { + size_t result = 1; + result = result * 31 + PigeonInternalDeepHash(a_field_); + return result; +} + +size_t PigeonInternalDeepHash(const UnusedClass& v) { return v.Hash(); } + // AllTypes AllTypes::AllTypes(bool a_bool, int64_t an_int, int64_t an_int64, @@ -337,6 +561,76 @@ AllTypes AllTypes::FromEncodableList(const EncodableList& list) { return decoded; } +bool AllTypes::operator==(const AllTypes& other) const { + return PigeonInternalDeepEquals(a_bool_, other.a_bool_) && + PigeonInternalDeepEquals(an_int_, other.an_int_) && + PigeonInternalDeepEquals(an_int64_, other.an_int64_) && + PigeonInternalDeepEquals(a_double_, other.a_double_) && + PigeonInternalDeepEquals(a_byte_array_, other.a_byte_array_) && + PigeonInternalDeepEquals(a4_byte_array_, other.a4_byte_array_) && + PigeonInternalDeepEquals(a8_byte_array_, other.a8_byte_array_) && + PigeonInternalDeepEquals(a_float_array_, other.a_float_array_) && + PigeonInternalDeepEquals(an_enum_, other.an_enum_) && + PigeonInternalDeepEquals(another_enum_, other.another_enum_) && + PigeonInternalDeepEquals(a_string_, other.a_string_) && + PigeonInternalDeepEquals(an_object_, other.an_object_) && + PigeonInternalDeepEquals(list_, other.list_) && + PigeonInternalDeepEquals(string_list_, other.string_list_) && + PigeonInternalDeepEquals(int_list_, other.int_list_) && + PigeonInternalDeepEquals(double_list_, other.double_list_) && + PigeonInternalDeepEquals(bool_list_, other.bool_list_) && + PigeonInternalDeepEquals(enum_list_, other.enum_list_) && + PigeonInternalDeepEquals(object_list_, other.object_list_) && + PigeonInternalDeepEquals(list_list_, other.list_list_) && + PigeonInternalDeepEquals(map_list_, other.map_list_) && + PigeonInternalDeepEquals(map_, other.map_) && + PigeonInternalDeepEquals(string_map_, other.string_map_) && + PigeonInternalDeepEquals(int_map_, other.int_map_) && + PigeonInternalDeepEquals(enum_map_, other.enum_map_) && + PigeonInternalDeepEquals(object_map_, other.object_map_) && + PigeonInternalDeepEquals(list_map_, other.list_map_) && + PigeonInternalDeepEquals(map_map_, other.map_map_); +} + +bool AllTypes::operator!=(const AllTypes& other) const { + return !(*this == other); +} + +size_t AllTypes::Hash() const { + size_t result = 1; + result = result * 31 + PigeonInternalDeepHash(a_bool_); + result = result * 31 + PigeonInternalDeepHash(an_int_); + result = result * 31 + PigeonInternalDeepHash(an_int64_); + result = result * 31 + PigeonInternalDeepHash(a_double_); + result = result * 31 + PigeonInternalDeepHash(a_byte_array_); + result = result * 31 + PigeonInternalDeepHash(a4_byte_array_); + result = result * 31 + PigeonInternalDeepHash(a8_byte_array_); + result = result * 31 + PigeonInternalDeepHash(a_float_array_); + result = result * 31 + PigeonInternalDeepHash(an_enum_); + result = result * 31 + PigeonInternalDeepHash(another_enum_); + result = result * 31 + PigeonInternalDeepHash(a_string_); + result = result * 31 + PigeonInternalDeepHash(an_object_); + result = result * 31 + PigeonInternalDeepHash(list_); + result = result * 31 + PigeonInternalDeepHash(string_list_); + result = result * 31 + PigeonInternalDeepHash(int_list_); + result = result * 31 + PigeonInternalDeepHash(double_list_); + result = result * 31 + PigeonInternalDeepHash(bool_list_); + result = result * 31 + PigeonInternalDeepHash(enum_list_); + result = result * 31 + PigeonInternalDeepHash(object_list_); + result = result * 31 + PigeonInternalDeepHash(list_list_); + result = result * 31 + PigeonInternalDeepHash(map_list_); + result = result * 31 + PigeonInternalDeepHash(map_); + result = result * 31 + PigeonInternalDeepHash(string_map_); + result = result * 31 + PigeonInternalDeepHash(int_map_); + result = result * 31 + PigeonInternalDeepHash(enum_map_); + result = result * 31 + PigeonInternalDeepHash(object_map_); + result = result * 31 + PigeonInternalDeepHash(list_map_); + result = result * 31 + PigeonInternalDeepHash(map_map_); + return result; +} + +size_t PigeonInternalDeepHash(const AllTypes& v) { return v.Hash(); } + // AllNullableTypes AllNullableTypes::AllNullableTypes() {} @@ -1187,6 +1481,93 @@ AllNullableTypes AllNullableTypes::FromEncodableList( return decoded; } +bool AllNullableTypes::operator==(const AllNullableTypes& other) const { + return PigeonInternalDeepEquals(a_nullable_bool_, other.a_nullable_bool_) && + PigeonInternalDeepEquals(a_nullable_int_, other.a_nullable_int_) && + PigeonInternalDeepEquals(a_nullable_int64_, other.a_nullable_int64_) && + PigeonInternalDeepEquals(a_nullable_double_, + other.a_nullable_double_) && + PigeonInternalDeepEquals(a_nullable_byte_array_, + other.a_nullable_byte_array_) && + PigeonInternalDeepEquals(a_nullable4_byte_array_, + other.a_nullable4_byte_array_) && + PigeonInternalDeepEquals(a_nullable8_byte_array_, + other.a_nullable8_byte_array_) && + PigeonInternalDeepEquals(a_nullable_float_array_, + other.a_nullable_float_array_) && + PigeonInternalDeepEquals(a_nullable_enum_, other.a_nullable_enum_) && + PigeonInternalDeepEquals(another_nullable_enum_, + other.another_nullable_enum_) && + PigeonInternalDeepEquals(a_nullable_string_, + other.a_nullable_string_) && + PigeonInternalDeepEquals(a_nullable_object_, + other.a_nullable_object_) && + PigeonInternalDeepEquals(all_nullable_types_, + other.all_nullable_types_) && + PigeonInternalDeepEquals(list_, other.list_) && + PigeonInternalDeepEquals(string_list_, other.string_list_) && + PigeonInternalDeepEquals(int_list_, other.int_list_) && + PigeonInternalDeepEquals(double_list_, other.double_list_) && + PigeonInternalDeepEquals(bool_list_, other.bool_list_) && + PigeonInternalDeepEquals(enum_list_, other.enum_list_) && + PigeonInternalDeepEquals(object_list_, other.object_list_) && + PigeonInternalDeepEquals(list_list_, other.list_list_) && + PigeonInternalDeepEquals(map_list_, other.map_list_) && + PigeonInternalDeepEquals(recursive_class_list_, + other.recursive_class_list_) && + PigeonInternalDeepEquals(map_, other.map_) && + PigeonInternalDeepEquals(string_map_, other.string_map_) && + PigeonInternalDeepEquals(int_map_, other.int_map_) && + PigeonInternalDeepEquals(enum_map_, other.enum_map_) && + PigeonInternalDeepEquals(object_map_, other.object_map_) && + PigeonInternalDeepEquals(list_map_, other.list_map_) && + PigeonInternalDeepEquals(map_map_, other.map_map_) && + PigeonInternalDeepEquals(recursive_class_map_, + other.recursive_class_map_); +} + +bool AllNullableTypes::operator!=(const AllNullableTypes& other) const { + return !(*this == other); +} + +size_t AllNullableTypes::Hash() const { + size_t result = 1; + result = result * 31 + PigeonInternalDeepHash(a_nullable_bool_); + result = result * 31 + PigeonInternalDeepHash(a_nullable_int_); + result = result * 31 + PigeonInternalDeepHash(a_nullable_int64_); + result = result * 31 + PigeonInternalDeepHash(a_nullable_double_); + result = result * 31 + PigeonInternalDeepHash(a_nullable_byte_array_); + result = result * 31 + PigeonInternalDeepHash(a_nullable4_byte_array_); + result = result * 31 + PigeonInternalDeepHash(a_nullable8_byte_array_); + result = result * 31 + PigeonInternalDeepHash(a_nullable_float_array_); + result = result * 31 + PigeonInternalDeepHash(a_nullable_enum_); + result = result * 31 + PigeonInternalDeepHash(another_nullable_enum_); + result = result * 31 + PigeonInternalDeepHash(a_nullable_string_); + result = result * 31 + PigeonInternalDeepHash(a_nullable_object_); + result = result * 31 + PigeonInternalDeepHash(all_nullable_types_); + result = result * 31 + PigeonInternalDeepHash(list_); + result = result * 31 + PigeonInternalDeepHash(string_list_); + result = result * 31 + PigeonInternalDeepHash(int_list_); + result = result * 31 + PigeonInternalDeepHash(double_list_); + result = result * 31 + PigeonInternalDeepHash(bool_list_); + result = result * 31 + PigeonInternalDeepHash(enum_list_); + result = result * 31 + PigeonInternalDeepHash(object_list_); + result = result * 31 + PigeonInternalDeepHash(list_list_); + result = result * 31 + PigeonInternalDeepHash(map_list_); + result = result * 31 + PigeonInternalDeepHash(recursive_class_list_); + result = result * 31 + PigeonInternalDeepHash(map_); + result = result * 31 + PigeonInternalDeepHash(string_map_); + result = result * 31 + PigeonInternalDeepHash(int_map_); + result = result * 31 + PigeonInternalDeepHash(enum_map_); + result = result * 31 + PigeonInternalDeepHash(object_map_); + result = result * 31 + PigeonInternalDeepHash(list_map_); + result = result * 31 + PigeonInternalDeepHash(map_map_); + result = result * 31 + PigeonInternalDeepHash(recursive_class_map_); + return result; +} + +size_t PigeonInternalDeepHash(const AllNullableTypes& v) { return v.Hash(); } + // AllNullableTypesWithoutRecursion AllNullableTypesWithoutRecursion::AllNullableTypesWithoutRecursion() {} @@ -1873,6 +2254,88 @@ AllNullableTypesWithoutRecursion::FromEncodableList(const EncodableList& list) { return decoded; } +bool AllNullableTypesWithoutRecursion::operator==( + const AllNullableTypesWithoutRecursion& other) const { + return PigeonInternalDeepEquals(a_nullable_bool_, other.a_nullable_bool_) && + PigeonInternalDeepEquals(a_nullable_int_, other.a_nullable_int_) && + PigeonInternalDeepEquals(a_nullable_int64_, other.a_nullable_int64_) && + PigeonInternalDeepEquals(a_nullable_double_, + other.a_nullable_double_) && + PigeonInternalDeepEquals(a_nullable_byte_array_, + other.a_nullable_byte_array_) && + PigeonInternalDeepEquals(a_nullable4_byte_array_, + other.a_nullable4_byte_array_) && + PigeonInternalDeepEquals(a_nullable8_byte_array_, + other.a_nullable8_byte_array_) && + PigeonInternalDeepEquals(a_nullable_float_array_, + other.a_nullable_float_array_) && + PigeonInternalDeepEquals(a_nullable_enum_, other.a_nullable_enum_) && + PigeonInternalDeepEquals(another_nullable_enum_, + other.another_nullable_enum_) && + PigeonInternalDeepEquals(a_nullable_string_, + other.a_nullable_string_) && + PigeonInternalDeepEquals(a_nullable_object_, + other.a_nullable_object_) && + PigeonInternalDeepEquals(list_, other.list_) && + PigeonInternalDeepEquals(string_list_, other.string_list_) && + PigeonInternalDeepEquals(int_list_, other.int_list_) && + PigeonInternalDeepEquals(double_list_, other.double_list_) && + PigeonInternalDeepEquals(bool_list_, other.bool_list_) && + PigeonInternalDeepEquals(enum_list_, other.enum_list_) && + PigeonInternalDeepEquals(object_list_, other.object_list_) && + PigeonInternalDeepEquals(list_list_, other.list_list_) && + PigeonInternalDeepEquals(map_list_, other.map_list_) && + PigeonInternalDeepEquals(map_, other.map_) && + PigeonInternalDeepEquals(string_map_, other.string_map_) && + PigeonInternalDeepEquals(int_map_, other.int_map_) && + PigeonInternalDeepEquals(enum_map_, other.enum_map_) && + PigeonInternalDeepEquals(object_map_, other.object_map_) && + PigeonInternalDeepEquals(list_map_, other.list_map_) && + PigeonInternalDeepEquals(map_map_, other.map_map_); +} + +bool AllNullableTypesWithoutRecursion::operator!=( + const AllNullableTypesWithoutRecursion& other) const { + return !(*this == other); +} + +size_t AllNullableTypesWithoutRecursion::Hash() const { + size_t result = 1; + result = result * 31 + PigeonInternalDeepHash(a_nullable_bool_); + result = result * 31 + PigeonInternalDeepHash(a_nullable_int_); + result = result * 31 + PigeonInternalDeepHash(a_nullable_int64_); + result = result * 31 + PigeonInternalDeepHash(a_nullable_double_); + result = result * 31 + PigeonInternalDeepHash(a_nullable_byte_array_); + result = result * 31 + PigeonInternalDeepHash(a_nullable4_byte_array_); + result = result * 31 + PigeonInternalDeepHash(a_nullable8_byte_array_); + result = result * 31 + PigeonInternalDeepHash(a_nullable_float_array_); + result = result * 31 + PigeonInternalDeepHash(a_nullable_enum_); + result = result * 31 + PigeonInternalDeepHash(another_nullable_enum_); + result = result * 31 + PigeonInternalDeepHash(a_nullable_string_); + result = result * 31 + PigeonInternalDeepHash(a_nullable_object_); + result = result * 31 + PigeonInternalDeepHash(list_); + result = result * 31 + PigeonInternalDeepHash(string_list_); + result = result * 31 + PigeonInternalDeepHash(int_list_); + result = result * 31 + PigeonInternalDeepHash(double_list_); + result = result * 31 + PigeonInternalDeepHash(bool_list_); + result = result * 31 + PigeonInternalDeepHash(enum_list_); + result = result * 31 + PigeonInternalDeepHash(object_list_); + result = result * 31 + PigeonInternalDeepHash(list_list_); + result = result * 31 + PigeonInternalDeepHash(map_list_); + result = result * 31 + PigeonInternalDeepHash(map_); + result = result * 31 + PigeonInternalDeepHash(string_map_); + result = result * 31 + PigeonInternalDeepHash(int_map_); + result = result * 31 + PigeonInternalDeepHash(enum_map_); + result = result * 31 + PigeonInternalDeepHash(object_map_); + result = result * 31 + PigeonInternalDeepHash(list_map_); + result = result * 31 + PigeonInternalDeepHash(map_map_); + return result; +} + +size_t PigeonInternalDeepHash(const AllNullableTypesWithoutRecursion& v) { + return v.Hash(); +} + // AllClassesWrapper AllClassesWrapper::AllClassesWrapper(const AllNullableTypes& all_nullable_types, @@ -2079,6 +2542,40 @@ AllClassesWrapper AllClassesWrapper::FromEncodableList( return decoded; } +bool AllClassesWrapper::operator==(const AllClassesWrapper& other) const { + return PigeonInternalDeepEquals(all_nullable_types_, + other.all_nullable_types_) && + PigeonInternalDeepEquals( + all_nullable_types_without_recursion_, + other.all_nullable_types_without_recursion_) && + PigeonInternalDeepEquals(all_types_, other.all_types_) && + PigeonInternalDeepEquals(class_list_, other.class_list_) && + PigeonInternalDeepEquals(nullable_class_list_, + other.nullable_class_list_) && + PigeonInternalDeepEquals(class_map_, other.class_map_) && + PigeonInternalDeepEquals(nullable_class_map_, + other.nullable_class_map_); +} + +bool AllClassesWrapper::operator!=(const AllClassesWrapper& other) const { + return !(*this == other); +} + +size_t AllClassesWrapper::Hash() const { + size_t result = 1; + result = result * 31 + PigeonInternalDeepHash(all_nullable_types_); + result = result * 31 + + PigeonInternalDeepHash(all_nullable_types_without_recursion_); + result = result * 31 + PigeonInternalDeepHash(all_types_); + result = result * 31 + PigeonInternalDeepHash(class_list_); + result = result * 31 + PigeonInternalDeepHash(nullable_class_list_); + result = result * 31 + PigeonInternalDeepHash(class_map_); + result = result * 31 + PigeonInternalDeepHash(nullable_class_map_); + return result; +} + +size_t PigeonInternalDeepHash(const AllClassesWrapper& v) { return v.Hash(); } + // TestMessage TestMessage::TestMessage() {} @@ -2116,10 +2613,26 @@ TestMessage TestMessage::FromEncodableList(const EncodableList& list) { return decoded; } +bool TestMessage::operator==(const TestMessage& other) const { + return PigeonInternalDeepEquals(test_list_, other.test_list_); +} + +bool TestMessage::operator!=(const TestMessage& other) const { + return !(*this == other); +} + +size_t TestMessage::Hash() const { + size_t result = 1; + result = result * 31 + PigeonInternalDeepHash(test_list_); + return result; +} + +size_t PigeonInternalDeepHash(const TestMessage& v) { return v.Hash(); } + PigeonInternalCodecSerializer::PigeonInternalCodecSerializer() {} EncodableValue PigeonInternalCodecSerializer::ReadValueOfType( - uint8_t type, flutter::ByteStreamReader* stream) const { + uint8_t type, ::flutter::ByteStreamReader* stream) const { switch (type) { case 129: { const auto& encodable_enum_arg = ReadValue(stream); @@ -2164,12 +2677,12 @@ EncodableValue PigeonInternalCodecSerializer::ReadValueOfType( std::get(ReadValue(stream)))); } default: - return flutter::StandardCodecSerializer::ReadValueOfType(type, stream); + return ::flutter::StandardCodecSerializer::ReadValueOfType(type, stream); } } void PigeonInternalCodecSerializer::WriteValue( - const EncodableValue& value, flutter::ByteStreamWriter* stream) const { + const EncodableValue& value, ::flutter::ByteStreamWriter* stream) const { if (const CustomEncodableValue* custom_value = std::get_if(&value)) { if (custom_value->type() == typeid(AnEnum)) { @@ -2233,23 +2746,23 @@ void PigeonInternalCodecSerializer::WriteValue( return; } } - flutter::StandardCodecSerializer::WriteValue(value, stream); + ::flutter::StandardCodecSerializer::WriteValue(value, stream); } /// The codec used by HostIntegrationCoreApi. -const flutter::StandardMessageCodec& HostIntegrationCoreApi::GetCodec() { - return flutter::StandardMessageCodec::GetInstance( +const ::flutter::StandardMessageCodec& HostIntegrationCoreApi::GetCodec() { + return ::flutter::StandardMessageCodec::GetInstance( &PigeonInternalCodecSerializer::GetInstance()); } // Sets up an instance of `HostIntegrationCoreApi` to handle messages through // the `binary_messenger`. -void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, +void HostIntegrationCoreApi::SetUp(::flutter::BinaryMessenger* binary_messenger, HostIntegrationCoreApi* api) { HostIntegrationCoreApi::SetUp(binary_messenger, api, ""); } -void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, +void HostIntegrationCoreApi::SetUp(::flutter::BinaryMessenger* binary_messenger, HostIntegrationCoreApi* api, const std::string& message_channel_suffix) { const std::string prepended_suffix = @@ -2265,7 +2778,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { std::optional output = api->Noop(); if (output.has_value()) { @@ -2292,7 +2805,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_everything_arg = args.at(0); @@ -2328,7 +2841,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { ErrorOr> output = api->ThrowError(); if (output.has_error()) { @@ -2361,7 +2874,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { std::optional output = api->ThrowErrorFromVoid(); if (output.has_value()) { @@ -2388,7 +2901,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { ErrorOr> output = api->ThrowFlutterError(); @@ -2422,7 +2935,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_an_int_arg = args.at(0); @@ -2456,7 +2969,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_double_arg = args.at(0); @@ -2491,7 +3004,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_bool_arg = args.at(0); @@ -2525,7 +3038,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_string_arg = args.at(0); @@ -2560,7 +3073,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_uint8_list_arg = args.at(0); @@ -2596,7 +3109,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_an_object_arg = args.at(0); @@ -2630,7 +3143,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_list_arg = args.at(0); @@ -2665,7 +3178,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_enum_list_arg = args.at(0); @@ -2700,7 +3213,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_class_list_arg = args.at(0); @@ -2736,7 +3249,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_enum_list_arg = args.at(0); @@ -2773,7 +3286,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_class_list_arg = args.at(0); @@ -2809,7 +3322,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_map_arg = args.at(0); @@ -2843,7 +3356,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_string_map_arg = args.at(0); @@ -2878,7 +3391,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_int_map_arg = args.at(0); @@ -2913,7 +3426,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_enum_map_arg = args.at(0); @@ -2948,7 +3461,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_class_map_arg = args.at(0); @@ -2984,7 +3497,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_string_map_arg = args.at(0); @@ -3020,7 +3533,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_int_map_arg = args.at(0); @@ -3056,7 +3569,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_enum_map_arg = args.at(0); @@ -3092,7 +3605,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_class_map_arg = args.at(0); @@ -3128,7 +3641,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_wrapper_arg = args.at(0); @@ -3165,7 +3678,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_an_enum_arg = args.at(0); @@ -3201,7 +3714,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_another_enum_arg = args.at(0); @@ -3239,7 +3752,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_string_arg = args.at(0); @@ -3276,7 +3789,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_double_arg = args.at(0); @@ -3312,7 +3825,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_an_int_arg = args.at(0); @@ -3337,6 +3850,124 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, channel.SetMessageHandler(nullptr); } } + { + BasicMessageChannel<> channel( + binary_messenger, + "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." + "areAllNullableTypesEqual" + + prepended_suffix, + &GetCodec()); + if (api != nullptr) { + channel.SetMessageHandler( + [api](const EncodableValue& message, + const ::flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_a_arg = args.at(0); + if (encodable_a_arg.IsNull()) { + reply(WrapError("a_arg unexpectedly null.")); + return; + } + const auto& a_arg = std::any_cast( + std::get(encodable_a_arg)); + const auto& encodable_b_arg = args.at(1); + if (encodable_b_arg.IsNull()) { + reply(WrapError("b_arg unexpectedly null.")); + return; + } + const auto& b_arg = std::any_cast( + std::get(encodable_b_arg)); + ErrorOr output = + api->AreAllNullableTypesEqual(a_arg, b_arg); + if (output.has_error()) { + reply(WrapError(output.error())); + return; + } + EncodableList wrapped; + wrapped.push_back(EncodableValue(std::move(output).TakeValue())); + reply(EncodableValue(std::move(wrapped))); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel.SetMessageHandler(nullptr); + } + } + { + BasicMessageChannel<> channel( + binary_messenger, + "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." + "getAllNullableTypesHash" + + prepended_suffix, + &GetCodec()); + if (api != nullptr) { + channel.SetMessageHandler( + [api](const EncodableValue& message, + const ::flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_value_arg = args.at(0); + if (encodable_value_arg.IsNull()) { + reply(WrapError("value_arg unexpectedly null.")); + return; + } + const auto& value_arg = std::any_cast( + std::get(encodable_value_arg)); + ErrorOr output = api->GetAllNullableTypesHash(value_arg); + if (output.has_error()) { + reply(WrapError(output.error())); + return; + } + EncodableList wrapped; + wrapped.push_back(EncodableValue(std::move(output).TakeValue())); + reply(EncodableValue(std::move(wrapped))); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel.SetMessageHandler(nullptr); + } + } + { + BasicMessageChannel<> channel( + binary_messenger, + "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." + "getAllNullableTypesWithoutRecursionHash" + + prepended_suffix, + &GetCodec()); + if (api != nullptr) { + channel.SetMessageHandler( + [api](const EncodableValue& message, + const ::flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_value_arg = args.at(0); + if (encodable_value_arg.IsNull()) { + reply(WrapError("value_arg unexpectedly null.")); + return; + } + const auto& value_arg = + std::any_cast( + std::get(encodable_value_arg)); + ErrorOr output = + api->GetAllNullableTypesWithoutRecursionHash(value_arg); + if (output.has_error()) { + reply(WrapError(output.error())); + return; + } + EncodableList wrapped; + wrapped.push_back(EncodableValue(std::move(output).TakeValue())); + reply(EncodableValue(std::move(wrapped))); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel.SetMessageHandler(nullptr); + } + } { BasicMessageChannel<> channel( binary_messenger, @@ -3347,7 +3978,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_everything_arg = args.at(0); @@ -3388,10 +4019,9 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, prepended_suffix, &GetCodec()); if (api != nullptr) { - channel.SetMessageHandler([api]( - const EncodableValue& message, - const flutter::MessageReply& - reply) { + channel.SetMessageHandler([api](const EncodableValue& message, + const ::flutter::MessageReply< + EncodableValue>& reply) { try { const auto& args = std::get(message); const auto& encodable_everything_arg = args.at(0); @@ -3434,7 +4064,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_wrapper_arg = args.at(0); @@ -3477,7 +4107,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_nullable_string_arg = args.at(0); @@ -3511,7 +4141,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_nullable_bool_arg = args.at(0); @@ -3552,7 +4182,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_nullable_bool_arg = args.at(0); @@ -3593,7 +4223,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_nullable_int_arg = args.at(0); @@ -3631,7 +4261,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_nullable_double_arg = args.at(0); @@ -3669,7 +4299,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_nullable_bool_arg = args.at(0); @@ -3707,7 +4337,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_nullable_string_arg = args.at(0); @@ -3746,7 +4376,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_nullable_uint8_list_arg = args.at(0); @@ -3785,7 +4415,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_nullable_object_arg = args.at(0); @@ -3823,7 +4453,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_nullable_list_arg = args.at(0); @@ -3862,7 +4492,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_enum_list_arg = args.at(0); @@ -3901,7 +4531,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_class_list_arg = args.at(0); @@ -3940,7 +4570,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_enum_list_arg = args.at(0); @@ -3979,7 +4609,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_class_list_arg = args.at(0); @@ -4017,7 +4647,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_map_arg = args.at(0); @@ -4056,7 +4686,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_string_map_arg = args.at(0); @@ -4094,7 +4724,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_int_map_arg = args.at(0); @@ -4132,7 +4762,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_enum_map_arg = args.at(0); @@ -4171,7 +4801,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_class_map_arg = args.at(0); @@ -4210,7 +4840,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_string_map_arg = args.at(0); @@ -4249,7 +4879,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_int_map_arg = args.at(0); @@ -4288,7 +4918,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_enum_map_arg = args.at(0); @@ -4327,7 +4957,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_class_map_arg = args.at(0); @@ -4365,7 +4995,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_an_enum_arg = args.at(0); @@ -4409,7 +5039,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_another_enum_arg = args.at(0); @@ -4454,7 +5084,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_nullable_int_arg = args.at(0); @@ -4493,7 +5123,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_nullable_string_arg = args.at(0); @@ -4531,7 +5161,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { api->NoopAsync([reply](std::optional&& output) { if (output.has_value()) { @@ -4559,7 +5189,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_an_int_arg = args.at(0); @@ -4595,7 +5225,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_double_arg = args.at(0); @@ -4633,7 +5263,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_bool_arg = args.at(0); @@ -4669,7 +5299,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_string_arg = args.at(0); @@ -4707,7 +5337,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_uint8_list_arg = args.at(0); @@ -4746,7 +5376,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_an_object_arg = args.at(0); @@ -4783,7 +5413,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_list_arg = args.at(0); @@ -4821,7 +5451,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_enum_list_arg = args.at(0); @@ -4859,7 +5489,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_class_list_arg = args.at(0); @@ -4897,7 +5527,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_map_arg = args.at(0); @@ -4934,7 +5564,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_string_map_arg = args.at(0); @@ -4972,7 +5602,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_int_map_arg = args.at(0); @@ -5010,7 +5640,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_enum_map_arg = args.at(0); @@ -5048,7 +5678,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_class_map_arg = args.at(0); @@ -5086,7 +5716,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_an_enum_arg = args.at(0); @@ -5125,7 +5755,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_another_enum_arg = args.at(0); @@ -5163,7 +5793,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { api->ThrowAsyncError( [reply](ErrorOr>&& output) { @@ -5199,7 +5829,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { api->ThrowAsyncErrorFromVoid( [reply](std::optional&& output) { @@ -5229,7 +5859,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { api->ThrowAsyncFlutterError( [reply](ErrorOr>&& output) { @@ -5264,7 +5894,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_everything_arg = args.at(0); @@ -5303,7 +5933,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_everything_arg = args.at(0); @@ -5346,10 +5976,9 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, prepended_suffix, &GetCodec()); if (api != nullptr) { - channel.SetMessageHandler([api]( - const EncodableValue& message, - const flutter::MessageReply& - reply) { + channel.SetMessageHandler([api](const EncodableValue& message, + const ::flutter::MessageReply< + EncodableValue>& reply) { try { const auto& args = std::get(message); const auto& encodable_everything_arg = args.at(0); @@ -5395,7 +6024,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_an_int_arg = args.at(0); @@ -5436,7 +6065,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_double_arg = args.at(0); @@ -5477,7 +6106,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_bool_arg = args.at(0); @@ -5516,7 +6145,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_string_arg = args.at(0); @@ -5557,7 +6186,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_uint8_list_arg = args.at(0); @@ -5599,7 +6228,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_an_object_arg = args.at(0); @@ -5639,7 +6268,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_list_arg = args.at(0); @@ -5680,7 +6309,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_enum_list_arg = args.at(0); @@ -5721,7 +6350,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_class_list_arg = args.at(0); @@ -5762,7 +6391,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_map_arg = args.at(0); @@ -5803,7 +6432,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_string_map_arg = args.at(0); @@ -5844,7 +6473,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_int_map_arg = args.at(0); @@ -5885,7 +6514,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_enum_map_arg = args.at(0); @@ -5926,7 +6555,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_class_map_arg = args.at(0); @@ -5967,7 +6596,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_an_enum_arg = args.at(0); @@ -6013,7 +6642,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_another_enum_arg = args.at(0); @@ -6058,7 +6687,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { ErrorOr output = api->DefaultIsMainThread(); if (output.has_error()) { @@ -6086,7 +6715,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { ErrorOr output = api->TaskQueueIsBackgroundThread(); if (output.has_error()) { @@ -6113,7 +6742,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { api->CallFlutterNoop( [reply](std::optional&& output) { @@ -6143,7 +6772,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { api->CallFlutterThrowError( [reply](ErrorOr>&& output) { @@ -6179,7 +6808,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { api->CallFlutterThrowErrorFromVoid( [reply](std::optional&& output) { @@ -6209,7 +6838,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_everything_arg = args.at(0); @@ -6248,7 +6877,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_everything_arg = args.at(0); @@ -6293,7 +6922,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_nullable_bool_arg = args.at(0); @@ -6334,10 +6963,9 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, prepended_suffix, &GetCodec()); if (api != nullptr) { - channel.SetMessageHandler([api]( - const EncodableValue& message, - const flutter::MessageReply& - reply) { + channel.SetMessageHandler([api](const EncodableValue& message, + const ::flutter::MessageReply< + EncodableValue>& reply) { try { const auto& args = std::get(message); const auto& encodable_everything_arg = args.at(0); @@ -6383,7 +7011,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_nullable_bool_arg = args.at(0); @@ -6425,7 +7053,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_bool_arg = args.at(0); @@ -6462,7 +7090,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_an_int_arg = args.at(0); @@ -6500,7 +7128,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_double_arg = args.at(0); @@ -6539,7 +7167,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_string_arg = args.at(0); @@ -6578,7 +7206,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_list_arg = args.at(0); @@ -6616,7 +7244,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_list_arg = args.at(0); @@ -6655,7 +7283,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_enum_list_arg = args.at(0); @@ -6694,7 +7322,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_class_list_arg = args.at(0); @@ -6733,7 +7361,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_enum_list_arg = args.at(0); @@ -6772,7 +7400,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_class_list_arg = args.at(0); @@ -6810,7 +7438,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_map_arg = args.at(0); @@ -6848,7 +7476,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_string_map_arg = args.at(0); @@ -6887,7 +7515,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_int_map_arg = args.at(0); @@ -6926,7 +7554,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_enum_map_arg = args.at(0); @@ -6965,7 +7593,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_class_map_arg = args.at(0); @@ -7004,7 +7632,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_string_map_arg = args.at(0); @@ -7043,7 +7671,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_int_map_arg = args.at(0); @@ -7082,7 +7710,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_enum_map_arg = args.at(0); @@ -7121,7 +7749,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_class_map_arg = args.at(0); @@ -7159,7 +7787,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_an_enum_arg = args.at(0); @@ -7198,7 +7826,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_another_enum_arg = args.at(0); @@ -7237,7 +7865,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_bool_arg = args.at(0); @@ -7276,7 +7904,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_an_int_arg = args.at(0); @@ -7317,7 +7945,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_double_arg = args.at(0); @@ -7358,7 +7986,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_string_arg = args.at(0); @@ -7399,7 +8027,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_list_arg = args.at(0); @@ -7441,7 +8069,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_list_arg = args.at(0); @@ -7482,7 +8110,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_enum_list_arg = args.at(0); @@ -7523,7 +8151,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_class_list_arg = args.at(0); @@ -7564,7 +8192,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_enum_list_arg = args.at(0); @@ -7605,7 +8233,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_class_list_arg = args.at(0); @@ -7646,7 +8274,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_map_arg = args.at(0); @@ -7687,7 +8315,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_string_map_arg = args.at(0); @@ -7728,7 +8356,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_int_map_arg = args.at(0); @@ -7769,7 +8397,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_enum_map_arg = args.at(0); @@ -7810,7 +8438,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_class_map_arg = args.at(0); @@ -7851,7 +8479,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_string_map_arg = args.at(0); @@ -7892,7 +8520,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_int_map_arg = args.at(0); @@ -7933,7 +8561,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_enum_map_arg = args.at(0); @@ -7974,7 +8602,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_class_map_arg = args.at(0); @@ -8015,7 +8643,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_an_enum_arg = args.at(0); @@ -8061,7 +8689,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_another_enum_arg = args.at(0); @@ -8107,7 +8735,7 @@ void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_string_arg = args.at(0); @@ -8154,19 +8782,19 @@ EncodableValue HostIntegrationCoreApi::WrapError(const FlutterError& error) { // Generated class from Pigeon that represents Flutter messages that can be // called from C++. FlutterIntegrationCoreApi::FlutterIntegrationCoreApi( - flutter::BinaryMessenger* binary_messenger) + ::flutter::BinaryMessenger* binary_messenger) : binary_messenger_(binary_messenger), message_channel_suffix_("") {} FlutterIntegrationCoreApi::FlutterIntegrationCoreApi( - flutter::BinaryMessenger* binary_messenger, + ::flutter::BinaryMessenger* binary_messenger, const std::string& message_channel_suffix) : binary_messenger_(binary_messenger), message_channel_suffix_(message_channel_suffix.length() > 0 ? std::string(".") + message_channel_suffix : "") {} -const flutter::StandardMessageCodec& FlutterIntegrationCoreApi::GetCodec() { - return flutter::StandardMessageCodec::GetInstance( +const ::flutter::StandardMessageCodec& FlutterIntegrationCoreApi::GetCodec() { + return ::flutter::StandardMessageCodec::GetInstance( &PigeonInternalCodecSerializer::GetInstance()); } @@ -10148,19 +10776,19 @@ void FlutterIntegrationCoreApi::EchoAsyncString( } /// The codec used by HostTrivialApi. -const flutter::StandardMessageCodec& HostTrivialApi::GetCodec() { - return flutter::StandardMessageCodec::GetInstance( +const ::flutter::StandardMessageCodec& HostTrivialApi::GetCodec() { + return ::flutter::StandardMessageCodec::GetInstance( &PigeonInternalCodecSerializer::GetInstance()); } // Sets up an instance of `HostTrivialApi` to handle messages through the // `binary_messenger`. -void HostTrivialApi::SetUp(flutter::BinaryMessenger* binary_messenger, +void HostTrivialApi::SetUp(::flutter::BinaryMessenger* binary_messenger, HostTrivialApi* api) { HostTrivialApi::SetUp(binary_messenger, api, ""); } -void HostTrivialApi::SetUp(flutter::BinaryMessenger* binary_messenger, +void HostTrivialApi::SetUp(::flutter::BinaryMessenger* binary_messenger, HostTrivialApi* api, const std::string& message_channel_suffix) { const std::string prepended_suffix = @@ -10176,7 +10804,7 @@ void HostTrivialApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { std::optional output = api->Noop(); if (output.has_value()) { @@ -10209,19 +10837,19 @@ EncodableValue HostTrivialApi::WrapError(const FlutterError& error) { } /// The codec used by HostSmallApi. -const flutter::StandardMessageCodec& HostSmallApi::GetCodec() { - return flutter::StandardMessageCodec::GetInstance( +const ::flutter::StandardMessageCodec& HostSmallApi::GetCodec() { + return ::flutter::StandardMessageCodec::GetInstance( &PigeonInternalCodecSerializer::GetInstance()); } // Sets up an instance of `HostSmallApi` to handle messages through the // `binary_messenger`. -void HostSmallApi::SetUp(flutter::BinaryMessenger* binary_messenger, +void HostSmallApi::SetUp(::flutter::BinaryMessenger* binary_messenger, HostSmallApi* api) { HostSmallApi::SetUp(binary_messenger, api, ""); } -void HostSmallApi::SetUp(flutter::BinaryMessenger* binary_messenger, +void HostSmallApi::SetUp(::flutter::BinaryMessenger* binary_messenger, HostSmallApi* api, const std::string& message_channel_suffix) { const std::string prepended_suffix = @@ -10237,7 +10865,7 @@ void HostSmallApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { const auto& args = std::get(message); const auto& encodable_a_string_arg = args.at(0); @@ -10274,7 +10902,7 @@ void HostSmallApi::SetUp(flutter::BinaryMessenger* binary_messenger, if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, - const flutter::MessageReply& reply) { + const ::flutter::MessageReply& reply) { try { api->VoidVoid([reply](std::optional&& output) { if (output.has_value()) { @@ -10309,18 +10937,18 @@ EncodableValue HostSmallApi::WrapError(const FlutterError& error) { // Generated class from Pigeon that represents Flutter messages that can be // called from C++. -FlutterSmallApi::FlutterSmallApi(flutter::BinaryMessenger* binary_messenger) +FlutterSmallApi::FlutterSmallApi(::flutter::BinaryMessenger* binary_messenger) : binary_messenger_(binary_messenger), message_channel_suffix_("") {} -FlutterSmallApi::FlutterSmallApi(flutter::BinaryMessenger* binary_messenger, +FlutterSmallApi::FlutterSmallApi(::flutter::BinaryMessenger* binary_messenger, const std::string& message_channel_suffix) : binary_messenger_(binary_messenger), message_channel_suffix_(message_channel_suffix.length() > 0 ? std::string(".") + message_channel_suffix : "") {} -const flutter::StandardMessageCodec& FlutterSmallApi::GetCodec() { - return flutter::StandardMessageCodec::GetInstance( +const ::flutter::StandardMessageCodec& FlutterSmallApi::GetCodec() { + return ::flutter::StandardMessageCodec::GetInstance( &PigeonInternalCodecSerializer::GetInstance()); } diff --git a/packages/pigeon/platform_tests/test_plugin/windows/pigeon/core_tests.gen.h b/packages/pigeon/platform_tests/test_plugin/windows/pigeon/core_tests.gen.h index 450a1dfcf068..24ca4540d6a8 100644 --- a/packages/pigeon/platform_tests/test_plugin/windows/pigeon/core_tests.gen.h +++ b/packages/pigeon/platform_tests/test_plugin/windows/pigeon/core_tests.gen.h @@ -28,17 +28,17 @@ class FlutterError { explicit FlutterError(const std::string& code, const std::string& message) : code_(code), message_(message) {} explicit FlutterError(const std::string& code, const std::string& message, - const flutter::EncodableValue& details) + const ::flutter::EncodableValue& details) : code_(code), message_(message), details_(details) {} const std::string& code() const { return code_; } const std::string& message() const { return message_; } - const flutter::EncodableValue& details() const { return details_; } + const ::flutter::EncodableValue& details() const { return details_; } private: std::string code_; std::string message_; - flutter::EncodableValue details_; + ::flutter::EncodableValue details_; }; template @@ -82,15 +82,21 @@ class UnusedClass { UnusedClass(); // Constructs an object setting all fields. - explicit UnusedClass(const flutter::EncodableValue* a_field); + explicit UnusedClass(const ::flutter::EncodableValue* a_field); - const flutter::EncodableValue* a_field() const; - void set_a_field(const flutter::EncodableValue* value_arg); - void set_a_field(const flutter::EncodableValue& value_arg); + const ::flutter::EncodableValue* a_field() const; + void set_a_field(const ::flutter::EncodableValue* value_arg); + void set_a_field(const ::flutter::EncodableValue& value_arg); + + bool operator==(const UnusedClass& other) const; + bool operator!=(const UnusedClass& other) const; + /// Returns a hash code value for the object. This method is supported for the + /// benefit of hash tables. + size_t Hash() const; private: - static UnusedClass FromEncodableList(const flutter::EncodableList& list); - flutter::EncodableList ToEncodableList() const; + static UnusedClass FromEncodableList(const ::flutter::EncodableList& list); + ::flutter::EncodableList ToEncodableList() const; friend class HostIntegrationCoreApi; friend class FlutterIntegrationCoreApi; friend class HostTrivialApi; @@ -98,7 +104,7 @@ class UnusedClass { friend class FlutterSmallApi; friend class PigeonInternalCodecSerializer; friend class CoreTestsTest; - std::optional a_field_; + std::optional<::flutter::EncodableValue> a_field_; }; // A class containing all supported types. @@ -114,23 +120,23 @@ class AllTypes { const std::vector& a_float_array, const AnEnum& an_enum, const AnotherEnum& another_enum, const std::string& a_string, - const flutter::EncodableValue& an_object, - const flutter::EncodableList& list, - const flutter::EncodableList& string_list, - const flutter::EncodableList& int_list, - const flutter::EncodableList& double_list, - const flutter::EncodableList& bool_list, - const flutter::EncodableList& enum_list, - const flutter::EncodableList& object_list, - const flutter::EncodableList& list_list, - const flutter::EncodableList& map_list, - const flutter::EncodableMap& map, - const flutter::EncodableMap& string_map, - const flutter::EncodableMap& int_map, - const flutter::EncodableMap& enum_map, - const flutter::EncodableMap& object_map, - const flutter::EncodableMap& list_map, - const flutter::EncodableMap& map_map); + const ::flutter::EncodableValue& an_object, + const ::flutter::EncodableList& list, + const ::flutter::EncodableList& string_list, + const ::flutter::EncodableList& int_list, + const ::flutter::EncodableList& double_list, + const ::flutter::EncodableList& bool_list, + const ::flutter::EncodableList& enum_list, + const ::flutter::EncodableList& object_list, + const ::flutter::EncodableList& list_list, + const ::flutter::EncodableList& map_list, + const ::flutter::EncodableMap& map, + const ::flutter::EncodableMap& string_map, + const ::flutter::EncodableMap& int_map, + const ::flutter::EncodableMap& enum_map, + const ::flutter::EncodableMap& object_map, + const ::flutter::EncodableMap& list_map, + const ::flutter::EncodableMap& map_map); bool a_bool() const; void set_a_bool(bool value_arg); @@ -165,60 +171,66 @@ class AllTypes { const std::string& a_string() const; void set_a_string(std::string_view value_arg); - const flutter::EncodableValue& an_object() const; - void set_an_object(const flutter::EncodableValue& value_arg); + const ::flutter::EncodableValue& an_object() const; + void set_an_object(const ::flutter::EncodableValue& value_arg); + + const ::flutter::EncodableList& list() const; + void set_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList& list() const; - void set_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList& string_list() const; + void set_string_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList& string_list() const; - void set_string_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList& int_list() const; + void set_int_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList& int_list() const; - void set_int_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList& double_list() const; + void set_double_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList& double_list() const; - void set_double_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList& bool_list() const; + void set_bool_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList& bool_list() const; - void set_bool_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList& enum_list() const; + void set_enum_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList& enum_list() const; - void set_enum_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList& object_list() const; + void set_object_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList& object_list() const; - void set_object_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList& list_list() const; + void set_list_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList& list_list() const; - void set_list_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList& map_list() const; + void set_map_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList& map_list() const; - void set_map_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableMap& map() const; + void set_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap& map() const; - void set_map(const flutter::EncodableMap& value_arg); + const ::flutter::EncodableMap& string_map() const; + void set_string_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap& string_map() const; - void set_string_map(const flutter::EncodableMap& value_arg); + const ::flutter::EncodableMap& int_map() const; + void set_int_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap& int_map() const; - void set_int_map(const flutter::EncodableMap& value_arg); + const ::flutter::EncodableMap& enum_map() const; + void set_enum_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap& enum_map() const; - void set_enum_map(const flutter::EncodableMap& value_arg); + const ::flutter::EncodableMap& object_map() const; + void set_object_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap& object_map() const; - void set_object_map(const flutter::EncodableMap& value_arg); + const ::flutter::EncodableMap& list_map() const; + void set_list_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap& list_map() const; - void set_list_map(const flutter::EncodableMap& value_arg); + const ::flutter::EncodableMap& map_map() const; + void set_map_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap& map_map() const; - void set_map_map(const flutter::EncodableMap& value_arg); + bool operator==(const AllTypes& other) const; + bool operator!=(const AllTypes& other) const; + /// Returns a hash code value for the object. This method is supported for the + /// benefit of hash tables. + size_t Hash() const; private: - static AllTypes FromEncodableList(const flutter::EncodableList& list); - flutter::EncodableList ToEncodableList() const; + static AllTypes FromEncodableList(const ::flutter::EncodableList& list); + ::flutter::EncodableList ToEncodableList() const; friend class AllClassesWrapper; friend class HostIntegrationCoreApi; friend class FlutterIntegrationCoreApi; @@ -238,23 +250,23 @@ class AllTypes { AnEnum an_enum_; AnotherEnum another_enum_; std::string a_string_; - flutter::EncodableValue an_object_; - flutter::EncodableList list_; - flutter::EncodableList string_list_; - flutter::EncodableList int_list_; - flutter::EncodableList double_list_; - flutter::EncodableList bool_list_; - flutter::EncodableList enum_list_; - flutter::EncodableList object_list_; - flutter::EncodableList list_list_; - flutter::EncodableList map_list_; - flutter::EncodableMap map_; - flutter::EncodableMap string_map_; - flutter::EncodableMap int_map_; - flutter::EncodableMap enum_map_; - flutter::EncodableMap object_map_; - flutter::EncodableMap list_map_; - flutter::EncodableMap map_map_; + ::flutter::EncodableValue an_object_; + ::flutter::EncodableList list_; + ::flutter::EncodableList string_list_; + ::flutter::EncodableList int_list_; + ::flutter::EncodableList double_list_; + ::flutter::EncodableList bool_list_; + ::flutter::EncodableList enum_list_; + ::flutter::EncodableList object_list_; + ::flutter::EncodableList list_list_; + ::flutter::EncodableList map_list_; + ::flutter::EncodableMap map_; + ::flutter::EncodableMap string_map_; + ::flutter::EncodableMap int_map_; + ::flutter::EncodableMap enum_map_; + ::flutter::EncodableMap object_map_; + ::flutter::EncodableMap list_map_; + ::flutter::EncodableMap map_map_; }; // A class containing all supported nullable types. @@ -275,25 +287,26 @@ class AllNullableTypes { const std::vector* a_nullable_float_array, const AnEnum* a_nullable_enum, const AnotherEnum* another_nullable_enum, const std::string* a_nullable_string, - const flutter::EncodableValue* a_nullable_object, + const ::flutter::EncodableValue* a_nullable_object, const AllNullableTypes* all_nullable_types, - const flutter::EncodableList* list, - const flutter::EncodableList* string_list, - const flutter::EncodableList* int_list, - const flutter::EncodableList* double_list, - const flutter::EncodableList* bool_list, - const flutter::EncodableList* enum_list, - const flutter::EncodableList* object_list, - const flutter::EncodableList* list_list, - const flutter::EncodableList* map_list, - const flutter::EncodableList* recursive_class_list, - const flutter::EncodableMap* map, const flutter::EncodableMap* string_map, - const flutter::EncodableMap* int_map, - const flutter::EncodableMap* enum_map, - const flutter::EncodableMap* object_map, - const flutter::EncodableMap* list_map, - const flutter::EncodableMap* map_map, - const flutter::EncodableMap* recursive_class_map); + const ::flutter::EncodableList* list, + const ::flutter::EncodableList* string_list, + const ::flutter::EncodableList* int_list, + const ::flutter::EncodableList* double_list, + const ::flutter::EncodableList* bool_list, + const ::flutter::EncodableList* enum_list, + const ::flutter::EncodableList* object_list, + const ::flutter::EncodableList* list_list, + const ::flutter::EncodableList* map_list, + const ::flutter::EncodableList* recursive_class_list, + const ::flutter::EncodableMap* map, + const ::flutter::EncodableMap* string_map, + const ::flutter::EncodableMap* int_map, + const ::flutter::EncodableMap* enum_map, + const ::flutter::EncodableMap* object_map, + const ::flutter::EncodableMap* list_map, + const ::flutter::EncodableMap* map_map, + const ::flutter::EncodableMap* recursive_class_map); ~AllNullableTypes() = default; AllNullableTypes(const AllNullableTypes& other); @@ -344,89 +357,96 @@ class AllNullableTypes { void set_a_nullable_string(const std::string_view* value_arg); void set_a_nullable_string(std::string_view value_arg); - const flutter::EncodableValue* a_nullable_object() const; - void set_a_nullable_object(const flutter::EncodableValue* value_arg); - void set_a_nullable_object(const flutter::EncodableValue& value_arg); + const ::flutter::EncodableValue* a_nullable_object() const; + void set_a_nullable_object(const ::flutter::EncodableValue* value_arg); + void set_a_nullable_object(const ::flutter::EncodableValue& value_arg); const AllNullableTypes* all_nullable_types() const; void set_all_nullable_types(const AllNullableTypes* value_arg); void set_all_nullable_types(const AllNullableTypes& value_arg); - const flutter::EncodableList* list() const; - void set_list(const flutter::EncodableList* value_arg); - void set_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList* list() const; + void set_list(const ::flutter::EncodableList* value_arg); + void set_list(const ::flutter::EncodableList& value_arg); + + const ::flutter::EncodableList* string_list() const; + void set_string_list(const ::flutter::EncodableList* value_arg); + void set_string_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList* string_list() const; - void set_string_list(const flutter::EncodableList* value_arg); - void set_string_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList* int_list() const; + void set_int_list(const ::flutter::EncodableList* value_arg); + void set_int_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList* int_list() const; - void set_int_list(const flutter::EncodableList* value_arg); - void set_int_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList* double_list() const; + void set_double_list(const ::flutter::EncodableList* value_arg); + void set_double_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList* double_list() const; - void set_double_list(const flutter::EncodableList* value_arg); - void set_double_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList* bool_list() const; + void set_bool_list(const ::flutter::EncodableList* value_arg); + void set_bool_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList* bool_list() const; - void set_bool_list(const flutter::EncodableList* value_arg); - void set_bool_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList* enum_list() const; + void set_enum_list(const ::flutter::EncodableList* value_arg); + void set_enum_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList* enum_list() const; - void set_enum_list(const flutter::EncodableList* value_arg); - void set_enum_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList* object_list() const; + void set_object_list(const ::flutter::EncodableList* value_arg); + void set_object_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList* object_list() const; - void set_object_list(const flutter::EncodableList* value_arg); - void set_object_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList* list_list() const; + void set_list_list(const ::flutter::EncodableList* value_arg); + void set_list_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList* list_list() const; - void set_list_list(const flutter::EncodableList* value_arg); - void set_list_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList* map_list() const; + void set_map_list(const ::flutter::EncodableList* value_arg); + void set_map_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList* map_list() const; - void set_map_list(const flutter::EncodableList* value_arg); - void set_map_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList* recursive_class_list() const; + void set_recursive_class_list(const ::flutter::EncodableList* value_arg); + void set_recursive_class_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList* recursive_class_list() const; - void set_recursive_class_list(const flutter::EncodableList* value_arg); - void set_recursive_class_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableMap* map() const; + void set_map(const ::flutter::EncodableMap* value_arg); + void set_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap* map() const; - void set_map(const flutter::EncodableMap* value_arg); - void set_map(const flutter::EncodableMap& value_arg); + const ::flutter::EncodableMap* string_map() const; + void set_string_map(const ::flutter::EncodableMap* value_arg); + void set_string_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap* string_map() const; - void set_string_map(const flutter::EncodableMap* value_arg); - void set_string_map(const flutter::EncodableMap& value_arg); + const ::flutter::EncodableMap* int_map() const; + void set_int_map(const ::flutter::EncodableMap* value_arg); + void set_int_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap* int_map() const; - void set_int_map(const flutter::EncodableMap* value_arg); - void set_int_map(const flutter::EncodableMap& value_arg); + const ::flutter::EncodableMap* enum_map() const; + void set_enum_map(const ::flutter::EncodableMap* value_arg); + void set_enum_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap* enum_map() const; - void set_enum_map(const flutter::EncodableMap* value_arg); - void set_enum_map(const flutter::EncodableMap& value_arg); + const ::flutter::EncodableMap* object_map() const; + void set_object_map(const ::flutter::EncodableMap* value_arg); + void set_object_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap* object_map() const; - void set_object_map(const flutter::EncodableMap* value_arg); - void set_object_map(const flutter::EncodableMap& value_arg); + const ::flutter::EncodableMap* list_map() const; + void set_list_map(const ::flutter::EncodableMap* value_arg); + void set_list_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap* list_map() const; - void set_list_map(const flutter::EncodableMap* value_arg); - void set_list_map(const flutter::EncodableMap& value_arg); + const ::flutter::EncodableMap* map_map() const; + void set_map_map(const ::flutter::EncodableMap* value_arg); + void set_map_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap* map_map() const; - void set_map_map(const flutter::EncodableMap* value_arg); - void set_map_map(const flutter::EncodableMap& value_arg); + const ::flutter::EncodableMap* recursive_class_map() const; + void set_recursive_class_map(const ::flutter::EncodableMap* value_arg); + void set_recursive_class_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap* recursive_class_map() const; - void set_recursive_class_map(const flutter::EncodableMap* value_arg); - void set_recursive_class_map(const flutter::EncodableMap& value_arg); + bool operator==(const AllNullableTypes& other) const; + bool operator!=(const AllNullableTypes& other) const; + /// Returns a hash code value for the object. This method is supported for the + /// benefit of hash tables. + size_t Hash() const; private: - static AllNullableTypes FromEncodableList(const flutter::EncodableList& list); - flutter::EncodableList ToEncodableList() const; + static AllNullableTypes FromEncodableList( + const ::flutter::EncodableList& list); + ::flutter::EncodableList ToEncodableList() const; friend class AllClassesWrapper; friend class HostIntegrationCoreApi; friend class FlutterIntegrationCoreApi; @@ -446,26 +466,26 @@ class AllNullableTypes { std::optional a_nullable_enum_; std::optional another_nullable_enum_; std::optional a_nullable_string_; - std::optional a_nullable_object_; + std::optional<::flutter::EncodableValue> a_nullable_object_; std::unique_ptr all_nullable_types_; - std::optional list_; - std::optional string_list_; - std::optional int_list_; - std::optional double_list_; - std::optional bool_list_; - std::optional enum_list_; - std::optional object_list_; - std::optional list_list_; - std::optional map_list_; - std::optional recursive_class_list_; - std::optional map_; - std::optional string_map_; - std::optional int_map_; - std::optional enum_map_; - std::optional object_map_; - std::optional list_map_; - std::optional map_map_; - std::optional recursive_class_map_; + std::optional<::flutter::EncodableList> list_; + std::optional<::flutter::EncodableList> string_list_; + std::optional<::flutter::EncodableList> int_list_; + std::optional<::flutter::EncodableList> double_list_; + std::optional<::flutter::EncodableList> bool_list_; + std::optional<::flutter::EncodableList> enum_list_; + std::optional<::flutter::EncodableList> object_list_; + std::optional<::flutter::EncodableList> list_list_; + std::optional<::flutter::EncodableList> map_list_; + std::optional<::flutter::EncodableList> recursive_class_list_; + std::optional<::flutter::EncodableMap> map_; + std::optional<::flutter::EncodableMap> string_map_; + std::optional<::flutter::EncodableMap> int_map_; + std::optional<::flutter::EncodableMap> enum_map_; + std::optional<::flutter::EncodableMap> object_map_; + std::optional<::flutter::EncodableMap> list_map_; + std::optional<::flutter::EncodableMap> map_map_; + std::optional<::flutter::EncodableMap> recursive_class_map_; }; // The primary purpose for this class is to ensure coverage of Swift structs @@ -488,22 +508,23 @@ class AllNullableTypesWithoutRecursion { const std::vector* a_nullable_float_array, const AnEnum* a_nullable_enum, const AnotherEnum* another_nullable_enum, const std::string* a_nullable_string, - const flutter::EncodableValue* a_nullable_object, - const flutter::EncodableList* list, - const flutter::EncodableList* string_list, - const flutter::EncodableList* int_list, - const flutter::EncodableList* double_list, - const flutter::EncodableList* bool_list, - const flutter::EncodableList* enum_list, - const flutter::EncodableList* object_list, - const flutter::EncodableList* list_list, - const flutter::EncodableList* map_list, const flutter::EncodableMap* map, - const flutter::EncodableMap* string_map, - const flutter::EncodableMap* int_map, - const flutter::EncodableMap* enum_map, - const flutter::EncodableMap* object_map, - const flutter::EncodableMap* list_map, - const flutter::EncodableMap* map_map); + const ::flutter::EncodableValue* a_nullable_object, + const ::flutter::EncodableList* list, + const ::flutter::EncodableList* string_list, + const ::flutter::EncodableList* int_list, + const ::flutter::EncodableList* double_list, + const ::flutter::EncodableList* bool_list, + const ::flutter::EncodableList* enum_list, + const ::flutter::EncodableList* object_list, + const ::flutter::EncodableList* list_list, + const ::flutter::EncodableList* map_list, + const ::flutter::EncodableMap* map, + const ::flutter::EncodableMap* string_map, + const ::flutter::EncodableMap* int_map, + const ::flutter::EncodableMap* enum_map, + const ::flutter::EncodableMap* object_map, + const ::flutter::EncodableMap* list_map, + const ::flutter::EncodableMap* map_map); const bool* a_nullable_bool() const; void set_a_nullable_bool(const bool* value_arg); @@ -549,78 +570,84 @@ class AllNullableTypesWithoutRecursion { void set_a_nullable_string(const std::string_view* value_arg); void set_a_nullable_string(std::string_view value_arg); - const flutter::EncodableValue* a_nullable_object() const; - void set_a_nullable_object(const flutter::EncodableValue* value_arg); - void set_a_nullable_object(const flutter::EncodableValue& value_arg); + const ::flutter::EncodableValue* a_nullable_object() const; + void set_a_nullable_object(const ::flutter::EncodableValue* value_arg); + void set_a_nullable_object(const ::flutter::EncodableValue& value_arg); - const flutter::EncodableList* list() const; - void set_list(const flutter::EncodableList* value_arg); - void set_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList* list() const; + void set_list(const ::flutter::EncodableList* value_arg); + void set_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList* string_list() const; - void set_string_list(const flutter::EncodableList* value_arg); - void set_string_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList* string_list() const; + void set_string_list(const ::flutter::EncodableList* value_arg); + void set_string_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList* int_list() const; - void set_int_list(const flutter::EncodableList* value_arg); - void set_int_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList* int_list() const; + void set_int_list(const ::flutter::EncodableList* value_arg); + void set_int_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList* double_list() const; - void set_double_list(const flutter::EncodableList* value_arg); - void set_double_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList* double_list() const; + void set_double_list(const ::flutter::EncodableList* value_arg); + void set_double_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList* bool_list() const; - void set_bool_list(const flutter::EncodableList* value_arg); - void set_bool_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList* bool_list() const; + void set_bool_list(const ::flutter::EncodableList* value_arg); + void set_bool_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList* enum_list() const; - void set_enum_list(const flutter::EncodableList* value_arg); - void set_enum_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList* enum_list() const; + void set_enum_list(const ::flutter::EncodableList* value_arg); + void set_enum_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList* object_list() const; - void set_object_list(const flutter::EncodableList* value_arg); - void set_object_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList* object_list() const; + void set_object_list(const ::flutter::EncodableList* value_arg); + void set_object_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList* list_list() const; - void set_list_list(const flutter::EncodableList* value_arg); - void set_list_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList* list_list() const; + void set_list_list(const ::flutter::EncodableList* value_arg); + void set_list_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList* map_list() const; - void set_map_list(const flutter::EncodableList* value_arg); - void set_map_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList* map_list() const; + void set_map_list(const ::flutter::EncodableList* value_arg); + void set_map_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableMap* map() const; - void set_map(const flutter::EncodableMap* value_arg); - void set_map(const flutter::EncodableMap& value_arg); + const ::flutter::EncodableMap* map() const; + void set_map(const ::flutter::EncodableMap* value_arg); + void set_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap* string_map() const; - void set_string_map(const flutter::EncodableMap* value_arg); - void set_string_map(const flutter::EncodableMap& value_arg); + const ::flutter::EncodableMap* string_map() const; + void set_string_map(const ::flutter::EncodableMap* value_arg); + void set_string_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap* int_map() const; - void set_int_map(const flutter::EncodableMap* value_arg); - void set_int_map(const flutter::EncodableMap& value_arg); + const ::flutter::EncodableMap* int_map() const; + void set_int_map(const ::flutter::EncodableMap* value_arg); + void set_int_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap* enum_map() const; - void set_enum_map(const flutter::EncodableMap* value_arg); - void set_enum_map(const flutter::EncodableMap& value_arg); + const ::flutter::EncodableMap* enum_map() const; + void set_enum_map(const ::flutter::EncodableMap* value_arg); + void set_enum_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap* object_map() const; - void set_object_map(const flutter::EncodableMap* value_arg); - void set_object_map(const flutter::EncodableMap& value_arg); + const ::flutter::EncodableMap* object_map() const; + void set_object_map(const ::flutter::EncodableMap* value_arg); + void set_object_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap* list_map() const; - void set_list_map(const flutter::EncodableMap* value_arg); - void set_list_map(const flutter::EncodableMap& value_arg); + const ::flutter::EncodableMap* list_map() const; + void set_list_map(const ::flutter::EncodableMap* value_arg); + void set_list_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap* map_map() const; - void set_map_map(const flutter::EncodableMap* value_arg); - void set_map_map(const flutter::EncodableMap& value_arg); + const ::flutter::EncodableMap* map_map() const; + void set_map_map(const ::flutter::EncodableMap* value_arg); + void set_map_map(const ::flutter::EncodableMap& value_arg); + + bool operator==(const AllNullableTypesWithoutRecursion& other) const; + bool operator!=(const AllNullableTypesWithoutRecursion& other) const; + /// Returns a hash code value for the object. This method is supported for the + /// benefit of hash tables. + size_t Hash() const; private: static AllNullableTypesWithoutRecursion FromEncodableList( - const flutter::EncodableList& list); - flutter::EncodableList ToEncodableList() const; + const ::flutter::EncodableList& list); + ::flutter::EncodableList ToEncodableList() const; friend class AllClassesWrapper; friend class HostIntegrationCoreApi; friend class FlutterIntegrationCoreApi; @@ -640,23 +667,23 @@ class AllNullableTypesWithoutRecursion { std::optional a_nullable_enum_; std::optional another_nullable_enum_; std::optional a_nullable_string_; - std::optional a_nullable_object_; - std::optional list_; - std::optional string_list_; - std::optional int_list_; - std::optional double_list_; - std::optional bool_list_; - std::optional enum_list_; - std::optional object_list_; - std::optional list_list_; - std::optional map_list_; - std::optional map_; - std::optional string_map_; - std::optional int_map_; - std::optional enum_map_; - std::optional object_map_; - std::optional list_map_; - std::optional map_map_; + std::optional<::flutter::EncodableValue> a_nullable_object_; + std::optional<::flutter::EncodableList> list_; + std::optional<::flutter::EncodableList> string_list_; + std::optional<::flutter::EncodableList> int_list_; + std::optional<::flutter::EncodableList> double_list_; + std::optional<::flutter::EncodableList> bool_list_; + std::optional<::flutter::EncodableList> enum_list_; + std::optional<::flutter::EncodableList> object_list_; + std::optional<::flutter::EncodableList> list_list_; + std::optional<::flutter::EncodableList> map_list_; + std::optional<::flutter::EncodableMap> map_; + std::optional<::flutter::EncodableMap> string_map_; + std::optional<::flutter::EncodableMap> int_map_; + std::optional<::flutter::EncodableMap> enum_map_; + std::optional<::flutter::EncodableMap> object_map_; + std::optional<::flutter::EncodableMap> list_map_; + std::optional<::flutter::EncodableMap> map_map_; }; // A class for testing nested class handling. @@ -670,18 +697,18 @@ class AllClassesWrapper { public: // Constructs an object setting all non-nullable fields. explicit AllClassesWrapper(const AllNullableTypes& all_nullable_types, - const flutter::EncodableList& class_list, - const flutter::EncodableMap& class_map); + const ::flutter::EncodableList& class_list, + const ::flutter::EncodableMap& class_map); // Constructs an object setting all fields. - explicit AllClassesWrapper(const AllNullableTypes& all_nullable_types, - const AllNullableTypesWithoutRecursion* - all_nullable_types_without_recursion, - const AllTypes* all_types, - const flutter::EncodableList& class_list, - const flutter::EncodableList* nullable_class_list, - const flutter::EncodableMap& class_map, - const flutter::EncodableMap* nullable_class_map); + explicit AllClassesWrapper( + const AllNullableTypes& all_nullable_types, + const AllNullableTypesWithoutRecursion* + all_nullable_types_without_recursion, + const AllTypes* all_types, const ::flutter::EncodableList& class_list, + const ::flutter::EncodableList* nullable_class_list, + const ::flutter::EncodableMap& class_map, + const ::flutter::EncodableMap* nullable_class_map); ~AllClassesWrapper() = default; AllClassesWrapper(const AllClassesWrapper& other); @@ -702,24 +729,30 @@ class AllClassesWrapper { void set_all_types(const AllTypes* value_arg); void set_all_types(const AllTypes& value_arg); - const flutter::EncodableList& class_list() const; - void set_class_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList& class_list() const; + void set_class_list(const ::flutter::EncodableList& value_arg); + + const ::flutter::EncodableList* nullable_class_list() const; + void set_nullable_class_list(const ::flutter::EncodableList* value_arg); + void set_nullable_class_list(const ::flutter::EncodableList& value_arg); - const flutter::EncodableList* nullable_class_list() const; - void set_nullable_class_list(const flutter::EncodableList* value_arg); - void set_nullable_class_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableMap& class_map() const; + void set_class_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap& class_map() const; - void set_class_map(const flutter::EncodableMap& value_arg); + const ::flutter::EncodableMap* nullable_class_map() const; + void set_nullable_class_map(const ::flutter::EncodableMap* value_arg); + void set_nullable_class_map(const ::flutter::EncodableMap& value_arg); - const flutter::EncodableMap* nullable_class_map() const; - void set_nullable_class_map(const flutter::EncodableMap* value_arg); - void set_nullable_class_map(const flutter::EncodableMap& value_arg); + bool operator==(const AllClassesWrapper& other) const; + bool operator!=(const AllClassesWrapper& other) const; + /// Returns a hash code value for the object. This method is supported for the + /// benefit of hash tables. + size_t Hash() const; private: static AllClassesWrapper FromEncodableList( - const flutter::EncodableList& list); - flutter::EncodableList ToEncodableList() const; + const ::flutter::EncodableList& list); + ::flutter::EncodableList ToEncodableList() const; friend class HostIntegrationCoreApi; friend class FlutterIntegrationCoreApi; friend class HostTrivialApi; @@ -731,10 +764,10 @@ class AllClassesWrapper { std::unique_ptr all_nullable_types_without_recursion_; std::unique_ptr all_types_; - flutter::EncodableList class_list_; - std::optional nullable_class_list_; - flutter::EncodableMap class_map_; - std::optional nullable_class_map_; + ::flutter::EncodableList class_list_; + std::optional<::flutter::EncodableList> nullable_class_list_; + ::flutter::EncodableMap class_map_; + std::optional<::flutter::EncodableMap> nullable_class_map_; }; // A data class containing a List, used in unit tests. @@ -746,15 +779,21 @@ class TestMessage { TestMessage(); // Constructs an object setting all fields. - explicit TestMessage(const flutter::EncodableList* test_list); + explicit TestMessage(const ::flutter::EncodableList* test_list); - const flutter::EncodableList* test_list() const; - void set_test_list(const flutter::EncodableList* value_arg); - void set_test_list(const flutter::EncodableList& value_arg); + const ::flutter::EncodableList* test_list() const; + void set_test_list(const ::flutter::EncodableList* value_arg); + void set_test_list(const ::flutter::EncodableList& value_arg); + + bool operator==(const TestMessage& other) const; + bool operator!=(const TestMessage& other) const; + /// Returns a hash code value for the object. This method is supported for the + /// benefit of hash tables. + size_t Hash() const; private: - static TestMessage FromEncodableList(const flutter::EncodableList& list); - flutter::EncodableList ToEncodableList() const; + static TestMessage FromEncodableList(const ::flutter::EncodableList& list); + ::flutter::EncodableList ToEncodableList() const; friend class HostIntegrationCoreApi; friend class FlutterIntegrationCoreApi; friend class HostTrivialApi; @@ -762,10 +801,11 @@ class TestMessage { friend class FlutterSmallApi; friend class PigeonInternalCodecSerializer; friend class CoreTestsTest; - std::optional test_list_; + std::optional<::flutter::EncodableList> test_list_; }; -class PigeonInternalCodecSerializer : public flutter::StandardCodecSerializer { +class PigeonInternalCodecSerializer + : public ::flutter::StandardCodecSerializer { public: PigeonInternalCodecSerializer(); inline static PigeonInternalCodecSerializer& GetInstance() { @@ -773,12 +813,12 @@ class PigeonInternalCodecSerializer : public flutter::StandardCodecSerializer { return sInstance; } - void WriteValue(const flutter::EncodableValue& value, - flutter::ByteStreamWriter* stream) const override; + void WriteValue(const ::flutter::EncodableValue& value, + ::flutter::ByteStreamWriter* stream) const override; protected: - flutter::EncodableValue ReadValueOfType( - uint8_t type, flutter::ByteStreamReader* stream) const override; + ::flutter::EncodableValue ReadValueOfType( + uint8_t type, ::flutter::ByteStreamReader* stream) const override; }; // The core interface that each host language plugin must implement in @@ -797,11 +837,11 @@ class HostIntegrationCoreApi { // Returns the passed object, to test serialization and deserialization. virtual ErrorOr EchoAllTypes(const AllTypes& everything) = 0; // Returns an error, to test error handling. - virtual ErrorOr> ThrowError() = 0; + virtual ErrorOr> ThrowError() = 0; // Returns an error from a void function, to test error handling. virtual std::optional ThrowErrorFromVoid() = 0; // Returns a Flutter error, to test error handling. - virtual ErrorOr> + virtual ErrorOr> ThrowFlutterError() = 0; // Returns passed in int. virtual ErrorOr EchoInt(int64_t an_int) = 0; @@ -815,50 +855,50 @@ class HostIntegrationCoreApi { virtual ErrorOr> EchoUint8List( const std::vector& a_uint8_list) = 0; // Returns the passed in generic Object. - virtual ErrorOr EchoObject( - const flutter::EncodableValue& an_object) = 0; + virtual ErrorOr<::flutter::EncodableValue> EchoObject( + const ::flutter::EncodableValue& an_object) = 0; // Returns the passed list, to test serialization and deserialization. - virtual ErrorOr EchoList( - const flutter::EncodableList& list) = 0; + virtual ErrorOr<::flutter::EncodableList> EchoList( + const ::flutter::EncodableList& list) = 0; // Returns the passed list, to test serialization and deserialization. - virtual ErrorOr EchoEnumList( - const flutter::EncodableList& enum_list) = 0; + virtual ErrorOr<::flutter::EncodableList> EchoEnumList( + const ::flutter::EncodableList& enum_list) = 0; // Returns the passed list, to test serialization and deserialization. - virtual ErrorOr EchoClassList( - const flutter::EncodableList& class_list) = 0; + virtual ErrorOr<::flutter::EncodableList> EchoClassList( + const ::flutter::EncodableList& class_list) = 0; // Returns the passed list, to test serialization and deserialization. - virtual ErrorOr EchoNonNullEnumList( - const flutter::EncodableList& enum_list) = 0; + virtual ErrorOr<::flutter::EncodableList> EchoNonNullEnumList( + const ::flutter::EncodableList& enum_list) = 0; // Returns the passed list, to test serialization and deserialization. - virtual ErrorOr EchoNonNullClassList( - const flutter::EncodableList& class_list) = 0; + virtual ErrorOr<::flutter::EncodableList> EchoNonNullClassList( + const ::flutter::EncodableList& class_list) = 0; // Returns the passed map, to test serialization and deserialization. - virtual ErrorOr EchoMap( - const flutter::EncodableMap& map) = 0; + virtual ErrorOr<::flutter::EncodableMap> EchoMap( + const ::flutter::EncodableMap& map) = 0; // Returns the passed map, to test serialization and deserialization. - virtual ErrorOr EchoStringMap( - const flutter::EncodableMap& string_map) = 0; + virtual ErrorOr<::flutter::EncodableMap> EchoStringMap( + const ::flutter::EncodableMap& string_map) = 0; // Returns the passed map, to test serialization and deserialization. - virtual ErrorOr EchoIntMap( - const flutter::EncodableMap& int_map) = 0; + virtual ErrorOr<::flutter::EncodableMap> EchoIntMap( + const ::flutter::EncodableMap& int_map) = 0; // Returns the passed map, to test serialization and deserialization. - virtual ErrorOr EchoEnumMap( - const flutter::EncodableMap& enum_map) = 0; + virtual ErrorOr<::flutter::EncodableMap> EchoEnumMap( + const ::flutter::EncodableMap& enum_map) = 0; // Returns the passed map, to test serialization and deserialization. - virtual ErrorOr EchoClassMap( - const flutter::EncodableMap& class_map) = 0; + virtual ErrorOr<::flutter::EncodableMap> EchoClassMap( + const ::flutter::EncodableMap& class_map) = 0; // Returns the passed map, to test serialization and deserialization. - virtual ErrorOr EchoNonNullStringMap( - const flutter::EncodableMap& string_map) = 0; + virtual ErrorOr<::flutter::EncodableMap> EchoNonNullStringMap( + const ::flutter::EncodableMap& string_map) = 0; // Returns the passed map, to test serialization and deserialization. - virtual ErrorOr EchoNonNullIntMap( - const flutter::EncodableMap& int_map) = 0; + virtual ErrorOr<::flutter::EncodableMap> EchoNonNullIntMap( + const ::flutter::EncodableMap& int_map) = 0; // Returns the passed map, to test serialization and deserialization. - virtual ErrorOr EchoNonNullEnumMap( - const flutter::EncodableMap& enum_map) = 0; + virtual ErrorOr<::flutter::EncodableMap> EchoNonNullEnumMap( + const ::flutter::EncodableMap& enum_map) = 0; // Returns the passed map, to test serialization and deserialization. - virtual ErrorOr EchoNonNullClassMap( - const flutter::EncodableMap& class_map) = 0; + virtual ErrorOr<::flutter::EncodableMap> EchoNonNullClassMap( + const ::flutter::EncodableMap& class_map) = 0; // Returns the passed class to test nested class serialization and // deserialization. virtual ErrorOr EchoClassWrapper( @@ -875,6 +915,15 @@ class HostIntegrationCoreApi { virtual ErrorOr EchoOptionalDefaultDouble(double a_double) = 0; // Returns passed in int. virtual ErrorOr EchoRequiredInt(int64_t an_int) = 0; + // Returns the result of platform-side equality check. + virtual ErrorOr AreAllNullableTypesEqual(const AllNullableTypes& a, + const AllNullableTypes& b) = 0; + // Returns the platform-side hash code for the given object. + virtual ErrorOr GetAllNullableTypesHash( + const AllNullableTypes& value) = 0; + // Returns the platform-side hash code for the given object. + virtual ErrorOr GetAllNullableTypesWithoutRecursionHash( + const AllNullableTypesWithoutRecursion& value) = 0; // Returns the passed object, to test serialization and deserialization. virtual ErrorOr> EchoAllNullableTypes( const AllNullableTypes* everything) = 0; @@ -915,50 +964,50 @@ class HostIntegrationCoreApi { virtual ErrorOr>> EchoNullableUint8List( const std::vector* a_nullable_uint8_list) = 0; // Returns the passed in generic Object. - virtual ErrorOr> EchoNullableObject( - const flutter::EncodableValue* a_nullable_object) = 0; + virtual ErrorOr> EchoNullableObject( + const ::flutter::EncodableValue* a_nullable_object) = 0; // Returns the passed list, to test serialization and deserialization. - virtual ErrorOr> EchoNullableList( - const flutter::EncodableList* a_nullable_list) = 0; + virtual ErrorOr> EchoNullableList( + const ::flutter::EncodableList* a_nullable_list) = 0; // Returns the passed list, to test serialization and deserialization. - virtual ErrorOr> EchoNullableEnumList( - const flutter::EncodableList* enum_list) = 0; + virtual ErrorOr> EchoNullableEnumList( + const ::flutter::EncodableList* enum_list) = 0; // Returns the passed list, to test serialization and deserialization. - virtual ErrorOr> EchoNullableClassList( - const flutter::EncodableList* class_list) = 0; + virtual ErrorOr> + EchoNullableClassList(const ::flutter::EncodableList* class_list) = 0; // Returns the passed list, to test serialization and deserialization. - virtual ErrorOr> - EchoNullableNonNullEnumList(const flutter::EncodableList* enum_list) = 0; + virtual ErrorOr> + EchoNullableNonNullEnumList(const ::flutter::EncodableList* enum_list) = 0; // Returns the passed list, to test serialization and deserialization. - virtual ErrorOr> - EchoNullableNonNullClassList(const flutter::EncodableList* class_list) = 0; + virtual ErrorOr> + EchoNullableNonNullClassList(const ::flutter::EncodableList* class_list) = 0; // Returns the passed map, to test serialization and deserialization. - virtual ErrorOr> EchoNullableMap( - const flutter::EncodableMap* map) = 0; + virtual ErrorOr> EchoNullableMap( + const ::flutter::EncodableMap* map) = 0; // Returns the passed map, to test serialization and deserialization. - virtual ErrorOr> EchoNullableStringMap( - const flutter::EncodableMap* string_map) = 0; + virtual ErrorOr> EchoNullableStringMap( + const ::flutter::EncodableMap* string_map) = 0; // Returns the passed map, to test serialization and deserialization. - virtual ErrorOr> EchoNullableIntMap( - const flutter::EncodableMap* int_map) = 0; + virtual ErrorOr> EchoNullableIntMap( + const ::flutter::EncodableMap* int_map) = 0; // Returns the passed map, to test serialization and deserialization. - virtual ErrorOr> EchoNullableEnumMap( - const flutter::EncodableMap* enum_map) = 0; + virtual ErrorOr> EchoNullableEnumMap( + const ::flutter::EncodableMap* enum_map) = 0; // Returns the passed map, to test serialization and deserialization. - virtual ErrorOr> EchoNullableClassMap( - const flutter::EncodableMap* class_map) = 0; + virtual ErrorOr> EchoNullableClassMap( + const ::flutter::EncodableMap* class_map) = 0; // Returns the passed map, to test serialization and deserialization. - virtual ErrorOr> - EchoNullableNonNullStringMap(const flutter::EncodableMap* string_map) = 0; + virtual ErrorOr> + EchoNullableNonNullStringMap(const ::flutter::EncodableMap* string_map) = 0; // Returns the passed map, to test serialization and deserialization. - virtual ErrorOr> - EchoNullableNonNullIntMap(const flutter::EncodableMap* int_map) = 0; + virtual ErrorOr> + EchoNullableNonNullIntMap(const ::flutter::EncodableMap* int_map) = 0; // Returns the passed map, to test serialization and deserialization. - virtual ErrorOr> - EchoNullableNonNullEnumMap(const flutter::EncodableMap* enum_map) = 0; + virtual ErrorOr> + EchoNullableNonNullEnumMap(const ::flutter::EncodableMap* enum_map) = 0; // Returns the passed map, to test serialization and deserialization. - virtual ErrorOr> - EchoNullableNonNullClassMap(const flutter::EncodableMap* class_map) = 0; + virtual ErrorOr> + EchoNullableNonNullClassMap(const ::flutter::EncodableMap* class_map) = 0; virtual ErrorOr> EchoNullableEnum( const AnEnum* an_enum) = 0; virtual ErrorOr> EchoAnotherNullableEnum( @@ -992,48 +1041,48 @@ class HostIntegrationCoreApi { std::function> reply)> result) = 0; // Returns the passed in generic Object asynchronously. virtual void EchoAsyncObject( - const flutter::EncodableValue& an_object, - std::function reply)> result) = 0; + const ::flutter::EncodableValue& an_object, + std::function reply)> result) = 0; // Returns the passed list, to test asynchronous serialization and // deserialization. virtual void EchoAsyncList( - const flutter::EncodableList& list, - std::function reply)> result) = 0; + const ::flutter::EncodableList& list, + std::function reply)> result) = 0; // Returns the passed list, to test asynchronous serialization and // deserialization. virtual void EchoAsyncEnumList( - const flutter::EncodableList& enum_list, - std::function reply)> result) = 0; + const ::flutter::EncodableList& enum_list, + std::function reply)> result) = 0; // Returns the passed list, to test asynchronous serialization and // deserialization. virtual void EchoAsyncClassList( - const flutter::EncodableList& class_list, - std::function reply)> result) = 0; + const ::flutter::EncodableList& class_list, + std::function reply)> result) = 0; // Returns the passed map, to test asynchronous serialization and // deserialization. virtual void EchoAsyncMap( - const flutter::EncodableMap& map, - std::function reply)> result) = 0; + const ::flutter::EncodableMap& map, + std::function reply)> result) = 0; // Returns the passed map, to test asynchronous serialization and // deserialization. virtual void EchoAsyncStringMap( - const flutter::EncodableMap& string_map, - std::function reply)> result) = 0; + const ::flutter::EncodableMap& string_map, + std::function reply)> result) = 0; // Returns the passed map, to test asynchronous serialization and // deserialization. virtual void EchoAsyncIntMap( - const flutter::EncodableMap& int_map, - std::function reply)> result) = 0; + const ::flutter::EncodableMap& int_map, + std::function reply)> result) = 0; // Returns the passed map, to test asynchronous serialization and // deserialization. virtual void EchoAsyncEnumMap( - const flutter::EncodableMap& enum_map, - std::function reply)> result) = 0; + const ::flutter::EncodableMap& enum_map, + std::function reply)> result) = 0; // Returns the passed map, to test asynchronous serialization and // deserialization. virtual void EchoAsyncClassMap( - const flutter::EncodableMap& class_map, - std::function reply)> result) = 0; + const ::flutter::EncodableMap& class_map, + std::function reply)> result) = 0; // Returns the passed enum, to test asynchronous serialization and // deserialization. virtual void EchoAsyncEnum( @@ -1046,14 +1095,16 @@ class HostIntegrationCoreApi { std::function reply)> result) = 0; // Responds with an error from an async function returning a value. virtual void ThrowAsyncError( - std::function> reply)> + std::function< + void(ErrorOr> reply)> result) = 0; // Responds with an error from an async void function. virtual void ThrowAsyncErrorFromVoid( std::function reply)> result) = 0; // Responds with a Flutter error from an async function returning a value. virtual void ThrowAsyncFlutterError( - std::function> reply)> + std::function< + void(ErrorOr> reply)> result) = 0; // Returns the passed object, to test async serialization and deserialization. virtual void EchoAsyncAllTypes( @@ -1094,56 +1145,60 @@ class HostIntegrationCoreApi { result) = 0; // Returns the passed in generic Object asynchronously. virtual void EchoAsyncNullableObject( - const flutter::EncodableValue* an_object, - std::function> reply)> + const ::flutter::EncodableValue* an_object, + std::function< + void(ErrorOr> reply)> result) = 0; // Returns the passed list, to test asynchronous serialization and // deserialization. virtual void EchoAsyncNullableList( - const flutter::EncodableList* list, - std::function> reply)> + const ::flutter::EncodableList* list, + std::function< + void(ErrorOr> reply)> result) = 0; // Returns the passed list, to test asynchronous serialization and // deserialization. virtual void EchoAsyncNullableEnumList( - const flutter::EncodableList* enum_list, - std::function> reply)> + const ::flutter::EncodableList* enum_list, + std::function< + void(ErrorOr> reply)> result) = 0; // Returns the passed list, to test asynchronous serialization and // deserialization. virtual void EchoAsyncNullableClassList( - const flutter::EncodableList* class_list, - std::function> reply)> + const ::flutter::EncodableList* class_list, + std::function< + void(ErrorOr> reply)> result) = 0; // Returns the passed map, to test asynchronous serialization and // deserialization. virtual void EchoAsyncNullableMap( - const flutter::EncodableMap* map, - std::function> reply)> + const ::flutter::EncodableMap* map, + std::function> reply)> result) = 0; // Returns the passed map, to test asynchronous serialization and // deserialization. virtual void EchoAsyncNullableStringMap( - const flutter::EncodableMap* string_map, - std::function> reply)> + const ::flutter::EncodableMap* string_map, + std::function> reply)> result) = 0; // Returns the passed map, to test asynchronous serialization and // deserialization. virtual void EchoAsyncNullableIntMap( - const flutter::EncodableMap* int_map, - std::function> reply)> + const ::flutter::EncodableMap* int_map, + std::function> reply)> result) = 0; // Returns the passed map, to test asynchronous serialization and // deserialization. virtual void EchoAsyncNullableEnumMap( - const flutter::EncodableMap* enum_map, - std::function> reply)> + const ::flutter::EncodableMap* enum_map, + std::function> reply)> result) = 0; // Returns the passed map, to test asynchronous serialization and // deserialization. virtual void EchoAsyncNullableClassMap( - const flutter::EncodableMap* class_map, - std::function> reply)> + const ::flutter::EncodableMap* class_map, + std::function> reply)> result) = 0; // Returns the passed enum, to test asynchronous serialization and // deserialization. @@ -1165,7 +1220,8 @@ class HostIntegrationCoreApi { virtual void CallFlutterNoop( std::function reply)> result) = 0; virtual void CallFlutterThrowError( - std::function> reply)> + std::function< + void(ErrorOr> reply)> result) = 0; virtual void CallFlutterThrowErrorFromVoid( std::function reply)> result) = 0; @@ -1203,47 +1259,47 @@ class HostIntegrationCoreApi { const std::vector& list, std::function> reply)> result) = 0; virtual void CallFlutterEchoList( - const flutter::EncodableList& list, - std::function reply)> result) = 0; + const ::flutter::EncodableList& list, + std::function reply)> result) = 0; virtual void CallFlutterEchoEnumList( - const flutter::EncodableList& enum_list, - std::function reply)> result) = 0; + const ::flutter::EncodableList& enum_list, + std::function reply)> result) = 0; virtual void CallFlutterEchoClassList( - const flutter::EncodableList& class_list, - std::function reply)> result) = 0; + const ::flutter::EncodableList& class_list, + std::function reply)> result) = 0; virtual void CallFlutterEchoNonNullEnumList( - const flutter::EncodableList& enum_list, - std::function reply)> result) = 0; + const ::flutter::EncodableList& enum_list, + std::function reply)> result) = 0; virtual void CallFlutterEchoNonNullClassList( - const flutter::EncodableList& class_list, - std::function reply)> result) = 0; + const ::flutter::EncodableList& class_list, + std::function reply)> result) = 0; virtual void CallFlutterEchoMap( - const flutter::EncodableMap& map, - std::function reply)> result) = 0; + const ::flutter::EncodableMap& map, + std::function reply)> result) = 0; virtual void CallFlutterEchoStringMap( - const flutter::EncodableMap& string_map, - std::function reply)> result) = 0; + const ::flutter::EncodableMap& string_map, + std::function reply)> result) = 0; virtual void CallFlutterEchoIntMap( - const flutter::EncodableMap& int_map, - std::function reply)> result) = 0; + const ::flutter::EncodableMap& int_map, + std::function reply)> result) = 0; virtual void CallFlutterEchoEnumMap( - const flutter::EncodableMap& enum_map, - std::function reply)> result) = 0; + const ::flutter::EncodableMap& enum_map, + std::function reply)> result) = 0; virtual void CallFlutterEchoClassMap( - const flutter::EncodableMap& class_map, - std::function reply)> result) = 0; + const ::flutter::EncodableMap& class_map, + std::function reply)> result) = 0; virtual void CallFlutterEchoNonNullStringMap( - const flutter::EncodableMap& string_map, - std::function reply)> result) = 0; + const ::flutter::EncodableMap& string_map, + std::function reply)> result) = 0; virtual void CallFlutterEchoNonNullIntMap( - const flutter::EncodableMap& int_map, - std::function reply)> result) = 0; + const ::flutter::EncodableMap& int_map, + std::function reply)> result) = 0; virtual void CallFlutterEchoNonNullEnumMap( - const flutter::EncodableMap& enum_map, - std::function reply)> result) = 0; + const ::flutter::EncodableMap& enum_map, + std::function reply)> result) = 0; virtual void CallFlutterEchoNonNullClassMap( - const flutter::EncodableMap& class_map, - std::function reply)> result) = 0; + const ::flutter::EncodableMap& class_map, + std::function reply)> result) = 0; virtual void CallFlutterEchoEnum( const AnEnum& an_enum, std::function reply)> result) = 0; @@ -1268,60 +1324,65 @@ class HostIntegrationCoreApi { std::function>> reply)> result) = 0; virtual void CallFlutterEchoNullableList( - const flutter::EncodableList* list, - std::function> reply)> + const ::flutter::EncodableList* list, + std::function< + void(ErrorOr> reply)> result) = 0; virtual void CallFlutterEchoNullableEnumList( - const flutter::EncodableList* enum_list, - std::function> reply)> + const ::flutter::EncodableList* enum_list, + std::function< + void(ErrorOr> reply)> result) = 0; virtual void CallFlutterEchoNullableClassList( - const flutter::EncodableList* class_list, - std::function> reply)> + const ::flutter::EncodableList* class_list, + std::function< + void(ErrorOr> reply)> result) = 0; virtual void CallFlutterEchoNullableNonNullEnumList( - const flutter::EncodableList* enum_list, - std::function> reply)> + const ::flutter::EncodableList* enum_list, + std::function< + void(ErrorOr> reply)> result) = 0; virtual void CallFlutterEchoNullableNonNullClassList( - const flutter::EncodableList* class_list, - std::function> reply)> + const ::flutter::EncodableList* class_list, + std::function< + void(ErrorOr> reply)> result) = 0; virtual void CallFlutterEchoNullableMap( - const flutter::EncodableMap* map, - std::function> reply)> + const ::flutter::EncodableMap* map, + std::function> reply)> result) = 0; virtual void CallFlutterEchoNullableStringMap( - const flutter::EncodableMap* string_map, - std::function> reply)> + const ::flutter::EncodableMap* string_map, + std::function> reply)> result) = 0; virtual void CallFlutterEchoNullableIntMap( - const flutter::EncodableMap* int_map, - std::function> reply)> + const ::flutter::EncodableMap* int_map, + std::function> reply)> result) = 0; virtual void CallFlutterEchoNullableEnumMap( - const flutter::EncodableMap* enum_map, - std::function> reply)> + const ::flutter::EncodableMap* enum_map, + std::function> reply)> result) = 0; virtual void CallFlutterEchoNullableClassMap( - const flutter::EncodableMap* class_map, - std::function> reply)> + const ::flutter::EncodableMap* class_map, + std::function> reply)> result) = 0; virtual void CallFlutterEchoNullableNonNullStringMap( - const flutter::EncodableMap* string_map, - std::function> reply)> + const ::flutter::EncodableMap* string_map, + std::function> reply)> result) = 0; virtual void CallFlutterEchoNullableNonNullIntMap( - const flutter::EncodableMap* int_map, - std::function> reply)> + const ::flutter::EncodableMap* int_map, + std::function> reply)> result) = 0; virtual void CallFlutterEchoNullableNonNullEnumMap( - const flutter::EncodableMap* enum_map, - std::function> reply)> + const ::flutter::EncodableMap* enum_map, + std::function> reply)> result) = 0; virtual void CallFlutterEchoNullableNonNullClassMap( - const flutter::EncodableMap* class_map, - std::function> reply)> + const ::flutter::EncodableMap* class_map, + std::function> reply)> result) = 0; virtual void CallFlutterEchoNullableEnum( const AnEnum* an_enum, @@ -1335,16 +1396,16 @@ class HostIntegrationCoreApi { std::function reply)> result) = 0; // The codec used by HostIntegrationCoreApi. - static const flutter::StandardMessageCodec& GetCodec(); + static const ::flutter::StandardMessageCodec& GetCodec(); // Sets up an instance of `HostIntegrationCoreApi` to handle messages through // the `binary_messenger`. - static void SetUp(flutter::BinaryMessenger* binary_messenger, + static void SetUp(::flutter::BinaryMessenger* binary_messenger, HostIntegrationCoreApi* api); - static void SetUp(flutter::BinaryMessenger* binary_messenger, + static void SetUp(::flutter::BinaryMessenger* binary_messenger, HostIntegrationCoreApi* api, const std::string& message_channel_suffix); - static flutter::EncodableValue WrapError(std::string_view error_message); - static flutter::EncodableValue WrapError(const FlutterError& error); + static ::flutter::EncodableValue WrapError(std::string_view error_message); + static ::flutter::EncodableValue WrapError(const FlutterError& error); protected: HostIntegrationCoreApi() = default; @@ -1356,17 +1417,17 @@ class HostIntegrationCoreApi { // called from C++. class FlutterIntegrationCoreApi { public: - FlutterIntegrationCoreApi(flutter::BinaryMessenger* binary_messenger); - FlutterIntegrationCoreApi(flutter::BinaryMessenger* binary_messenger, + FlutterIntegrationCoreApi(::flutter::BinaryMessenger* binary_messenger); + FlutterIntegrationCoreApi(::flutter::BinaryMessenger* binary_messenger, const std::string& message_channel_suffix); - static const flutter::StandardMessageCodec& GetCodec(); + static const ::flutter::StandardMessageCodec& GetCodec(); // A no-op function taking no arguments and returning no value, to sanity // test basic calling. void Noop(std::function&& on_success, std::function&& on_error); // Responds with an error from an async function returning a value. void ThrowError( - std::function&& on_success, + std::function&& on_success, std::function&& on_error); // Responds with an error from an async void function. void ThrowErrorFromVoid(std::function&& on_success, @@ -1420,72 +1481,73 @@ class FlutterIntegrationCoreApi { std::function&)>&& on_success, std::function&& on_error); // Returns the passed list, to test serialization and deserialization. - void EchoList(const flutter::EncodableList& list, - std::function&& on_success, - std::function&& on_error); + void EchoList( + const ::flutter::EncodableList& list, + std::function&& on_success, + std::function&& on_error); // Returns the passed list, to test serialization and deserialization. void EchoEnumList( - const flutter::EncodableList& enum_list, - std::function&& on_success, + const ::flutter::EncodableList& enum_list, + std::function&& on_success, std::function&& on_error); // Returns the passed list, to test serialization and deserialization. void EchoClassList( - const flutter::EncodableList& class_list, - std::function&& on_success, + const ::flutter::EncodableList& class_list, + std::function&& on_success, std::function&& on_error); // Returns the passed list, to test serialization and deserialization. void EchoNonNullEnumList( - const flutter::EncodableList& enum_list, - std::function&& on_success, + const ::flutter::EncodableList& enum_list, + std::function&& on_success, std::function&& on_error); // Returns the passed list, to test serialization and deserialization. void EchoNonNullClassList( - const flutter::EncodableList& class_list, - std::function&& on_success, + const ::flutter::EncodableList& class_list, + std::function&& on_success, std::function&& on_error); // Returns the passed map, to test serialization and deserialization. - void EchoMap(const flutter::EncodableMap& map, - std::function&& on_success, + void EchoMap(const ::flutter::EncodableMap& map, + std::function&& on_success, std::function&& on_error); // Returns the passed map, to test serialization and deserialization. void EchoStringMap( - const flutter::EncodableMap& string_map, - std::function&& on_success, + const ::flutter::EncodableMap& string_map, + std::function&& on_success, std::function&& on_error); // Returns the passed map, to test serialization and deserialization. void EchoIntMap( - const flutter::EncodableMap& int_map, - std::function&& on_success, + const ::flutter::EncodableMap& int_map, + std::function&& on_success, std::function&& on_error); // Returns the passed map, to test serialization and deserialization. void EchoEnumMap( - const flutter::EncodableMap& enum_map, - std::function&& on_success, + const ::flutter::EncodableMap& enum_map, + std::function&& on_success, std::function&& on_error); // Returns the passed map, to test serialization and deserialization. void EchoClassMap( - const flutter::EncodableMap& class_map, - std::function&& on_success, + const ::flutter::EncodableMap& class_map, + std::function&& on_success, std::function&& on_error); // Returns the passed map, to test serialization and deserialization. void EchoNonNullStringMap( - const flutter::EncodableMap& string_map, - std::function&& on_success, + const ::flutter::EncodableMap& string_map, + std::function&& on_success, std::function&& on_error); // Returns the passed map, to test serialization and deserialization. void EchoNonNullIntMap( - const flutter::EncodableMap& int_map, - std::function&& on_success, + const ::flutter::EncodableMap& int_map, + std::function&& on_success, std::function&& on_error); // Returns the passed map, to test serialization and deserialization. void EchoNonNullEnumMap( - const flutter::EncodableMap& enum_map, - std::function&& on_success, + const ::flutter::EncodableMap& enum_map, + std::function&& on_success, std::function&& on_error); // Returns the passed map, to test serialization and deserialization. void EchoNonNullClassMap( - const flutter::EncodableMap& class_map, - std::function&& on_success, + const ::flutter::EncodableMap& class_map, + std::function&& on_success, std::function&& on_error); // Returns the passed enum to test serialization and deserialization. void EchoEnum(const AnEnum& an_enum, @@ -1518,73 +1580,73 @@ class FlutterIntegrationCoreApi { std::function&& on_error); // Returns the passed list, to test serialization and deserialization. void EchoNullableList( - const flutter::EncodableList* list, - std::function&& on_success, + const ::flutter::EncodableList* list, + std::function&& on_success, std::function&& on_error); // Returns the passed list, to test serialization and deserialization. void EchoNullableEnumList( - const flutter::EncodableList* enum_list, - std::function&& on_success, + const ::flutter::EncodableList* enum_list, + std::function&& on_success, std::function&& on_error); // Returns the passed list, to test serialization and deserialization. void EchoNullableClassList( - const flutter::EncodableList* class_list, - std::function&& on_success, + const ::flutter::EncodableList* class_list, + std::function&& on_success, std::function&& on_error); // Returns the passed list, to test serialization and deserialization. void EchoNullableNonNullEnumList( - const flutter::EncodableList* enum_list, - std::function&& on_success, + const ::flutter::EncodableList* enum_list, + std::function&& on_success, std::function&& on_error); // Returns the passed list, to test serialization and deserialization. void EchoNullableNonNullClassList( - const flutter::EncodableList* class_list, - std::function&& on_success, + const ::flutter::EncodableList* class_list, + std::function&& on_success, std::function&& on_error); // Returns the passed map, to test serialization and deserialization. void EchoNullableMap( - const flutter::EncodableMap* map, - std::function&& on_success, + const ::flutter::EncodableMap* map, + std::function&& on_success, std::function&& on_error); // Returns the passed map, to test serialization and deserialization. void EchoNullableStringMap( - const flutter::EncodableMap* string_map, - std::function&& on_success, + const ::flutter::EncodableMap* string_map, + std::function&& on_success, std::function&& on_error); // Returns the passed map, to test serialization and deserialization. void EchoNullableIntMap( - const flutter::EncodableMap* int_map, - std::function&& on_success, + const ::flutter::EncodableMap* int_map, + std::function&& on_success, std::function&& on_error); // Returns the passed map, to test serialization and deserialization. void EchoNullableEnumMap( - const flutter::EncodableMap* enum_map, - std::function&& on_success, + const ::flutter::EncodableMap* enum_map, + std::function&& on_success, std::function&& on_error); // Returns the passed map, to test serialization and deserialization. void EchoNullableClassMap( - const flutter::EncodableMap* class_map, - std::function&& on_success, + const ::flutter::EncodableMap* class_map, + std::function&& on_success, std::function&& on_error); // Returns the passed map, to test serialization and deserialization. void EchoNullableNonNullStringMap( - const flutter::EncodableMap* string_map, - std::function&& on_success, + const ::flutter::EncodableMap* string_map, + std::function&& on_success, std::function&& on_error); // Returns the passed map, to test serialization and deserialization. void EchoNullableNonNullIntMap( - const flutter::EncodableMap* int_map, - std::function&& on_success, + const ::flutter::EncodableMap* int_map, + std::function&& on_success, std::function&& on_error); // Returns the passed map, to test serialization and deserialization. void EchoNullableNonNullEnumMap( - const flutter::EncodableMap* enum_map, - std::function&& on_success, + const ::flutter::EncodableMap* enum_map, + std::function&& on_success, std::function&& on_error); // Returns the passed map, to test serialization and deserialization. void EchoNullableNonNullClassMap( - const flutter::EncodableMap* class_map, - std::function&& on_success, + const ::flutter::EncodableMap* class_map, + std::function&& on_success, std::function&& on_error); // Returns the passed enum to test serialization and deserialization. void EchoNullableEnum(const AnEnum* an_enum, @@ -1605,7 +1667,7 @@ class FlutterIntegrationCoreApi { std::function&& on_error); private: - flutter::BinaryMessenger* binary_messenger_; + ::flutter::BinaryMessenger* binary_messenger_; std::string message_channel_suffix_; }; @@ -1621,16 +1683,16 @@ class HostTrivialApi { virtual std::optional Noop() = 0; // The codec used by HostTrivialApi. - static const flutter::StandardMessageCodec& GetCodec(); + static const ::flutter::StandardMessageCodec& GetCodec(); // Sets up an instance of `HostTrivialApi` to handle messages through the // `binary_messenger`. - static void SetUp(flutter::BinaryMessenger* binary_messenger, + static void SetUp(::flutter::BinaryMessenger* binary_messenger, HostTrivialApi* api); - static void SetUp(flutter::BinaryMessenger* binary_messenger, + static void SetUp(::flutter::BinaryMessenger* binary_messenger, HostTrivialApi* api, const std::string& message_channel_suffix); - static flutter::EncodableValue WrapError(std::string_view error_message); - static flutter::EncodableValue WrapError(const FlutterError& error); + static ::flutter::EncodableValue WrapError(std::string_view error_message); + static ::flutter::EncodableValue WrapError(const FlutterError& error); protected: HostTrivialApi() = default; @@ -1650,16 +1712,16 @@ class HostSmallApi { std::function reply)> result) = 0; // The codec used by HostSmallApi. - static const flutter::StandardMessageCodec& GetCodec(); + static const ::flutter::StandardMessageCodec& GetCodec(); // Sets up an instance of `HostSmallApi` to handle messages through the // `binary_messenger`. - static void SetUp(flutter::BinaryMessenger* binary_messenger, + static void SetUp(::flutter::BinaryMessenger* binary_messenger, HostSmallApi* api); - static void SetUp(flutter::BinaryMessenger* binary_messenger, + static void SetUp(::flutter::BinaryMessenger* binary_messenger, HostSmallApi* api, const std::string& message_channel_suffix); - static flutter::EncodableValue WrapError(std::string_view error_message); - static flutter::EncodableValue WrapError(const FlutterError& error); + static ::flutter::EncodableValue WrapError(std::string_view error_message); + static ::flutter::EncodableValue WrapError(const FlutterError& error); protected: HostSmallApi() = default; @@ -1670,10 +1732,10 @@ class HostSmallApi { // called from C++. class FlutterSmallApi { public: - FlutterSmallApi(flutter::BinaryMessenger* binary_messenger); - FlutterSmallApi(flutter::BinaryMessenger* binary_messenger, + FlutterSmallApi(::flutter::BinaryMessenger* binary_messenger); + FlutterSmallApi(::flutter::BinaryMessenger* binary_messenger, const std::string& message_channel_suffix); - static const flutter::StandardMessageCodec& GetCodec(); + static const ::flutter::StandardMessageCodec& GetCodec(); void EchoWrappedList(const TestMessage& msg, std::function&& on_success, std::function&& on_error); @@ -1682,7 +1744,7 @@ class FlutterSmallApi { std::function&& on_error); private: - flutter::BinaryMessenger* binary_messenger_; + ::flutter::BinaryMessenger* binary_messenger_; std::string message_channel_suffix_; }; diff --git a/packages/pigeon/platform_tests/test_plugin/windows/test/equality_test.cpp b/packages/pigeon/platform_tests/test_plugin/windows/test/equality_test.cpp new file mode 100644 index 000000000000..79cfe24f9cb8 --- /dev/null +++ b/packages/pigeon/platform_tests/test_plugin/windows/test/equality_test.cpp @@ -0,0 +1,104 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include + +#include "pigeon/core_tests.gen.h" + +namespace test_plugin { +namespace test { + +using namespace core_tests_pigeontest; + +TEST(EqualityTests, NaNEquality) { + AllNullableTypes all1; + all1.set_a_nullable_double(NAN); + + AllNullableTypes all2; + all2.set_a_nullable_double(NAN); + + EXPECT_EQ(all1, all2); + + AllNullableTypes all3; + all3.set_a_nullable_double(1.0); + + EXPECT_NE(all1, all3); +} + +TEST(EqualityTests, OptionalNaNEquality) { + AllNullableTypes all1; + // std::optional handled via set_a_nullable_double + all1.set_a_nullable_double(NAN); + + AllNullableTypes all2; + all2.set_a_nullable_double(NAN); + + EXPECT_EQ(all1, all2); +} + +TEST(EqualityTests, NestedNaNEquality) { + std::vector list = {NAN}; + AllNullableTypes all1; + all1.set_double_list(list); + + AllNullableTypes all2; + all2.set_double_list(list); + + EXPECT_EQ(all1, all2); +} + +TEST(EqualityTests, SignedZeroEquality) { + AllNullableTypes all1; + all1.set_a_nullable_double(0.0); + + AllNullableTypes all2; + all2.set_a_nullable_double(-0.0); + + EXPECT_EQ(all1, all2); +} + +TEST(EqualityTests, NestedZeroListEquality) { + std::vector list1 = {0.0}; + AllNullableTypes all1; + all1.set_double_list(list1); + + std::vector list2 = {-0.0}; + AllNullableTypes all2; + all2.set_double_list(list2); + + EXPECT_EQ(all1, all2); +} + +TEST(EqualityTests, ZeroMapKeyEquality) { + std::map map1; + map1[flutter::EncodableValue(0.0)] = flutter::EncodableValue("a"); + AllNullableTypes all1; + all1.set_map(map1); + + std::map map2; + map2[flutter::EncodableValue(-0.0)] = flutter::EncodableValue("a"); + AllNullableTypes all2; + all2.set_map(map2); + + EXPECT_EQ(all1, all2); +} + +TEST(EqualityTests, ZeroMapValueEquality) { + std::map map1; + map1[flutter::EncodableValue("a")] = flutter::EncodableValue(0.0); + AllNullableTypes all1; + all1.set_map(map1); + + std::map map2; + map2[flutter::EncodableValue("a")] = flutter::EncodableValue(-0.0); + AllNullableTypes all2; + all2.set_map(map2); + + EXPECT_EQ(all1, all2); +} + +} // namespace test +} // namespace test_plugin diff --git a/packages/pigeon/platform_tests/test_plugin/windows/test/non_null_fields_test.cpp b/packages/pigeon/platform_tests/test_plugin/windows/test/non_null_fields_test.cpp index 07412dc84378..d7ea926f62b3 100644 --- a/packages/pigeon/platform_tests/test_plugin/windows/test/non_null_fields_test.cpp +++ b/packages/pigeon/platform_tests/test_plugin/windows/test/non_null_fields_test.cpp @@ -14,4 +14,13 @@ TEST(NonNullFields, Build) { EXPECT_EQ(request.query(), "hello"); } +TEST(NonNullFields, Equality) { + NonNullFieldSearchRequest request1("hello"); + NonNullFieldSearchRequest request2("hello"); + NonNullFieldSearchRequest request3("world"); + + EXPECT_EQ(request1, request2); + EXPECT_NE(request1, request3); +} + } // namespace non_null_fields_pigeontest diff --git a/packages/pigeon/platform_tests/test_plugin/windows/test/null_fields_test.cpp b/packages/pigeon/platform_tests/test_plugin/windows/test/null_fields_test.cpp index 9a0cf75e8259..46f16079cc45 100644 --- a/packages/pigeon/platform_tests/test_plugin/windows/test/null_fields_test.cpp +++ b/packages/pigeon/platform_tests/test_plugin/windows/test/null_fields_test.cpp @@ -211,4 +211,34 @@ TEST_F(NullFieldsTest, ReplyToListWithNulls) { } } +TEST(NullFields, Equality) { + NullFieldsSearchRequest request1(1); + request1.set_query("hello"); + NullFieldsSearchRequest request2(1); + request2.set_query("hello"); + NullFieldsSearchRequest request3(2); + request3.set_query("hello"); + NullFieldsSearchRequest request4(1); + request4.set_query("world"); + + EXPECT_EQ(request1, request2); + EXPECT_FALSE(request1 == request3); + EXPECT_FALSE(request1 == request4); + + NullFieldsSearchReply reply1; + reply1.set_result("result"); + reply1.set_request(request1); + + NullFieldsSearchReply reply2; + reply2.set_result("result"); + reply2.set_request(request2); + + NullFieldsSearchReply reply3; + reply3.set_result("result"); + reply3.set_request(request3); + + EXPECT_EQ(reply1, reply2); + EXPECT_FALSE(reply1 == reply3); +} + } // namespace null_fields_pigeontest diff --git a/packages/pigeon/platform_tests/test_plugin/windows/test_plugin.cpp b/packages/pigeon/platform_tests/test_plugin/windows/test_plugin.cpp index bb77ea902dfc..3e6056f3a810 100644 --- a/packages/pigeon/platform_tests/test_plugin/windows/test_plugin.cpp +++ b/packages/pigeon/platform_tests/test_plugin/windows/test_plugin.cpp @@ -97,6 +97,21 @@ ErrorOr> TestPlugin::EchoAllNullableTypes( return std::optional(*everything); } +ErrorOr TestPlugin::AreAllNullableTypesEqual(const AllNullableTypes& a, + const AllNullableTypes& b) { + return a == b; +} + +ErrorOr TestPlugin::GetAllNullableTypesHash( + const AllNullableTypes& value) { + return (int64_t)value.Hash(); +} + +ErrorOr TestPlugin::GetAllNullableTypesWithoutRecursionHash( + const AllNullableTypesWithoutRecursion& value) { + return (int64_t)value.Hash(); +} + ErrorOr> TestPlugin::EchoAllNullableTypesWithoutRecursion( const AllNullableTypesWithoutRecursion* everything) { diff --git a/packages/pigeon/platform_tests/test_plugin/windows/test_plugin.h b/packages/pigeon/platform_tests/test_plugin/windows/test_plugin.h index 002a73291335..a52bd83f03a2 100644 --- a/packages/pigeon/platform_tests/test_plugin/windows/test_plugin.h +++ b/packages/pigeon/platform_tests/test_plugin/windows/test_plugin.h @@ -60,6 +60,15 @@ class TestPlugin : public flutter::Plugin, std::optional> EchoAllNullableTypes( const core_tests_pigeontest::AllNullableTypes* everything) override; + core_tests_pigeontest::ErrorOr AreAllNullableTypesEqual( + const core_tests_pigeontest::AllNullableTypes& a, + const core_tests_pigeontest::AllNullableTypes& b) override; + core_tests_pigeontest::ErrorOr GetAllNullableTypesHash( + const core_tests_pigeontest::AllNullableTypes& value) override; + core_tests_pigeontest::ErrorOr + GetAllNullableTypesWithoutRecursionHash( + const core_tests_pigeontest::AllNullableTypesWithoutRecursion& value) + override; core_tests_pigeontest::ErrorOr< std::optional> EchoAllNullableTypesWithoutRecursion( diff --git a/packages/pigeon/pubspec.yaml b/packages/pigeon/pubspec.yaml index 6298399391e7..0fc8a2cdd64c 100644 --- a/packages/pigeon/pubspec.yaml +++ b/packages/pigeon/pubspec.yaml @@ -2,14 +2,14 @@ name: pigeon description: Code generator tool to make communication between Flutter and the host platform type-safe and easier. repository: https://github.com/flutter/packages/tree/main/packages/pigeon issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+pigeon%22 -version: 26.1.2 # This must match the version in lib/src/generator_tools.dart +version: 26.3.1 # This must match the version in lib/src/generator_tools.dart environment: - sdk: ^3.8.0 + sdk: ^3.9.0 dependencies: analyzer: ">=8.0.0 <10.0.0" - args: ^2.1.0 + args: ^2.5.0 code_builder: ^4.10.0 collection: ^1.15.0 dart_style: ^3.0.0 diff --git a/packages/pigeon/test/ast_generator_test.dart b/packages/pigeon/test/ast_generator_test.dart index b6aad7533527..98a74f8a25de 100644 --- a/packages/pigeon/test/ast_generator_test.dart +++ b/packages/pigeon/test/ast_generator_test.dart @@ -8,7 +8,7 @@ import 'package:test/test.dart'; void main() { test('gen one class', () { - final Class classDefinition = Class( + final classDefinition = Class( name: 'Foobar', fields: [ NamedType( @@ -17,14 +17,14 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [], classes: [classDefinition], enums: [], ); - final StringBuffer sink = StringBuffer(); + final sink = StringBuffer(); generateAst(root, sink); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('Foobar')); expect(code, contains('dataType1')); expect(code, contains('field1')); diff --git a/packages/pigeon/test/cpp_generator_test.dart b/packages/pigeon/test/cpp_generator_test.dart index 0662261b9eee..0c77bed2b1de 100644 --- a/packages/pigeon/test/cpp_generator_test.dart +++ b/packages/pigeon/test/cpp_generator_test.dart @@ -27,7 +27,7 @@ final Enum emptyEnum = Enum( void main() { test('gen one api', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -77,48 +77,46 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('class Input')); expect(code, contains('class Output')); expect(code, contains('class Api')); expect(code, contains('virtual ~Api() {}\n')); } { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('Input::Input()')); expect(code, contains('Output::Output')); expect( @@ -126,7 +124,7 @@ void main() { contains( RegExp( r'void Api::SetUp\(\s*' - r'flutter::BinaryMessenger\* binary_messenger,\s*' + r'::flutter::BinaryMessenger\* binary_messenger,\s*' r'Api\* api\s*\)', ), ), @@ -135,14 +133,14 @@ void main() { }); test('naming follows style', () { - final Enum anEnum = Enum( + final anEnum = Enum( name: 'AnEnum', members: [ EnumMember(name: 'one'), EnumMember(name: 'fortyTwo'), ], ); - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -200,24 +198,23 @@ void main() { enums: [anEnum], ); { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); // Method name and argument names should be adjusted. expect(code, contains(' DoSomething(const Input& some_input)')); // Getters and setters should use optional getter/setter style. @@ -233,24 +230,23 @@ void main() { expect(code, contains('kFortyTwo')); } { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('encodable_some_input')); expect(code, contains('Output::output_field()')); expect(code, contains('Output::set_output_field(bool value_arg)')); @@ -258,7 +254,7 @@ void main() { }); test('FlutterError fields are private with public accessors', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -287,24 +283,23 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code.split('\n'), @@ -314,19 +309,19 @@ void main() { contains(' const std::string& code() const { return code_; }'), contains(' const std::string& message() const { return message_; }'), contains( - ' const flutter::EncodableValue& details() const { return details_; }', + ' const ::flutter::EncodableValue& details() const { return details_; }', ), contains(' private:'), contains(' std::string code_;'), contains(' std::string message_;'), - contains(' flutter::EncodableValue details_;'), + contains(' ::flutter::EncodableValue details_;'), ]), ); } }); test('Error field is private with public accessors', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -356,24 +351,23 @@ void main() { containsHostApi: true, ); { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code.split('\n'), @@ -391,7 +385,7 @@ void main() { }); test('Spaces before {', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -441,53 +435,51 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, isNot(contains('){'))); expect(code, isNot(contains('const{'))); } { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, isNot(contains('){'))); expect(code, isNot(contains('const{'))); } }); test('include blocks follow style', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -516,24 +508,23 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains(''' @@ -549,24 +540,23 @@ void main() { ); } { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - headerIncludePath: 'a_header.h', - cppHeaderOut: '', - cppSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalCppOptions( + headerIncludePath: 'a_header.h', + cppHeaderOut: '', + cppSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains(''' @@ -577,6 +567,8 @@ void main() { #include #include +#include +#include #include #include #include @@ -586,7 +578,7 @@ void main() { }); test('namespaces follows style', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -615,55 +607,53 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - namespace: 'foo', - headerIncludePath: '', - cppHeaderOut: '', - cppSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalCppOptions( + namespace: 'foo', + headerIncludePath: '', + cppHeaderOut: '', + cppSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('namespace foo {')); expect(code, contains('} // namespace foo')); } { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - namespace: 'foo', - headerIncludePath: '', - cppHeaderOut: '', - cppSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalCppOptions( + namespace: 'foo', + headerIncludePath: '', + cppHeaderOut: '', + cppSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('namespace foo {')); expect(code, contains('} // namespace foo')); } }); test('data classes handle nullable fields', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -725,24 +715,23 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); // There should be a default constructor. expect(code, contains('Nested();')); @@ -788,24 +777,23 @@ void main() { expect(code, contains('std::unique_ptr nullable_nested_')); } { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); // There should be a default constructor. expect(code, contains('Nested::Nested() {}')); @@ -893,7 +881,7 @@ void main() { }); test('data classes handle non-nullable fields', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -958,24 +946,23 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); // There should not be a default constructor. expect(code, isNot(contains('Nested();'))); @@ -1012,24 +999,23 @@ void main() { expect(code, contains('std::unique_ptr non_nullable_nested_;')); } { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); // There should not be a default constructor. expect(code, isNot(contains('Nested::Nested() {}'))); @@ -1074,7 +1060,7 @@ void main() { }); test('host nullable return types map correctly', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1158,24 +1144,23 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains('ErrorOr> ReturnNullableBool()'), @@ -1191,13 +1176,13 @@ void main() { expect( code, contains( - 'ErrorOr> ReturnNullableList()', + 'ErrorOr> ReturnNullableList()', ), ); expect( code, contains( - 'ErrorOr> ReturnNullableMap()', + 'ErrorOr> ReturnNullableMap()', ), ); expect( @@ -1210,7 +1195,7 @@ void main() { }); test('host non-nullable return types map correctly', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1294,35 +1279,34 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('ErrorOr ReturnBool()')); expect(code, contains('ErrorOr ReturnInt()')); expect(code, contains('ErrorOr ReturnString()')); - expect(code, contains('ErrorOr ReturnList()')); - expect(code, contains('ErrorOr ReturnMap()')); + expect(code, contains('ErrorOr<::flutter::EncodableList> ReturnList()')); + expect(code, contains('ErrorOr<::flutter::EncodableMap> ReturnMap()')); expect(code, contains('ErrorOr ReturnDataClass()')); } }); test('host nullable arguments map correctly', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1408,24 +1392,23 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -1434,33 +1417,32 @@ void main() { r'const bool\* a_bool,\s*' r'const int64_t\* an_int,\s*' r'const std::string\* a_string,\s*' - r'const flutter::EncodableList\* a_list,\s*' - r'const flutter::EncodableMap\* a_map,\s*' + r'const ::flutter::EncodableList\* a_list,\s*' + r'const ::flutter::EncodableMap\* a_map,\s*' r'const ParameterObject\* an_object,\s*' - r'const flutter::EncodableValue\* a_generic_object\s*\)', + r'const ::flutter::EncodableValue\* a_generic_object\s*\)', ), ), ); } { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); // Most types should just use get_if, since the parameter is a pointer, // and get_if will automatically handle null values (since a null // EncodableValue will not match the queried type, so get_if will return @@ -1520,7 +1502,7 @@ void main() { }); test('host non-nullable arguments map correctly', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1606,24 +1588,23 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -1632,33 +1613,32 @@ void main() { r'bool a_bool,\s*' r'int64_t an_int,\s*' r'const std::string& a_string,\s*' - r'const flutter::EncodableList& a_list,\s*' - r'const flutter::EncodableMap& a_map,\s*' + r'const ::flutter::EncodableList& a_list,\s*' + r'const ::flutter::EncodableMap& a_map,\s*' r'const ParameterObject& an_object,\s*' - r'const flutter::EncodableValue& a_generic_object\s*\)', + r'const ::flutter::EncodableValue& a_generic_object\s*\)', ), ), ); } { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); // Most types should extract references. Since the type is non-nullable, // there's only one possible type. expect( @@ -1712,7 +1692,7 @@ void main() { }); test('flutter nullable arguments map correctly', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1801,24 +1781,23 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); // Nullable arguments should all be pointers. This will make them somewhat // awkward for some uses (literals, values that could be inlined) but // unlike setters there's no way to provide reference-based alternatives @@ -1836,10 +1815,10 @@ void main() { // Nullable strings use std::string* rather than std::string_view* // since there's no implicit conversion for pointer types. r'const std::string\* a_string,\s*' - r'const flutter::EncodableList\* a_list,\s*' - r'const flutter::EncodableMap\* a_map,\s*' + r'const ::flutter::EncodableList\* a_list,\s*' + r'const ::flutter::EncodableMap\* a_map,\s*' r'const ParameterObject\* an_object,\s*' - r'const flutter::EncodableValue\* a_generic_object,', + r'const ::flutter::EncodableValue\* a_generic_object,', ), ), ); @@ -1855,24 +1834,23 @@ void main() { ); } { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); // All types pass nulls values when the pointer is null. // Standard types are wrapped an EncodableValues. expect( @@ -1908,7 +1886,7 @@ void main() { }); test('flutter non-nullable arguments map correctly', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1997,24 +1975,23 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -2026,10 +2003,10 @@ void main() { // nullable strings. r'const std::string& a_string,\s*' // Non-POD types use const references. - r'const flutter::EncodableList& a_list,\s*' - r'const flutter::EncodableMap& a_map,\s*' + r'const ::flutter::EncodableList& a_list,\s*' + r'const ::flutter::EncodableMap& a_map,\s*' r'const ParameterObject& an_object,\s*' - r'const flutter::EncodableValue& a_generic_object,\s*', + r'const ::flutter::EncodableValue& a_generic_object,\s*', ), ), ); @@ -2045,24 +2022,23 @@ void main() { ); } { - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); // Standard types are wrapped in EncodableValues. expect(code, contains('EncodableValue(a_bool_arg)')); expect(code, contains('EncodableValue(an_int_arg)')); @@ -2075,7 +2051,7 @@ void main() { }); test('host API argument extraction uses references', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -2101,24 +2077,23 @@ void main() { enums: [], ); - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); // A bare 'auto' here would create a copy, not a reference, which is // inefficient. expect( @@ -2129,7 +2104,7 @@ void main() { }); test('enum argument', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Bar', @@ -2175,7 +2150,7 @@ void main() { }); test('transfers documentation comments', () { - final List comments = [ + final comments = [ ' api comment', ' api method comment', ' class comment', @@ -2183,12 +2158,12 @@ void main() { ' enum comment', ' enum member comment', ]; - int count = 0; + var count = 0; - final List unspacedComments = ['////////']; - int unspacedCount = 0; + final unspacedComments = ['////////']; + var unspacedCount = 0; - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -2249,32 +2224,31 @@ void main() { ), ], ); - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - headerIncludePath: 'foo', - cppHeaderOut: '', - cppSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalCppOptions( + headerIncludePath: 'foo', + cppHeaderOut: '', + cppSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); - for (final String comment in comments) { + final code = sink.toString(); + for (final comment in comments) { expect(code, contains('//$comment')); } expect(code, contains('// ///')); }); test('creates custom codecs', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -2324,29 +2298,28 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); - expect(code, contains(' : public flutter::StandardCodecSerializer')); + final code = sink.toString(); + expect(code, contains(' : public ::flutter::StandardCodecSerializer')); }); test('Does not send unwrapped EncodableLists', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -2424,30 +2397,29 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, isNot(contains('reply(wrap'))); expect(code, contains('reply(EncodableValue(')); }); test('does not keep unowned references in async handlers', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'HostApi', @@ -2513,24 +2485,23 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); // Nothing should be captured by reference for async handlers, since their // lifetime is unknown (and expected to be longer than the stack's). expect(code, isNot(contains('&reply'))); @@ -2542,7 +2513,7 @@ void main() { }); test('connection error contains channel name', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -2568,24 +2539,23 @@ void main() { enums: [], containsFlutterApi: true, ); - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -2596,7 +2566,7 @@ void main() { }); test('stack allocates the message channel.', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -2621,24 +2591,23 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const CppGenerator generator = CppGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalCppOptions( - cppHeaderOut: '', - cppSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -2647,4 +2616,170 @@ void main() { ); expect(code, contains('channel.Send')); }); + + test('data class equality', () { + final root = Root( + apis: [], + classes: [ + Class( + name: 'Foo', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'int', isNullable: false), + name: 'bar', + ), + ], + ), + ], + enums: [], + ); + { + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); + generator.generate( + generatorOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final code = sink.toString(); + expect(code, contains('bool operator==(const Foo& other) const;')); + } + { + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); + generator.generate( + generatorOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final code = sink.toString(); + expect(code, contains('bool Foo::operator==(const Foo& other) const {')); + } + }); + + test('data class equality with pointers', () { + final nested = Class( + name: 'Nested', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'int', isNullable: false), + name: 'data', + ), + ], + ); + final root = Root( + apis: [], + classes: [ + Class( + name: 'Foo', + fields: [ + NamedType( + type: TypeDeclaration( + baseName: 'Nested', + isNullable: true, + associatedClass: nested, + ), + name: 'nested', + ), + ], + ), + nested, + ], + enums: [], + ); + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalCppOptions( + cppHeaderOut: '', + cppSourceOut: '', + headerIncludePath: '', + ), + ); + generator.generate( + generatorOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final code = sink.toString(); + expect(code, contains('bool Foo::operator==(const Foo& other) const {')); + }); + + test('data classes implement Hash', () { + final root = Root( + apis: [], + classes: [ + Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'int', isNullable: false), + name: 'field1', + ), + ], + ), + ], + enums: [], + ); + { + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalCppOptions( + headerIncludePath: 'foo.h', + cppHeaderOut: '', + cppSourceOut: '', + ), + ); + generator.generate( + generatorOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final code = sink.toString(); + expect(code, contains('size_t Hash() const;')); + } + { + final sink = StringBuffer(); + const generator = CppGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalCppOptions( + headerIncludePath: 'foo.h', + cppHeaderOut: '', + cppSourceOut: '', + ), + ); + generator.generate( + generatorOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final code = sink.toString(); + expect(code, contains('size_t Input::Hash() const {')); + } + }); } diff --git a/packages/pigeon/test/dart/proxy_api_test.dart b/packages/pigeon/test/dart/proxy_api_test.dart index cfa6bafb6f81..96ca1ce6b093 100644 --- a/packages/pigeon/test/dart/proxy_api_test.dart +++ b/packages/pigeon/test/dart/proxy_api_test.dart @@ -11,7 +11,7 @@ const String DEFAULT_PACKAGE_NAME = 'test_package'; void main() { group('ProxyApi', () { test('one api', () { - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -77,15 +77,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); // Instance Manager @@ -137,7 +137,7 @@ void main() { }); test('InstanceManagerApi', () { - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -149,15 +149,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect(code, contains(r'class _PigeonInternalInstanceManagerApi')); @@ -175,7 +175,7 @@ void main() { expect( collapsedCode, contains( - '(instanceManager ?? PigeonInstanceManager.instance) .remove(arg_identifier!);', + '(instanceManager ?? PigeonInstanceManager.instance) .remove(arg_identifier);', ), ); @@ -190,7 +190,7 @@ void main() { group('ProxyApi base class', () { test('class name', () { - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -202,15 +202,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, @@ -219,7 +219,7 @@ void main() { }); test('InstanceManager field', () { - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -231,15 +231,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect( @@ -254,13 +254,13 @@ void main() { group('inheritance', () { test('extends', () { - final AstProxyApi api2 = AstProxyApi( + final api2 = AstProxyApi( name: 'Api2', constructors: [], fields: [], methods: [], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -278,15 +278,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect(code, contains(r'class Api extends Api2')); expect( @@ -298,13 +298,13 @@ void main() { }); test('implements', () { - final AstProxyApi api2 = AstProxyApi( + final api2 = AstProxyApi( name: 'Api2', constructors: [], fields: [], methods: [], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -324,15 +324,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -342,19 +342,19 @@ void main() { }); test('implements 2 ProxyApis', () { - final AstProxyApi api2 = AstProxyApi( + final api2 = AstProxyApi( name: 'Api2', constructors: [], fields: [], methods: [], ); - final AstProxyApi api3 = AstProxyApi( + final api3 = AstProxyApi( name: 'Api3', constructors: [], fields: [], methods: [], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -380,15 +380,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -398,7 +398,7 @@ void main() { }); test('implements inherits flutter methods', () { - final AstProxyApi api2 = AstProxyApi( + final api2 = AstProxyApi( name: 'Api2', constructors: [], fields: [], @@ -418,7 +418,7 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -438,15 +438,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect( code, @@ -468,7 +468,7 @@ void main() { group('Constructors', () { test('empty name and no params constructor', () { - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -482,15 +482,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect(code, contains('class Api')); expect( @@ -510,7 +510,7 @@ void main() { expect( collapsedCode, contains( - r"const String pigeonVar_channelName = 'dev.flutter.pigeon.test_package.Api.pigeon_defaultConstructor';", + r"const pigeonVar_channelName = 'dev.flutter.pigeon.test_package.Api.pigeon_defaultConstructor';", ), ); expect( @@ -522,17 +522,17 @@ void main() { expect( collapsedCode, contains( - '() async { final List? pigeonVar_replyList = await pigeonVar_sendFuture as List?;', + '() async { final pigeonVar_replyList = await pigeonVar_sendFuture as List?;', ), ); }); test('multiple params constructor', () { - final Enum anEnum = Enum( + final anEnum = Enum( name: 'AnEnum', members: [EnumMember(name: 'one')], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -600,15 +600,15 @@ void main() { classes: [], enums: [anEnum], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect(code, contains('class Api')); expect( @@ -651,11 +651,11 @@ void main() { group('Fields', () { test('constructor with fields', () { - final Enum anEnum = Enum( + final anEnum = Enum( name: 'AnEnum', members: [EnumMember(name: 'one')], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -720,15 +720,15 @@ void main() { classes: [], enums: [anEnum], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect(code, contains('class Api')); expect( @@ -775,13 +775,13 @@ void main() { }); test('attached field', () { - final AstProxyApi api2 = AstProxyApi( + final api2 = AstProxyApi( name: 'Api2', constructors: [], fields: [], methods: [], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -804,28 +804,28 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('class Api')); expect(code, contains(r'late final Api2 aField = pigeonVar_aField();')); expect(code, contains(r'Api2 pigeonVar_aField()')); }); test('static attached field', () { - final AstProxyApi api2 = AstProxyApi( + final api2 = AstProxyApi( name: 'Api2', constructors: [], fields: [], methods: [], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -849,15 +849,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('class Api')); expect( code, @@ -875,11 +875,11 @@ void main() { group('Host methods', () { test('multiple params method', () { - final Enum anEnum = Enum( + final anEnum = Enum( name: 'AnEnum', members: [EnumMember(name: 'one')], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -949,15 +949,15 @@ void main() { classes: [], enums: [anEnum], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect(code, contains('class Api')); expect( @@ -980,7 +980,7 @@ void main() { }); test('static method', () { - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -1000,15 +1000,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect(code, contains('class Api')); expect( @@ -1025,11 +1025,11 @@ void main() { group('Flutter methods', () { test('multiple params flutter method', () { - final Enum anEnum = Enum( + final anEnum = Enum( name: 'AnEnum', members: [EnumMember(name: 'one')], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -1094,15 +1094,15 @@ void main() { classes: [], enums: [anEnum], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect(code, contains('class Api')); expect( @@ -1125,35 +1125,30 @@ void main() { ); expect( code, - contains(r'final Api? arg_pigeon_instance = (args[0] as Api?);'), + contains(r'final Api arg_pigeon_instance = args[0]! as Api;'), ); + expect(code, contains(r'final int arg_validType = args[1]! as int;')); expect( code, - contains(r'final int? arg_validType = (args[1] as int?);'), + contains(r'final AnEnum arg_enumType = args[2]! as AnEnum;'), ); expect( code, - contains(r'final AnEnum? arg_enumType = (args[2] as AnEnum?);'), + contains(r'final Api2 arg_proxyApiType = args[3]! as Api2;'), ); expect( code, - contains(r'final Api2? arg_proxyApiType = (args[3] as Api2?);'), + contains(r'final int? arg_nullableValidType = args[4] as int?;'), ); expect( code, - contains(r'final int? arg_nullableValidType = (args[4] as int?);'), - ); - expect( - code, - contains( - r'final AnEnum? arg_nullableEnumType = (args[5] as AnEnum?);', - ), + contains(r'final AnEnum? arg_nullableEnumType = args[5] as AnEnum?;'), ); expect( collapsedCode, contains( - r'(doSomething ?? arg_pigeon_instance!.doSomething)?.call( arg_pigeon_instance!, ' - r'arg_validType!, arg_enumType!, arg_proxyApiType!, ' + r'(doSomething ?? arg_pigeon_instance.doSomething)?.call( arg_pigeon_instance, ' + r'arg_validType, arg_enumType, arg_proxyApiType, ' r'arg_nullableValidType, arg_nullableEnumType, ' r'arg_nullableProxyApiType);', ), @@ -1180,7 +1175,7 @@ void main() { /// void method( int param1, int param2, ) /// ``` String _collapseNewlineAndIndentation(String string) { - final StringBuffer result = StringBuffer(); + final result = StringBuffer(); for (final String line in string.split('\n')) { result.write('${line.trimLeft()} '); } diff --git a/packages/pigeon/test/dart_generator_test.dart b/packages/pigeon/test/dart_generator_test.dart index f159cdaf48d8..f3774fc75c92 100644 --- a/packages/pigeon/test/dart_generator_test.dart +++ b/packages/pigeon/test/dart_generator_test.dart @@ -29,7 +29,7 @@ final Enum emptyEnum = Enum( void main() { test('gen one class', () { - final Class classDefinition = Class( + final classDefinition = Class( name: 'Foobar', fields: [ NamedType( @@ -42,53 +42,49 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [], classes: [classDefinition], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('class Foobar')); expect(code, contains(' dataType1? field1;')); }); test('gen one enum', () { - final Enum anEnum = Enum( + final anEnum = Enum( name: 'Foobar', members: [ EnumMember(name: 'one'), EnumMember(name: 'two'), ], ); - final Root root = Root( - apis: [], - classes: [], - enums: [anEnum], - ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final root = Root(apis: [], classes: [], enums: [anEnum]); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('enum Foobar')); expect(code, contains(' one,')); expect(code, contains(' two,')); }); test('gen one host api', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -137,21 +133,21 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('class Api')); expect(code, contains('Future doSomething(Input input)')); }); test('host multiple args', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -186,15 +182,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('class Api')); expect(code, contains('Future add(int x, int y)')); expect( @@ -207,7 +203,7 @@ void main() { }); test('flutter multiple args', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -242,28 +238,28 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('class Api')); expect(code, contains('int add(int x, int y)')); expect( code, - contains('final List args = (message as List?)!'), + contains('final List args = message! as List'), ); - expect(code, contains('final int? arg_x = (args[0] as int?)')); - expect(code, contains('final int? arg_y = (args[1] as int?)')); - expect(code, contains('final int output = api.add(arg_x!, arg_y!)')); + expect(code, contains('final int arg_x = args[0]! as int')); + expect(code, contains('final int arg_y = args[1]! as int')); + expect(code, contains('final int output = api.add(arg_x, arg_y)')); }); test('nested class', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -291,21 +287,21 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('nested,')); expect(code, contains('nested: result[0] as Input?')); }); test('nested non-nullable class', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -336,21 +332,21 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('nested,')); expect(code, contains('nested: result[0]! as Input')); }); test('flutterApi', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -399,22 +395,22 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('abstract class Api')); expect(code, contains('static void setUp(Api')); expect(code, contains('Output doSomething(Input input)')); }); test('host void', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -450,21 +446,20 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('Future doSomething')); - expect(code, contains('return;')); }); test('flutter void return', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -500,15 +495,15 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); // The next line verifies that we're not setting a variable to the value of "doSomething", but // ignores the line where we assert the value of the argument isn't null, since on that line // we mention "doSomething" in the assertion message. @@ -517,7 +512,7 @@ void main() { }); test('flutter void argument', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -548,21 +543,21 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, matches('output.*=.*doSomething[(][)]')); expect(code, contains('Output doSomething();')); }); test('flutter enum argument with enum class', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -614,26 +609,26 @@ void main() { ), ], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('return value == null ? null : Enum.values[value];')); expect(code, contains('writeValue(buffer, value.index);')); expect( code, - contains('final EnumClass? arg_enumClass = (args[0] as EnumClass?);'), + contains('final EnumClass arg_enumClass = args[0]! as EnumClass;'), ); expect(code, contains('EnumClass doSomething(EnumClass enumClass);')); }); test('primitive enum host', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Bar', @@ -667,15 +662,15 @@ void main() { ), ], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('enum Foo {')); expect(code, contains('Future bar(Foo? foo) async')); expect( @@ -686,7 +681,7 @@ void main() { }); test('flutter non-nullable enum argument with enum class', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -738,22 +733,22 @@ void main() { ), ], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('writeValue(buffer, value.index)')); expect(code, contains('return value == null ? null : Enum.values[value];')); expect(code, contains('enum1: result[0]! as Enum,')); }); test('host void argument', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -784,15 +779,15 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, matches('pigeonVar_sendFuture = pigeonVar_channel.send[(]null[)]'), @@ -800,7 +795,7 @@ void main() { }); test('mock Dart handler', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -865,16 +860,16 @@ void main() { ], enums: [], ); - final StringBuffer mainCodeSink = StringBuffer(); - final StringBuffer testCodeSink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final mainCodeSink = StringBuffer(); + final testCodeSink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, mainCodeSink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String mainCode = mainCodeSink.toString(); + final mainCode = mainCodeSink.toString(); expect(mainCode, isNot(contains(r"import 'fo\'o.dart';"))); expect(mainCode, contains('class Api {')); expect(mainCode, isNot(contains('abstract class ApiMock'))); @@ -882,15 +877,19 @@ void main() { expect(mainCode, isNot(contains("'${Keys.result}': output"))); expect(mainCode, isNot(contains('return [];'))); - const DartGenerator testGenerator = DartGenerator(); + const testGenerator = DartGenerator(); testGenerator.generateTest( - const InternalDartOptions(dartOut: "fo'o.dart", testOut: 'test.dart'), + const InternalDartOptions( + dartOut: "fo'o.dart", + testOut: 'test.dart', + ignoreLints: false, + ), root, testCodeSink, dartPackageName: DEFAULT_PACKAGE_NAME, dartOutputPackageName: DEFAULT_PACKAGE_NAME, ); - final String testCode = testCodeSink.toString(); + final testCode = testCodeSink.toString(); expect(testCode, contains(r"import 'fo\'o.dart';")); expect(testCode, isNot(contains('class Api {'))); expect(testCode, contains('abstract class ApiMock')); @@ -900,7 +899,7 @@ void main() { }); test('gen one async Flutter Api', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -950,25 +949,25 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('abstract class Api')); expect(code, contains('Future doSomething(Input input);')); expect( code, - contains('final Output output = await api.doSomething(arg_input!);'), + contains('final Output output = await api.doSomething(arg_input);'), ); }); test('gen one async Flutter Api with void return', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1014,22 +1013,22 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, isNot(matches('=.s*doSomething'))); expect(code, contains('await api.doSomething(')); expect(code, isNot(contains('._toMap()'))); }); test('gen one async Host Api', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1079,21 +1078,21 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('class Api')); expect(code, matches('Output.*doSomething.*Input')); }); test('async host void argument', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1125,15 +1124,15 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, matches('pigeonVar_channel.send[(]null[)]')); }); @@ -1142,22 +1141,25 @@ void main() { } test('header', () { - final Root root = Root(apis: [], classes: [], enums: []); - final StringBuffer sink = StringBuffer(); + final root = Root(apis: [], classes: [], enums: []); + final sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + const generator = DartGenerator(); generator.generate( - InternalDartOptions(copyrightHeader: makeIterable('hello world')), + InternalDartOptions( + copyrightHeader: makeIterable('hello world'), + ignoreLints: false, + ), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, startsWith('// hello world')); }); test('generics', () { - final Class classDefinition = Class( + final classDefinition = Class( name: 'Foobar', fields: [ NamedType( @@ -1172,26 +1174,26 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [], classes: [classDefinition], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('class Foobar')); expect(code, contains(' List? field1;')); }); test('map generics', () { - final Class classDefinition = Class( + final classDefinition = Class( name: 'Foobar', fields: [ NamedType( @@ -1207,26 +1209,26 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [], classes: [classDefinition], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('class Foobar')); expect(code, contains(' Map? field1;')); }); test('host generics argument', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1254,20 +1256,20 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('doit(List arg')); }); test('flutter generics argument with void return', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1295,20 +1297,20 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('doit(List arg')); }); test('host generics return', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1331,26 +1333,24 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('Future> doit(')); expect( code, - contains( - 'return (pigeonVar_replyList[0] as List?)!.cast();', - ), + contains('return (pigeonVar_replyValue! as List).cast();'), ); }); test('flutter generics argument non void return', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1384,27 +1384,27 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('List doit(')); expect( code, contains( - 'final List? arg_foo = (args[0] as List?)?.cast()', + 'final List arg_foo = (args[0]! as List).cast()', ), ); - expect(code, contains('final List output = api.doit(arg_foo!)')); + expect(code, contains('final List output = api.doit(arg_foo)')); }); test('return nullable host', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1424,21 +1424,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('Future doit()')); - expect(code, contains('return (pigeonVar_replyList[0] as int?);')); + expect(code, contains('return pigeonVar_replyValue as int?;')); }); test('return nullable collection host', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1461,26 +1461,26 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('Future?> doit()')); expect( code, contains( - 'return (pigeonVar_replyList[0] as List?)?.cast();', + 'return (pigeonVar_replyValue as List?)?.cast();', ), ); }); test('return nullable async host', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1501,21 +1501,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('Future doit()')); - expect(code, contains('return (pigeonVar_replyList[0] as int?);')); + expect(code, contains('return pigeonVar_replyValue as int?;')); }); test('return nullable flutter', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1535,21 +1535,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('int? doit();')); expect(code, contains('final int? output = api.doit();')); }); test('return nullable async flutter', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1570,21 +1570,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('Future doit();')); expect(code, contains('final int? output = await api.doit();')); }); test('platform error for return nil on nonnull', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1603,16 +1603,17 @@ void main() { ], classes: [], enums: [], + containsHostApi: true, ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains('Host platform returned null value for non-null return value.'), @@ -1620,7 +1621,7 @@ void main() { }); test('nullable argument host', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1645,20 +1646,20 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('Future doit(int? foo) async {')); }); test('nullable argument flutter', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1683,20 +1684,20 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('void doit(int? foo);')); }); test('named argument flutter', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1723,49 +1724,46 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('void doit({required int foo});')); - expect(code, contains('api.doit(foo: arg_foo!)')); + expect(code, contains('api.doit(foo: arg_foo)')); }); test('uses output package name for imports', () { - const String overriddenPackageName = 'custom_name'; - const String outputPackageName = 'some_output_package'; + const overriddenPackageName = 'custom_name'; + const outputPackageName = 'some_output_package'; assert(outputPackageName != DEFAULT_PACKAGE_NAME); final Directory tempDir = Directory.systemTemp.createTempSync('pigeon'); try { - final Directory foo = Directory(path.join(tempDir.path, 'lib', 'foo')); + final foo = Directory(path.join(tempDir.path, 'lib', 'foo')); foo.createSync(recursive: true); - final File pubspecFile = File(path.join(tempDir.path, 'pubspec.yaml')); + final pubspecFile = File(path.join(tempDir.path, 'pubspec.yaml')); pubspecFile.writeAsStringSync(''' name: foobar '''); - final Root root = Root( - classes: [], - apis: [], - enums: [], - ); - final StringBuffer sink = StringBuffer(); - const DartGenerator testGenerator = DartGenerator(); + final root = Root(classes: [], apis: [], enums: []); + final sink = StringBuffer(); + const testGenerator = DartGenerator(); testGenerator.generateTest( InternalDartOptions( dartOut: path.join(foo.path, 'bar.dart'), testOut: path.join(tempDir.path, 'test', 'bar_test.dart'), + ignoreLints: false, ), root, sink, dartPackageName: overriddenPackageName, dartOutputPackageName: outputPackageName, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains("import 'package:$outputPackageName/foo/bar.dart';"), @@ -1776,7 +1774,7 @@ name: foobar }); test('transfers documentation comments', () { - final List comments = [ + final comments = [ ' api comment', ' api method comment', ' class comment', @@ -1784,12 +1782,12 @@ name: foobar ' enum comment', ' enum member comment', ]; - int count = 0; + var count = 0; - final List unspacedComments = ['////////']; - int unspacedCount = 0; + final unspacedComments = ['////////']; + var unspacedCount = 0; - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1850,23 +1848,23 @@ name: foobar ), ], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); - for (final String comment in comments) { + final code = sink.toString(); + for (final comment in comments) { expect(code, contains('///$comment')); } expect(code, contains('/// ///')); }); test('creates custom codecs', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1916,20 +1914,20 @@ name: foobar ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('extends StandardMessageCodec')); }); test('host test code handles enums', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1964,19 +1962,23 @@ name: foobar ), ], ); - final StringBuffer sink = StringBuffer(); + final sink = StringBuffer(); - const DartGenerator testGenerator = DartGenerator(); + const testGenerator = DartGenerator(); testGenerator.generateTest( - const InternalDartOptions(dartOut: 'code.dart', testOut: 'test.dart'), + const InternalDartOptions( + dartOut: 'code.dart', + testOut: 'test.dart', + ignoreLints: false, + ), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, dartOutputPackageName: DEFAULT_PACKAGE_NAME, ); - final String testCode = sink.toString(); - expect(testCode, contains('final Enum? arg_anEnum = (args[0] as Enum?);')); + final testCode = sink.toString(); + expect(testCode, contains('final Enum arg_anEnum = args[0]! as Enum;')); expect( testCode, contains('return value == null ? null : Enum.values[value];'), @@ -1985,7 +1987,7 @@ name: foobar }); test('connection error contains channel name', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -2006,19 +2008,15 @@ name: foobar enums: [], containsHostApi: true, ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); - expect( - code, - contains('throw _createConnectionError(pigeonVar_channelName);'), - ); + final code = sink.toString(); expect( code, contains( @@ -2028,7 +2026,7 @@ name: foobar }); test('generate wrapResponse if is generating tests', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -2047,20 +2045,20 @@ name: foobar enums: [], ); - final StringBuffer mainCodeSink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final mainCodeSink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(testOut: 'test.dart'), + const InternalDartOptions(testOut: 'test.dart', ignoreLints: false), root, mainCodeSink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String mainCode = mainCodeSink.toString(); + final mainCode = mainCodeSink.toString(); expect(mainCode, contains('List wrapResponse(')); }); test('writes custom int codec without custom types', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -2080,17 +2078,77 @@ name: foobar classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const DartGenerator generator = DartGenerator(); + final sink = StringBuffer(); + const generator = DartGenerator(); generator.generate( - const InternalDartOptions(), + const InternalDartOptions(ignoreLints: false), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('if (value is int) {')); expect(code, contains('buffer.putUint8(4);')); expect(code, contains('buffer.putInt64(value);')); }); + + test('data class equality', () { + final classDefinition = Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'int', isNullable: true), + name: 'field1', + ), + ], + ); + final root = Root( + apis: [], + classes: [classDefinition], + enums: [], + ); + final sink = StringBuffer(); + const generator = DartGenerator(); + generator.generate( + const InternalDartOptions(ignoreLints: false), + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final code = sink.toString(); + expect(code, contains('bool operator ==(Object other) {')); + expect(code, contains('int get hashCode =>')); + }); + + test('data class equality multi-field', () { + final classDefinition = Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'int', isNullable: true), + name: 'field1', + ), + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'field2', + ), + ], + ); + final root = Root( + apis: [], + classes: [classDefinition], + enums: [], + ); + final sink = StringBuffer(); + const generator = DartGenerator(); + generator.generate( + const InternalDartOptions(ignoreLints: false), + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final code = sink.toString(); + expect(code, contains('bool operator ==(Object other) {')); + expect(code, contains('int get hashCode =>')); + }); } diff --git a/packages/pigeon/test/functional_test.dart b/packages/pigeon/test/functional_test.dart index 4e83c21031ec..48110f1487fe 100644 --- a/packages/pigeon/test/functional_test.dart +++ b/packages/pigeon/test/functional_test.dart @@ -7,7 +7,7 @@ import 'package:test/test.dart'; void main() { test('indexMap', () { - final List items = ['a', 'b', 'c']; + final items = ['a', 'b', 'c']; final List result = indexMap( items, (int index, String value) => value + index.toString(), @@ -18,8 +18,8 @@ void main() { }); test('enumerate', () { - final List items = ['a', 'b', 'c']; - int saw = 0; + final items = ['a', 'b', 'c']; + var saw = 0; enumerate(items, (int index, String value) { if (index == 0) { expect(value, 'a'); diff --git a/packages/pigeon/test/generator_tools_test.dart b/packages/pigeon/test/generator_tools_test.dart index 6483c12ef97d..183865f1e3f3 100644 --- a/packages/pigeon/test/generator_tools_test.dart +++ b/packages/pigeon/test/generator_tools_test.dart @@ -10,7 +10,7 @@ bool _equalSet(Set x, Set y) { if (x.length != y.length) { return false; } - for (final T object in x) { + for (final object in x) { if (!y.contains(object)) { return false; } @@ -49,18 +49,18 @@ final Class emptyClass = Class( void main() { test('test merge maps', () { - final Map source = { + final source = { '1': '1', '2': {'1': '1', '3': '3'}, '3': '3', // not modified }; - final Map modification = { + final modification = { '1': '2', // modify '2': { '2': '2', // added }, }; - final Map expected = { + final expected = { '1': '2', '2': {'1': '1', '2': '2', '3': '3'}, '3': '3', @@ -69,7 +69,7 @@ void main() { }); test('get codec types from all classes and enums', () { - final Root root = Root( + final root = Root( classes: [ Class( name: 'name', @@ -94,7 +94,7 @@ void main() { }); test('getEnumeratedTypes:ed type arguments', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -162,7 +162,7 @@ void main() { }); test('getEnumeratedTypes: Object', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api1', @@ -209,7 +209,7 @@ void main() { }); test('getEnumeratedTypes:ue entries', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api1', @@ -282,13 +282,13 @@ void main() { }); test('recursiveGetSuperClassApisChain', () { - final AstProxyApi superClassOfSuperClassApi = AstProxyApi( + final superClassOfSuperClassApi = AstProxyApi( name: 'Api3', methods: [], constructors: [], fields: [], ); - final AstProxyApi superClassApi = AstProxyApi( + final superClassApi = AstProxyApi( name: 'Api2', methods: [], constructors: [], @@ -299,7 +299,7 @@ void main() { associatedProxyApi: superClassOfSuperClassApi, ), ); - final AstProxyApi api = AstProxyApi( + final api = AstProxyApi( name: 'Api', methods: [], constructors: [], @@ -321,19 +321,19 @@ void main() { }); test('recursiveFindAllInterfacesApis', () { - final AstProxyApi interfaceOfInterfaceApi2 = AstProxyApi( + final interfaceOfInterfaceApi2 = AstProxyApi( name: 'Api5', methods: [], constructors: [], fields: [], ); - final AstProxyApi interfaceOfInterfaceApi = AstProxyApi( + final interfaceOfInterfaceApi = AstProxyApi( name: 'Api4', methods: [], constructors: [], fields: [], ); - final AstProxyApi interfaceApi2 = AstProxyApi( + final interfaceApi2 = AstProxyApi( name: 'Api3', methods: [], constructors: [], @@ -346,7 +346,7 @@ void main() { ), }, ); - final AstProxyApi interfaceApi = AstProxyApi( + final interfaceApi = AstProxyApi( name: 'Api2', methods: [], constructors: [], @@ -364,7 +364,7 @@ void main() { ), }, ); - final AstProxyApi api = AstProxyApi( + final api = AstProxyApi( name: 'Api', methods: [], constructors: [], @@ -397,19 +397,19 @@ void main() { test( 'recursiveFindAllInterfacesApis throws error if api recursively implements itself', () { - final AstProxyApi a = AstProxyApi( + final a = AstProxyApi( name: 'A', methods: [], constructors: [], fields: [], ); - final AstProxyApi b = AstProxyApi( + final b = AstProxyApi( name: 'B', methods: [], constructors: [], fields: [], ); - final AstProxyApi c = AstProxyApi( + final c = AstProxyApi( name: 'C', methods: [], constructors: [], @@ -443,7 +443,7 @@ void main() { ); test('findHighestApiRequirement', () { - final TypeDeclaration typeWithoutMinApi = TypeDeclaration( + final typeWithoutMinApi = TypeDeclaration( baseName: 'TypeWithoutMinApi', isNullable: false, associatedProxyApi: AstProxyApi( @@ -454,7 +454,7 @@ void main() { ), ); - final TypeDeclaration typeWithMinApi = TypeDeclaration( + final typeWithMinApi = TypeDeclaration( baseName: 'TypeWithMinApi', isNullable: false, associatedProxyApi: AstProxyApi( @@ -465,7 +465,7 @@ void main() { ), ); - final TypeDeclaration typeWithHighestMinApi = TypeDeclaration( + final typeWithHighestMinApi = TypeDeclaration( baseName: 'TypeWithHighestMinApi', isNullable: false, associatedProxyApi: AstProxyApi( @@ -500,8 +500,7 @@ void main() { }); test('Indent.format trims indentation', () { - final StringBuffer buffer = StringBuffer(); - final Indent indent = Indent(buffer); + final indent = Indent(); indent.format(''' void myMethod() { @@ -509,7 +508,7 @@ void main() { print('hello'); }'''); - expect(buffer.toString(), ''' + expect(indent.toString(), ''' void myMethod() { print('hello'); diff --git a/packages/pigeon/test/gobject_generator_test.dart b/packages/pigeon/test/gobject_generator_test.dart index 2c66b13afe00..8f44885a4617 100644 --- a/packages/pigeon/test/gobject_generator_test.dart +++ b/packages/pigeon/test/gobject_generator_test.dart @@ -11,7 +11,7 @@ const String DEFAULT_PACKAGE_NAME = 'test_package'; void main() { test('gen one api', () { - final Class inputClass = Class( + final inputClass = Class( name: 'Input', fields: [ NamedType( @@ -20,7 +20,7 @@ void main() { ), ], ); - final Class outputClass = Class( + final outputClass = Class( name: 'Output', fields: [ NamedType( @@ -29,7 +29,7 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -60,24 +60,23 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const GObjectGenerator generator = GObjectGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = GObjectGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -92,24 +91,23 @@ void main() { ); } { - final StringBuffer sink = StringBuffer(); - const GObjectGenerator generator = GObjectGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = GObjectGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -134,7 +132,7 @@ void main() { }); test('naming follows style', () { - final Class inputClass = Class( + final inputClass = Class( name: 'Input', fields: [ NamedType( @@ -143,7 +141,7 @@ void main() { ), ], ); - final Class outputClass = Class( + final outputClass = Class( name: 'Output', fields: [ NamedType( @@ -152,7 +150,7 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -183,24 +181,23 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const GObjectGenerator generator = GObjectGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = GObjectGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -221,24 +218,23 @@ void main() { ); } { - final StringBuffer sink = StringBuffer(); - const GObjectGenerator generator = GObjectGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = GObjectGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -255,7 +251,7 @@ void main() { }); test('Spaces before {', () { - final Class inputClass = Class( + final inputClass = Class( name: 'Input', fields: [ NamedType( @@ -264,7 +260,7 @@ void main() { ), ], ); - final Class outputClass = Class( + final outputClass = Class( name: 'Output', fields: [ NamedType( @@ -273,7 +269,7 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -304,53 +300,51 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const GObjectGenerator generator = GObjectGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = GObjectGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, isNot(contains('){'))); expect(code, isNot(contains('const{'))); } { - final StringBuffer sink = StringBuffer(); - const GObjectGenerator generator = GObjectGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = GObjectGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, isNot(contains('){'))); expect(code, isNot(contains('const{'))); } }); test('include blocks follow style', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -379,24 +373,23 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const GObjectGenerator generator = GObjectGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = GObjectGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains(''' @@ -405,24 +398,23 @@ void main() { ); } { - final StringBuffer sink = StringBuffer(); - const GObjectGenerator generator = GObjectGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalGObjectOptions( - headerIncludePath: 'a_header.h', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = GObjectGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalGObjectOptions( + headerIncludePath: 'a_header.h', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains(''' @@ -433,7 +425,7 @@ void main() { }); test('data classes handle non-nullable fields', () { - final Class nestedClass = Class( + final nestedClass = Class( name: 'Nested', fields: [ NamedType( @@ -442,7 +434,7 @@ void main() { ), ], ); - final Class inputClass = Class( + final inputClass = Class( name: 'Input', fields: [ NamedType( @@ -467,7 +459,7 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -494,24 +486,23 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const GObjectGenerator generator = GObjectGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = GObjectGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, @@ -521,24 +512,23 @@ void main() { ); } { - final StringBuffer sink = StringBuffer(); - const GObjectGenerator generator = GObjectGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = GObjectGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, @@ -550,7 +540,7 @@ void main() { }); test('host non-nullable return types map correctly', () { - final Class returnDataClass = Class( + final returnDataClass = Class( name: 'ReturnData', fields: [ NamedType( @@ -559,7 +549,7 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -633,24 +623,23 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const GObjectGenerator generator = GObjectGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = GObjectGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -691,7 +680,7 @@ void main() { }); test('host non-nullable arguments map correctly', () { - final Class parameterObjectClass = Class( + final parameterObjectClass = Class( name: 'ParameterObject', fields: [ NamedType( @@ -700,8 +689,8 @@ void main() { ), ], ); - final Class objectClass = Class(name: 'Object', fields: []); - final Root root = Root( + final objectClass = Class(name: 'Object', fields: []); + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -789,24 +778,23 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const GObjectGenerator generator = GObjectGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = GObjectGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -815,24 +803,23 @@ void main() { ); } { - final StringBuffer sink = StringBuffer(); - const GObjectGenerator generator = GObjectGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = GObjectGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -843,7 +830,7 @@ void main() { }); test('transfers documentation comments', () { - final List comments = [ + final comments = [ ' api comment', ' api method comment', ' class comment', @@ -851,12 +838,12 @@ void main() { ' enum comment', ' enum member comment', ]; - int count = 0; + var count = 0; - final List unspacedComments = ['////////']; - int unspacedCount = 0; + final unspacedComments = ['////////']; + var unspacedCount = 0; - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -917,32 +904,31 @@ void main() { ), ], ); - final StringBuffer sink = StringBuffer(); - const GObjectGenerator generator = GObjectGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalGObjectOptions( - headerIncludePath: 'foo', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = GObjectGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalGObjectOptions( + headerIncludePath: 'foo', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); - for (final String comment in comments) { + final code = sink.toString(); + for (final comment in comments) { expect(code, contains(' *$comment')); } expect(code, contains(' * ///')); }); test('generates custom class id constants', () { - final Class parameterObjectClass = Class( + final parameterObjectClass = Class( name: 'ParameterObject', fields: [ NamedType( @@ -951,15 +937,15 @@ void main() { ), ], ); - final Class objectClass = Class(name: 'Object', fields: []); - final Enum anEnum = Enum( + final objectClass = Class(name: 'Object', fields: []); + final anEnum = Enum( name: 'enum', members: [ EnumMember(name: 'one'), EnumMember(name: 'two'), ], ); - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -998,24 +984,23 @@ void main() { enums: [anEnum], ); { - final StringBuffer sink = StringBuffer(); - const GObjectGenerator generator = GObjectGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = GObjectGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('extern const int test_packageenum_type_id;')); expect( code, @@ -1024,24 +1009,23 @@ void main() { expect(code, contains('extern const int test_package_object_type_id;')); } { - final StringBuffer sink = StringBuffer(); - const GObjectGenerator generator = GObjectGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalGObjectOptions( - headerIncludePath: '', - gobjectHeaderOut: '', - gobjectSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = GObjectGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('const int test_packageenum_type_id = 129;')); expect( @@ -1051,4 +1035,50 @@ void main() { expect(code, contains('const int test_package_object_type_id = 131;')); } }); + + test('data classes handle equality and hashing', () { + final inputClass = Class( + name: 'Input', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'input', + ), + NamedType( + type: const TypeDeclaration(baseName: 'double', isNullable: false), + name: 'someDouble', + ), + NamedType( + type: const TypeDeclaration(baseName: 'Uint8List', isNullable: false), + name: 'someBytes', + ), + ], + ); + final root = Root( + apis: [], + classes: [inputClass], + enums: [], + ); + { + final sink = StringBuffer(); + const generator = GObjectGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalGObjectOptions( + headerIncludePath: '', + gobjectHeaderOut: '', + gobjectSourceOut: '', + ), + ); + generator.generate( + generatorOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final code = sink.toString(); + expect(code, contains('gboolean test_package_input_equals(')); + expect(code, contains('guint test_package_input_hash(')); + } + }); } diff --git a/packages/pigeon/test/java_generator_test.dart b/packages/pigeon/test/java_generator_test.dart index deb2e6bbe809..a5f0708abf58 100644 --- a/packages/pigeon/test/java_generator_test.dart +++ b/packages/pigeon/test/java_generator_test.dart @@ -4,6 +4,7 @@ import 'package:pigeon/pigeon.dart'; import 'package:pigeon/src/ast.dart'; +import 'package:pigeon/src/generator_tools.dart'; import 'package:pigeon/src/java/java_generator.dart'; import 'package:test/test.dart'; @@ -26,7 +27,7 @@ final Enum emptyEnum = Enum( void main() { test('gen one class', () { - final Class classDefinition = Class( + final classDefinition = Class( name: 'Foobar', fields: [ NamedType( @@ -35,24 +36,21 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [], classes: [classDefinition], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('public class Messages')); expect(code, contains('public static final class Foobar')); expect(code, contains('public static final class Builder')); @@ -61,7 +59,7 @@ void main() { }); test('gen one enum', () { - final Enum anEnum = Enum( + final anEnum = Enum( name: 'Foobar', members: [ EnumMember(name: 'one'), @@ -69,24 +67,17 @@ void main() { EnumMember(name: 'remoteDB'), ], ); - final Root root = Root( - apis: [], - classes: [], - enums: [anEnum], - ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final root = Root(apis: [], classes: [], enums: [anEnum]); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('public enum Foobar')); expect(code, contains(' ONE(0),')); expect(code, contains(' TWO_THREE_FOUR(1),')); @@ -97,7 +88,7 @@ void main() { }); test('package', () { - final Class classDefinition = Class( + final classDefinition = Class( name: 'Foobar', fields: [ NamedType( @@ -106,30 +97,30 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [], classes: [classDefinition], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions( className: 'Messages', package: 'com.google.foobar', javaOut: '', ); - const JavaGenerator generator = JavaGenerator(); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('package com.google.foobar;')); }); test('gen one host api', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -179,19 +170,16 @@ void main() { enums: [], containsHostApi: true, ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('public interface Api')); expect(code, matches('Output.*doSomething.*Input')); expect(code, contains('channel.setMessageHandler(null)')); @@ -219,7 +207,7 @@ void main() { }); test('all the simple datatypes header', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -275,19 +263,16 @@ void main() { enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('private @Nullable Boolean aBool;')); expect(code, contains('private @Nullable Long aInt;')); expect(code, contains('private @Nullable Double aDouble;')); @@ -299,7 +284,7 @@ void main() { }); test('gen one flutter api', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -348,25 +333,22 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('public static class Api')); expect(code, matches('doSomething.*Input.*Output')); }); test('gen host void api', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -402,25 +384,22 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, isNot(matches('=.*doSomething'))); expect(code, contains('doSomething(')); }); test('gen flutter void return api', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -456,19 +435,16 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -479,7 +455,7 @@ void main() { }); test('gen host void argument api', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -510,25 +486,22 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('Output doSomething()')); expect(code, contains('api.doSomething()')); }); test('gen flutter void argument api', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -559,19 +532,16 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains('public void doSomething(@NonNull Result result)'), @@ -580,7 +550,7 @@ void main() { }); test('gen list', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -595,25 +565,22 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('public static final class Foobar')); expect(code, contains('private @Nullable List field1;')); }); test('gen map', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -628,25 +595,22 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('public static final class Foobar')); expect(code, contains('private @Nullable Map field1;')); }); test('gen nested', () { - final Class classDefinition = Class( + final classDefinition = Class( name: 'Outer', fields: [ NamedType( @@ -659,7 +623,7 @@ void main() { ), ], ); - final Class nestedClass = Class( + final nestedClass = Class( name: 'Nested', fields: [ NamedType( @@ -668,24 +632,21 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [], classes: [classDefinition, nestedClass], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('public class Messages')); expect(code, contains('public static final class Outer')); expect(code, contains('public static final class Nested')); @@ -694,7 +655,7 @@ void main() { }); test('gen one async Host Api', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -744,19 +705,16 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('public interface Api')); expect(code, contains('public interface Result {')); expect(code, contains('void error(@NonNull Throwable error);')); @@ -771,7 +729,7 @@ void main() { }); test('gen one async Flutter Api', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -821,25 +779,22 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('public static class Api')); expect(code, matches('doSomething.*Input.*Output')); }); test('gen one enum class', () { - final Enum anEnum = Enum( + final anEnum = Enum( name: 'Enum1', members: [ EnumMember(name: 'one'), @@ -847,7 +802,7 @@ void main() { EnumMember(name: 'remoteDB'), ], ); - final Class classDefinition = Class( + final classDefinition = Class( name: 'EnumClass', fields: [ NamedType( @@ -860,24 +815,21 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [], classes: [classDefinition], enums: [anEnum], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('public enum Enum1')); expect(code, contains(' ONE(0),')); expect(code, contains(' TWO_THREE_FOUR(1),')); @@ -891,7 +843,7 @@ void main() { }); test('primitive enum host', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Bar', @@ -925,19 +877,16 @@ void main() { ), ], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('public enum Foo')); expect( code, @@ -959,26 +908,26 @@ void main() { } test('header', () { - final Root root = Root(apis: [], classes: [], enums: []); - final StringBuffer sink = StringBuffer(); - final InternalJavaOptions javaOptions = InternalJavaOptions( + final root = Root(apis: [], classes: [], enums: []); + final sink = StringBuffer(); + final javaOptions = InternalJavaOptions( className: 'Messages', copyrightHeader: makeIterable('hello world'), javaOut: '', ); - const JavaGenerator generator = JavaGenerator(); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, startsWith('// hello world')); }); test('generics', () { - final Class classDefinition = Class( + final classDefinition = Class( name: 'Foobar', fields: [ NamedType( @@ -993,30 +942,27 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [], classes: [classDefinition], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('class Foobar')); expect(code, contains('List field1;')); }); test('generics - maps', () { - final Class classDefinition = Class( + final classDefinition = Class( name: 'Foobar', fields: [ NamedType( @@ -1032,30 +978,27 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [], classes: [classDefinition], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('class Foobar')); expect(code, contains('Map field1;')); }); test('host generics argument', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1083,24 +1026,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('doit(@NonNull List arg')); }); test('flutter generics argument', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1128,24 +1068,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('doit(@NonNull List arg')); }); test('host generics return', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1168,25 +1105,22 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('List doit(')); expect(code, contains('List output =')); }); test('flutter generics return', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1209,19 +1143,16 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains('public void doit(@NonNull Result> result)'), @@ -1230,7 +1161,7 @@ void main() { }); test('flutter int return', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1251,25 +1182,22 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('public void doit(@NonNull Result result)')); expect(code, contains('Long output = (Long) listReply.get(0);')); }); test('host multiple args', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1304,19 +1232,16 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('class Messages')); expect(code, contains('Long add(@NonNull Long x, @NonNull Long y)')); expect( @@ -1329,7 +1254,7 @@ void main() { }); test('if host argType is Object not cast', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1354,24 +1279,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Api', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Api', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('Object xArg = args.get(0)')); }); test('flutter multiple args', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1406,19 +1328,16 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('class Messages')); expect(code, contains('BasicMessageChannel channel')); expect(code, contains('Long output')); @@ -1439,7 +1358,7 @@ void main() { }); test('flutter single args', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1467,19 +1386,16 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -1491,7 +1407,7 @@ void main() { }); test('return nullable host', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1511,24 +1427,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains(RegExp(r'@Nullable\s*Long doit\(\);'))); }); test('return nullable host async', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1549,25 +1462,22 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); // Java doesn't accept nullability annotations in type arguments. expect(code, contains('Result')); }); test('nullable argument host', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1592,24 +1502,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains(' void doit(@Nullable Long foo);')); }); test('nullable argument flutter', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1634,19 +1541,16 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -1656,7 +1560,7 @@ void main() { }); test('background platform channel', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1682,19 +1586,16 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -1711,58 +1612,59 @@ void main() { ); }); - test('generated annotation', () { - final Class classDefinition = Class(name: 'Foobar', fields: []); - final Root root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - useGeneratedAnnotation: true, - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); - final String code = sink.toString(); - expect(code, contains('@javax.annotation.Generated("dev.flutter.pigeon")')); - }); + group('generated annotation', () { + late Class classDefinition; + late Root root; + late StringBuffer sink; + late JavaGenerator generator; + const generatedAnnotation = + '@javax.annotation.Generated("$defaultPluginPackageName")'; - test('no generated annotation', () { - final Class classDefinition = Class(name: 'Foobar', fields: []); - final Root root = Root( - apis: [], - classes: [classDefinition], - enums: [], - ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); - generator.generate( - javaOptions, - root, - sink, - dartPackageName: DEFAULT_PACKAGE_NAME, - ); - final String code = sink.toString(); - expect( - code, - isNot(contains('@javax.annotation.Generated("dev.flutter.pigeon")')), - ); + setUp(() { + classDefinition = Class(name: 'Foobar', fields: []); + root = Root( + apis: [], + classes: [classDefinition], + enums: [], + ); + sink = StringBuffer(); + generator = const JavaGenerator(); + }); + + test('with generated annotation', () { + const javaOptions = InternalJavaOptions( + className: 'Messages', + useGeneratedAnnotation: true, + javaOut: '', + ); + generator.generate( + javaOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final code = sink.toString(); + expect(code, contains(generatedAnnotation)); + }); + + test('without generated annotation', () { + const javaOptions = InternalJavaOptions( + className: 'Messages', + javaOut: '', + ); + generator.generate( + javaOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final code = sink.toString(); + expect(code, isNot(contains(generatedAnnotation))); + }); }); test('transfers documentation comments', () { - final List comments = [ + final comments = [ ' api comment', ' api method comment', ' class comment', @@ -1770,12 +1672,12 @@ void main() { ' enum comment', ' enum member comment', ]; - int count = 0; + var count = 0; - final List unspacedComments = ['////////']; - int unspacedCount = 0; + final unspacedComments = ['////////']; + var unspacedCount = 0; - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'api', @@ -1836,20 +1738,17 @@ void main() { ), ], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); - for (final String comment in comments) { + final code = sink.toString(); + for (final comment in comments) { // This regex finds the comment only between the open and close comment block expect( RegExp( @@ -1863,7 +1762,7 @@ void main() { }); test('creates custom codecs', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1913,48 +1812,42 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains(' extends StandardMessageCodec')); }); test('creates api error class for custom errors', () { final Api api = AstHostApi(name: 'Api', methods: []); - final Root root = Root( + final root = Root( apis: [api], classes: [], enums: [], containsHostApi: true, ); - final StringBuffer sink = StringBuffer(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); - const JavaGenerator generator = JavaGenerator(); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('class FlutterError')); }); test('connection error contains channel name', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1980,19 +1873,16 @@ void main() { enums: [], containsFlutterApi: true, ); - final StringBuffer sink = StringBuffer(); - const JavaGenerator generator = JavaGenerator(); - const InternalJavaOptions javaOptions = InternalJavaOptions( - className: 'Messages', - javaOut: '', - ); + final sink = StringBuffer(); + const generator = JavaGenerator(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); generator.generate( javaOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('createConnectionError(channelName)')); expect( code, @@ -2001,4 +1891,33 @@ void main() { ), ); }); + + test('data class equality', () { + final classDefinition = Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'int', isNullable: true), + name: 'field1', + ), + ], + ); + final root = Root( + apis: [], + classes: [classDefinition], + enums: [], + ); + final sink = StringBuffer(); + const javaOptions = InternalJavaOptions(className: 'Messages', javaOut: ''); + const generator = JavaGenerator(); + generator.generate( + javaOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final code = sink.toString(); + expect(code, contains('public boolean equals(Object o) {')); + expect(code, contains('public int hashCode() {')); + }); } diff --git a/packages/pigeon/test/kotlin/proxy_api_test.dart b/packages/pigeon/test/kotlin/proxy_api_test.dart index 97b1d42c1d98..e942a2c9bd06 100644 --- a/packages/pigeon/test/kotlin/proxy_api_test.dart +++ b/packages/pigeon/test/kotlin/proxy_api_test.dart @@ -11,7 +11,7 @@ const String DEFAULT_PACKAGE_NAME = 'test_package'; void main() { group('ProxyApi', () { test('one api', () { - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -80,8 +80,8 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const generator = KotlinGenerator(); generator.generate( const InternalKotlinOptions( fileSpecificClassNameComponent: 'MyFile', @@ -91,7 +91,7 @@ void main() { sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); // Instance Manager @@ -165,13 +165,13 @@ void main() { group('inheritance', () { test('extends', () { - final AstProxyApi api2 = AstProxyApi( + final api2 = AstProxyApi( name: 'Api2', constructors: [], fields: [], methods: [], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -189,15 +189,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const generator = KotlinGenerator(); generator.generate( const InternalKotlinOptions(kotlinOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect( collapsedCode, @@ -206,13 +206,13 @@ void main() { }); test('implements', () { - final AstProxyApi api2 = AstProxyApi( + final api2 = AstProxyApi( name: 'Api2', constructors: [], fields: [], methods: [], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -232,32 +232,32 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const generator = KotlinGenerator(); generator.generate( const InternalKotlinOptions(kotlinOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('fun pigeon_getPigeonApiApi2(): PigeonApiApi2')); }); test('implements 2 ProxyApis', () { - final AstProxyApi api2 = AstProxyApi( + final api2 = AstProxyApi( name: 'Api2', constructors: [], fields: [], methods: [], ); - final AstProxyApi api3 = AstProxyApi( + final api3 = AstProxyApi( name: 'Api3', constructors: [], fields: [], methods: [], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -283,15 +283,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const generator = KotlinGenerator(); generator.generate( const InternalKotlinOptions(kotlinOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('fun pigeon_getPigeonApiApi2(): PigeonApiApi2')); expect(code, contains('fun pigeon_getPigeonApiApi3(): PigeonApiApi3')); }); @@ -299,7 +299,7 @@ void main() { group('Constructors', () { test('empty name and no params constructor', () { - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -313,15 +313,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const generator = KotlinGenerator(); generator.generate( const InternalKotlinOptions(kotlinOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect( code, @@ -348,11 +348,11 @@ void main() { }); test('multiple params constructor', () { - final Enum anEnum = Enum( + final anEnum = Enum( name: 'AnEnum', members: [EnumMember(name: 'one')], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -420,15 +420,15 @@ void main() { classes: [], enums: [anEnum], ); - final StringBuffer sink = StringBuffer(); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const generator = KotlinGenerator(); generator.generate( const InternalKotlinOptions(kotlinOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect( code, @@ -455,7 +455,7 @@ void main() { }); test('host platform constructor callback method', () { - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -474,8 +474,8 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const generator = KotlinGenerator(); generator.generate( const InternalKotlinOptions( errorClassName: 'TestError', @@ -485,7 +485,7 @@ void main() { sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect( @@ -499,7 +499,7 @@ void main() { test( 'host platform constructor calls new instance error for required callbacks', () { - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -518,8 +518,8 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const generator = KotlinGenerator(); generator.generate( const InternalKotlinOptions( errorClassName: 'TestError', @@ -529,7 +529,7 @@ void main() { sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect( @@ -542,11 +542,11 @@ void main() { group('Fields', () { test('constructor with fields', () { - final Enum anEnum = Enum( + final anEnum = Enum( name: 'AnEnum', members: [EnumMember(name: 'one')], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -611,15 +611,15 @@ void main() { classes: [], enums: [anEnum], ); - final StringBuffer sink = StringBuffer(); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const generator = KotlinGenerator(); generator.generate( const InternalKotlinOptions(kotlinOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect( collapsedCode, @@ -678,13 +678,13 @@ void main() { }); test('attached field', () { - final AstProxyApi api2 = AstProxyApi( + final api2 = AstProxyApi( name: 'Api2', constructors: [], fields: [], methods: [], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -707,15 +707,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const generator = KotlinGenerator(); generator.generate( const InternalKotlinOptions(kotlinOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains(r'abstract fun aField(pigeon_instance: Api): Api2'), @@ -729,13 +729,13 @@ void main() { }); test('static attached field', () { - final AstProxyApi api2 = AstProxyApi( + final api2 = AstProxyApi( name: 'Api2', constructors: [], fields: [], methods: [], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -759,15 +759,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const generator = KotlinGenerator(); generator.generate( const InternalKotlinOptions(kotlinOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains(r'abstract fun aField(): Api2')); expect( code, @@ -780,11 +780,11 @@ void main() { group('Host methods', () { test('multiple params method', () { - final Enum anEnum = Enum( + final anEnum = Enum( name: 'AnEnum', members: [EnumMember(name: 'one')], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -854,15 +854,15 @@ void main() { classes: [], enums: [anEnum], ); - final StringBuffer sink = StringBuffer(); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const generator = KotlinGenerator(); generator.generate( const InternalKotlinOptions(kotlinOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect( collapsedCode, @@ -883,7 +883,7 @@ void main() { }); test('static method', () { - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -903,15 +903,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const generator = KotlinGenerator(); generator.generate( const InternalKotlinOptions(kotlinOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect(collapsedCode, contains('abstract fun doSomething()')); expect(collapsedCode, contains(r'api.doSomething()')); @@ -920,11 +920,11 @@ void main() { group('Flutter methods', () { test('multiple params flutter method', () { - final Enum anEnum = Enum( + final anEnum = Enum( name: 'AnEnum', members: [EnumMember(name: 'one')], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -988,15 +988,15 @@ void main() { classes: [], enums: [anEnum], ); - final StringBuffer sink = StringBuffer(); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const generator = KotlinGenerator(); generator.generate( const InternalKotlinOptions(kotlinOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect( collapsedCode, @@ -1022,7 +1022,7 @@ void main() { test( 'InstanceManager passes runnable field and not a new runnable instance', () { - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -1034,15 +1034,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const generator = KotlinGenerator(); generator.generate( const InternalKotlinOptions(kotlinOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect( @@ -1072,7 +1072,7 @@ void main() { ); test('InstanceManager.getInstance specifies nonnull type', () { - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -1084,15 +1084,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const generator = KotlinGenerator(); generator.generate( const InternalKotlinOptions(kotlinOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect( @@ -1121,7 +1121,7 @@ void main() { /// void method( int param1, int param2, ) /// ``` String _collapseNewlineAndIndentation(String string) { - final StringBuffer result = StringBuffer(); + final result = StringBuffer(); for (final String line in string.split('\n')) { result.write('${line.trimLeft()} '); } diff --git a/packages/pigeon/test/kotlin_generator_test.dart b/packages/pigeon/test/kotlin_generator_test.dart index 0196ca859233..479357d57fe3 100644 --- a/packages/pigeon/test/kotlin_generator_test.dart +++ b/packages/pigeon/test/kotlin_generator_test.dart @@ -25,7 +25,7 @@ final Enum emptyEnum = Enum( void main() { test('gen one class', () { - final Class classDefinition = Class( + final classDefinition = Class( name: 'Foobar', fields: [ NamedType( @@ -34,23 +34,21 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [], classes: [classDefinition], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('data class Foobar (')); expect(code, contains('val field1: Long? = null')); expect(code, contains('fun fromList(pigeonVar_list: List): Foobar')); @@ -59,37 +57,31 @@ void main() { }); test('gen one enum', () { - final Enum anEnum = Enum( + final anEnum = Enum( name: 'Foobar', members: [ EnumMember(name: 'one'), EnumMember(name: 'two'), ], ); - final Root root = Root( - apis: [], - classes: [], - enums: [anEnum], - ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final root = Root(apis: [], classes: [], enums: [anEnum]); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('enum class Foobar(val raw: Int) {')); expect(code, contains('ONE(0)')); expect(code, contains('TWO(1)')); }); test('gen class with enum', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -123,18 +115,16 @@ void main() { ), ], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('enum class Foo(val raw: Int) {')); expect(code, contains('data class Bar (')); expect(code, contains('val field1: Foo,')); @@ -147,7 +137,7 @@ void main() { }); test('primitive enum host', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Bar', @@ -181,24 +171,22 @@ void main() { ), ], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('enum class Foo(val raw: Int) {')); expect(code, contains('Foo.ofRaw(it.toInt())')); }); test('gen one host api', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -247,18 +235,16 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('interface Api')); expect(code, contains('fun doSomething(input: Input): Output')); expect( @@ -291,7 +277,7 @@ void main() { }); test('all the simple datatypes header', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -397,19 +383,17 @@ void main() { enums: [], ); - final StringBuffer sink = StringBuffer(); + final sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('val aBool: Boolean')); expect(code, contains('val aInt: Long')); expect(code, contains('val aDouble: Double')); @@ -429,7 +413,7 @@ void main() { }); test('gen one flutter api', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -478,18 +462,16 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -500,7 +482,7 @@ void main() { }); test('gen host void api', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -536,24 +518,22 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, isNot(matches('.*doSomething(.*) ->'))); expect(code, matches('doSomething(.*)')); }); test('gen flutter void return api', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -589,18 +569,16 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('callback: (Result) -> Unit')); expect(code, contains('callback(Result.success(Unit))')); // Lines should not end in semicolons. @@ -608,7 +586,7 @@ void main() { }); test('gen host void argument api', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -639,18 +617,16 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('fun doSomething(): Output')); expect(code, contains('listOf(api.doSomething())')); expect(code, contains('wrapError(exception)')); @@ -658,7 +634,7 @@ void main() { }); test('gen flutter void argument api', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -689,18 +665,16 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains('fun doSomething(callback: (Result) -> Unit)'), @@ -709,7 +683,7 @@ void main() { }); test('gen list', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -724,24 +698,22 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('data class Foobar')); expect(code, contains('val field1: List? = null')); }); test('gen map', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -756,24 +728,22 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('data class Foobar')); expect(code, contains('val field1: Map? = null')); }); test('gen nested', () { - final Class classDefinition = Class( + final classDefinition = Class( name: 'Outer', fields: [ NamedType( @@ -786,7 +756,7 @@ void main() { ), ], ); - final Class nestedClass = Class( + final nestedClass = Class( name: 'Nested', fields: [ NamedType( @@ -795,23 +765,21 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [], classes: [classDefinition, nestedClass], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('data class Outer')); expect(code, contains('data class Nested')); expect(code, contains('val nested: Nested? = null')); @@ -821,7 +789,7 @@ void main() { }); test('gen one async Host Api', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -871,25 +839,23 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('interface Api')); expect(code, contains('api.doSomething(argArg) {')); expect(code, contains('reply.reply(PigeonUtils.wrapResult(data))')); }); test('gen one async Flutter Api', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -939,31 +905,29 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('class Api')); expect(code, matches('fun doSomething.*Input.*callback.*Output.*Unit')); }); test('gen one enum class', () { - final Enum anEnum = Enum( + final anEnum = Enum( name: 'SampleEnum', members: [ EnumMember(name: 'sampleVersion'), EnumMember(name: 'sampleTest'), ], ); - final Class classDefinition = Class( + final classDefinition = Class( name: 'EnumClass', fields: [ NamedType( @@ -976,23 +940,21 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [], classes: [classDefinition], enums: [anEnum], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('enum class SampleEnum(val raw: Int)')); expect(code, contains('SAMPLE_VERSION(0)')); expect(code, contains('SAMPLE_TEST(1)')); @@ -1003,25 +965,68 @@ void main() { } test('header', () { - final Root root = Root(apis: [], classes: [], enums: []); - final StringBuffer sink = StringBuffer(); - final InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + final root = Root(apis: [], classes: [], enums: []); + final sink = StringBuffer(); + final kotlinOptions = InternalKotlinOptions( copyrightHeader: makeIterable('hello world'), kotlinOut: '', ); - const KotlinGenerator generator = KotlinGenerator(); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, startsWith('// hello world')); }); + group('generated annotation', () { + late Root root; + late KotlinGenerator generator; + late StringBuffer sink; + + setUp(() { + root = Root(apis: [], classes: [], enums: []); + generator = const KotlinGenerator(); + sink = StringBuffer(); + }); + + test('with generated annotation', () { + final kotlinOptions = InternalKotlinOptions( + copyrightHeader: makeIterable('hello world'), + kotlinOut: '', + useGeneratedAnnotation: true, + ); + generator.generate( + kotlinOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final code = sink.toString(); + expect(code, contains(kotlinGeneratedAnnotation)); + }); + + test('without generated annotation', () { + final kotlinOptions = InternalKotlinOptions( + copyrightHeader: makeIterable('hello world'), + kotlinOut: '', + ); + generator.generate( + kotlinOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final code = sink.toString(); + expect(code, isNot(contains(kotlinGeneratedAnnotation))); + }); + }); + test('generics - list', () { - final Class classDefinition = Class( + final classDefinition = Class( name: 'Foobar', fields: [ NamedType( @@ -1036,29 +1041,27 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [], classes: [classDefinition], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('data class Foobar')); expect(code, contains('val field1: List')); }); test('generics - maps', () { - final Class classDefinition = Class( + final classDefinition = Class( name: 'Foobar', fields: [ NamedType( @@ -1074,29 +1077,27 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [], classes: [classDefinition], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('data class Foobar')); expect(code, contains('val field1: Map')); }); test('host generics argument', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1124,23 +1125,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('fun doit(arg: List')); }); test('flutter generics argument', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1168,23 +1167,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('fun doit(argArg: List')); }); test('host generics return', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1207,25 +1204,23 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('fun doit(): List')); expect(code, contains('listOf(api.doit())')); expect(code, contains('reply.reply(wrapped)')); }); test('flutter generics return', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1248,25 +1243,23 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('fun doit(callback: (Result>) -> Unit)')); expect(code, contains('val output = it[0] as List')); expect(code, contains('callback(Result.success(output))')); }); test('host multiple args', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1301,18 +1294,16 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('fun add(x: Long, y: Long): Long')); expect(code, contains('val args = message as List')); expect(code, contains('listOf(api.add(xArg, yArg))')); @@ -1320,7 +1311,7 @@ void main() { }); test('flutter multiple args', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1355,18 +1346,16 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('val channel = BasicMessageChannel')); expect(code, contains('callback(Result.success(output))')); expect( @@ -1379,7 +1368,7 @@ void main() { }); test('return nullable host', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1399,23 +1388,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('fun doit(): Long?')); }); test('return nullable host async', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1436,23 +1423,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('fun doit(callback: (Result) -> Unit')); }); test('nullable argument host', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1477,23 +1462,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('val fooArg = args[0]')); }); test('nullable argument flutter', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1518,18 +1501,16 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains('fun doit(fooArg: Long?, callback: (Result) -> Unit)'), @@ -1537,7 +1518,7 @@ void main() { }); test('nonnull fields', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1576,23 +1557,21 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('val input: String\n')); }); test('transfers documentation comments', () { - final List comments = [ + final comments = [ ' api comment', ' api method comment', ' class comment', @@ -1600,12 +1579,12 @@ void main() { ' enum comment', ' enum member comment', ]; - int count = 0; + var count = 0; - final List unspacedComments = ['////////']; - int unspacedCount = 0; + final unspacedComments = ['////////']; + var unspacedCount = 0; - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'api', @@ -1666,19 +1645,17 @@ void main() { ), ], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); - for (final String comment in comments) { + final code = sink.toString(); + for (final comment in comments) { // This regex finds the comment only between the open and close comment block expect( RegExp( @@ -1692,7 +1669,7 @@ void main() { }); test('creates custom codecs', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1742,51 +1719,46 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains(' : StandardMessageCodec() ')); }); test('creates api error class for custom errors', () { - final Method method = Method( + final method = Method( name: 'doSomething', location: ApiLocation.host, returnType: const TypeDeclaration.voidDeclaration(), parameters: [], ); - final AstHostApi api = AstHostApi( - name: 'SomeApi', - methods: [method], - ); - final Root root = Root( + final api = AstHostApi(name: 'SomeApi', methods: [method]); + final root = Root( apis: [api], classes: [], enums: [], containsHostApi: true, ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions( errorClassName: 'SomeError', kotlinOut: '', ); - const KotlinGenerator generator = KotlinGenerator(); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('class SomeError')); expect(code, contains('if (exception is SomeError)')); expect(code, contains('exception.code,')); @@ -1795,7 +1767,7 @@ void main() { }); test('connection error contains channel name', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1821,18 +1793,16 @@ void main() { enums: [], containsFlutterApi: true, ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -1848,7 +1818,7 @@ void main() { }); test('gen host uses default error class', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1873,23 +1843,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('FlutterError')); }); test('gen flutter uses default error class', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1914,23 +1882,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( - kotlinOut: '', - ); - const KotlinGenerator generator = KotlinGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('FlutterError')); }); test('gen host uses error class', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1955,26 +1921,26 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const String errorClassName = 'FooError'; - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + final sink = StringBuffer(); + const errorClassName = 'FooError'; + const kotlinOptions = InternalKotlinOptions( errorClassName: errorClassName, kotlinOut: '', ); - const KotlinGenerator generator = KotlinGenerator(); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains(errorClassName)); expect(code, isNot(contains('FlutterError'))); }); test('gen flutter uses error class', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1999,26 +1965,26 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const String errorClassName = 'FooError'; - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + final sink = StringBuffer(); + const errorClassName = 'FooError'; + const kotlinOptions = InternalKotlinOptions( errorClassName: errorClassName, kotlinOut: '', ); - const KotlinGenerator generator = KotlinGenerator(); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains(errorClassName)); expect(code, isNot(contains('FlutterError'))); }); test('do not generate duplicated entries in writeValue', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'FooBar', @@ -2067,13 +2033,13 @@ void main() { enums: [], ); - final StringBuffer sink = StringBuffer(); - const String errorClassName = 'FooError'; - const InternalKotlinOptions kotlinOptions = InternalKotlinOptions( + final sink = StringBuffer(); + const errorClassName = 'FooError'; + const kotlinOptions = InternalKotlinOptions( errorClassName: errorClassName, kotlinOut: '', ); - const KotlinGenerator generator = KotlinGenerator(); + const generator = KotlinGenerator(); generator.generate( kotlinOptions, root, @@ -2081,7 +2047,7 @@ void main() { dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); // Extract override fun writeValue block final int blockStart = code.indexOf('override fun writeValue'); @@ -2091,8 +2057,8 @@ void main() { final String writeValueBlock = code.substring(blockStart, blockEnd); // Count the occurrence of 'is Foo' in the block - int count = 0; - int index = 0; + var count = 0; + var index = 0; while (index != -1) { index = writeValueBlock.indexOf('is Foo', index); if (index != -1) { @@ -2104,4 +2070,66 @@ void main() { // There should be only one occurrence of 'is Foo' in the block expect(count, 1); }); + + test('data class equality', () { + final classDefinition = Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'int', isNullable: true), + name: 'field1', + ), + ], + ); + final root = Root( + apis: [], + classes: [classDefinition], + enums: [], + ); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); + generator.generate( + kotlinOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final code = sink.toString(); + expect(code, contains('override fun equals(other: Any?): Boolean {')); + expect(code, contains('override fun hashCode(): Int {')); + }); + + test('data class equality multi-field', () { + final classDefinition = Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'int', isNullable: true), + name: 'field1', + ), + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'field2', + ), + ], + ); + final root = Root( + apis: [], + classes: [classDefinition], + enums: [], + ); + final sink = StringBuffer(); + const kotlinOptions = InternalKotlinOptions(kotlinOut: ''); + const generator = KotlinGenerator(); + generator.generate( + kotlinOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final code = sink.toString(); + expect(code, contains('override fun equals(other: Any?): Boolean {')); + expect(code, contains('override fun hashCode(): Int {')); + }); } diff --git a/packages/pigeon/test/objc_generator_test.dart b/packages/pigeon/test/objc_generator_test.dart index 2c806907828e..fb18833f77bc 100644 --- a/packages/pigeon/test/objc_generator_test.dart +++ b/packages/pigeon/test/objc_generator_test.dart @@ -27,7 +27,7 @@ final Enum emptyEnum = Enum( void main() { test('gen one class header', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -42,30 +42,29 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('@interface Foobar')); expect(code, matches('@property.*NSString.*field1')); }); test('gen one class source', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -80,30 +79,29 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('#import "foo.h"')); expect(code, contains('@implementation Foobar')); }); test('gen one enum header', () { - final Root root = Root( + final root = Root( apis: [], classes: [], enums: [ @@ -116,31 +114,30 @@ void main() { ), ], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('typedef NS_ENUM(NSUInteger, Enum1) {')); expect(code, contains(' Enum1One = 0,')); expect(code, contains(' Enum1Two = 1,')); }); test('gen one enum header with prefix', () { - final Root root = Root( + final root = Root( apis: [], classes: [], enums: [ @@ -153,32 +150,31 @@ void main() { ), ], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - prefix: 'PREFIX', - headerIncludePath: '', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + prefix: 'PREFIX', + headerIncludePath: '', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('typedef NS_ENUM(NSUInteger, PREFIXEnum1) {')); expect(code, contains(' PREFIXEnum1One = 0,')); expect(code, contains(' PREFIXEnum1Two = 1,')); }); test('gen one class source with enum', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -209,24 +205,23 @@ void main() { ), ], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('#import "foo.h"')); expect(code, contains('@implementation Foobar')); expect( @@ -238,7 +233,7 @@ void main() { }); test('primitive enum host', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Bar', @@ -272,44 +267,42 @@ void main() { ), ], ); - final StringBuffer sink = StringBuffer(); - const InternalObjcOptions options = InternalObjcOptions( + final sink = StringBuffer(); + const options = InternalObjcOptions( headerIncludePath: 'foo.h', prefix: 'AC', objcHeaderOut: '', objcSourceOut: '', ); { - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: options, - ); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: options, + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('typedef NS_ENUM(NSUInteger, ACFoo)')); expect(code, contains(':(ACFoo)foo error:')); } { - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: options, - ); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: options, + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -322,7 +315,7 @@ void main() { }); test('validate nullable primitive enum', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Bar', @@ -356,7 +349,7 @@ void main() { ), ], ); - const InternalObjcOptions options = InternalObjcOptions( + const options = InternalObjcOptions( headerIncludePath: 'foo.h', objcHeaderOut: '', objcSourceOut: '', @@ -367,7 +360,7 @@ void main() { }); test('gen one class header with enum', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -398,24 +391,23 @@ void main() { ), ], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains('@property(nonatomic, strong, nullable) Enum1Box * enum1;'), @@ -423,7 +415,7 @@ void main() { }); test('gen one api header', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -472,24 +464,23 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('@interface Input')); expect(code, contains('@interface Output')); expect(code, contains('@protocol Api')); @@ -499,7 +490,7 @@ void main() { }); test('gen one api source', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -548,24 +539,23 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('#import "foo.h"')); expect(code, contains('@implementation Input')); expect(code, contains('@implementation Output')); @@ -579,7 +569,7 @@ void main() { }); test('all the simple datatypes header', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -635,24 +625,23 @@ void main() { enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('@interface Foobar')); expect(code, contains('@class FlutterStandardTypedData;')); expect(code, matches('@property.*strong.*NSNumber.*aBool')); @@ -678,7 +667,7 @@ void main() { }); test('bool source', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -694,24 +683,23 @@ void main() { enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('@implementation Foobar')); expect( code, @@ -720,7 +708,7 @@ void main() { }); test('nested class header', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -748,24 +736,23 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains('@property(nonatomic, strong, nullable) Input * nested;'), @@ -773,7 +760,7 @@ void main() { }); test('nested class source', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -801,24 +788,23 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains('pigeonResult.nested = GetNullableObjectAtIndex(list, 0);'), @@ -826,7 +812,7 @@ void main() { }); test('prefix class header', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -841,30 +827,29 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('@interface ABCFoobar')); }); test('prefix class source', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -879,30 +864,29 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('@implementation ABCFoobar')); }); test('prefix nested class header', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -955,32 +939,31 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, matches('property.*ABCInput')); expect(code, matches('ABCNested.*doSomething.*ABCInput')); expect(code, contains('@protocol ABCApi')); }); test('prefix nested class source', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1033,32 +1016,31 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('ABCInput fromList')); expect(code, matches(r'ABCInput.*=.*args.*0.*\;')); expect(code, contains('void SetUpABCApi(')); }); test('gen flutter api header', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1107,24 +1089,23 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('@interface Api : NSObject')); expect( code, @@ -1136,7 +1117,7 @@ void main() { }); test('gen flutter api source', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1185,30 +1166,29 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('@implementation Api')); expect(code, matches('void.*doSomething.*Input.*Output.*{')); }); test('gen host void header', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1244,30 +1224,29 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('(void)doSomething:')); }); test('gen host void source', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1303,32 +1282,31 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, isNot(matches('=.*doSomething'))); expect(code, matches('[.*doSomething:.*]')); expect(code, contains('callback(wrapResult(nil, error))')); }); test('gen flutter void return header', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1364,30 +1342,29 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('completion:(void (^)(FlutterError *_Nullable))')); }); test('gen flutter void return source', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1423,31 +1400,30 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('completion:(void (^)(FlutterError *_Nullable))')); expect(code, contains('completion(nil)')); }); test('gen host void arg header', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1478,30 +1454,29 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, matches('ABCOutput.*doSomethingWithError:[(]FlutterError')); }); test('gen host void arg source', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1532,30 +1507,29 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, matches('output.*=.*api doSomethingWithError:&error')); }); test('gen flutter void arg header', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1586,25 +1560,24 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -1614,7 +1587,7 @@ void main() { }); test('gen flutter void arg source', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1645,25 +1618,24 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -1674,7 +1646,7 @@ void main() { }); test('gen list', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -1689,30 +1661,29 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('@interface Foobar')); expect(code, matches('@property.*NSArray.*field1')); }); test('gen map', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -1727,30 +1698,29 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('@interface Foobar')); expect(code, matches('@property.*NSDictionary.*field1')); }); test('gen map field with object', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -1772,24 +1742,23 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('@interface Foobar')); expect( code, @@ -1800,7 +1769,7 @@ void main() { }); test('gen map argument with object', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1829,29 +1798,28 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('(NSDictionary *)foo')); }); test('async void (input) HostApi header', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1897,25 +1865,24 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -1925,7 +1892,7 @@ void main() { }); test('async output(input) HostApi header', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1975,25 +1942,24 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -2003,7 +1969,7 @@ void main() { }); test('async output(void) HostApi header', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -2035,25 +2001,24 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -2063,7 +2028,7 @@ void main() { }); test('async void (void) HostApi header', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -2081,25 +2046,24 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -2109,7 +2073,7 @@ void main() { }); test('async output(input) HostApi source', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -2159,25 +2123,24 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -2187,7 +2150,7 @@ void main() { }); test('async void (input) HostApi source', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -2233,25 +2196,24 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -2261,7 +2223,7 @@ void main() { }); test('async void (void) HostApi source', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -2279,25 +2241,24 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -2307,7 +2268,7 @@ void main() { }); test('async output(void) HostApi source', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -2339,25 +2300,24 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -2371,57 +2331,80 @@ void main() { } test('source copyright', () { - final Root root = Root(apis: [], classes: [], enums: []); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - copyrightHeader: makeIterable('hello world'), - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final root = Root(apis: [], classes: [], enums: []); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + copyrightHeader: makeIterable('hello world'), + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, startsWith('// hello world')); }); test('header copyright', () { - final Root root = Root(apis: [], classes: [], enums: []); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - copyrightHeader: makeIterable('hello world'), - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final root = Root(apis: [], classes: [], enums: []); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + copyrightHeader: makeIterable('hello world'), + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, startsWith('// hello world')); }); + test('only uses new-style module imports', () { + final root = Root(apis: [], classes: [], enums: []); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + copyrightHeader: makeIterable('hello world'), + objcHeaderOut: '', + objcSourceOut: '', + ), + ); + generator.generate( + generatorOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final code = sink.toString(); + expect(code, contains('@import')); + expect(code, isNot(contains('#import <'))); + }); + test('field generics', () { - final Class classDefinition = Class( + final classDefinition = Class( name: 'Foobar', fields: [ NamedType( @@ -2436,35 +2419,34 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [], classes: [classDefinition], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('NSArray * field1')); }); test('host generics argument', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -2493,47 +2475,45 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('doitArg:(NSArray *)arg')); } { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -2544,7 +2524,7 @@ void main() { }); test('flutter generics argument', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -2573,53 +2553,51 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('doitArg:(NSArray *)arg')); } { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('doitArg:(NSArray *)arg')); } }); test('host nested generic argument', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -2654,31 +2632,30 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('doitArg:(NSArray *> *)arg')); } }); test('host generics return', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -2702,56 +2679,54 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains('- (nullable NSArray *)doitWithError:'), ); } { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('NSArray *output =')); } }); test('flutter generics return', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -2775,50 +2750,48 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains('doitWithCompletion:(void (^)(NSArray *'), ); } { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains('doitWithCompletion:(void (^)(NSArray *'), @@ -2827,7 +2800,7 @@ void main() { }); test('host multiple args', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -2863,25 +2836,24 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -2890,25 +2862,24 @@ void main() { ); } { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('NSArray *args = message;')); expect( code, @@ -2930,7 +2901,7 @@ void main() { }); test('host multiple args async', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -2967,25 +2938,24 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -2994,25 +2964,24 @@ void main() { ); } { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('NSArray *args = message;')); expect( code, @@ -3031,7 +3000,7 @@ void main() { }); test('flutter multiple args', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -3067,25 +3036,24 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -3094,25 +3062,24 @@ void main() { ); } { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -3198,47 +3165,45 @@ void main() { test('host custom objc selector', () { final Root divideRoot = getDivideRoot(ApiLocation.host); { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, divideRoot, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, matches('divideValue:.*by:.*error.*;')); } { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, divideRoot, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, matches('divideValue:.*by:.*error.*;')); } }); @@ -3246,53 +3211,51 @@ void main() { test('flutter custom objc selector', () { final Root divideRoot = getDivideRoot(ApiLocation.flutter); { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, divideRoot, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, matches('divideValue:.*by:.*completion.*;')); } { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - headerIncludePath: 'foo.h', - prefix: 'ABC', - objcHeaderOut: '', - objcSourceOut: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + headerIncludePath: 'foo.h', + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + ), + ); generator.generate( generatorOptions, divideRoot, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, matches('divideValue:.*by:.*completion.*{')); } }); test('test non null field', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -3310,30 +3273,29 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('@interface Foobar')); expect(code, contains('@property(nonatomic, copy) NSString * field1')); }); test('return nullable flutter header', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -3353,24 +3315,23 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, matches( @@ -3380,7 +3341,7 @@ void main() { }); test('return nullable flutter source', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -3400,29 +3361,28 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, matches(r'doitWithCompletion.*NSNumber \*_Nullable')); }); test('return nullable host header', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -3442,29 +3402,28 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, matches(r'nullable NSNumber.*doitWithError')); }); test('nullable argument host', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -3490,45 +3449,43 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('doitFoo:(nullable NSNumber *)foo')); } { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains('NSNumber *arg_foo = GetNullableObjectAtIndex(args, 0);'), @@ -3537,7 +3494,7 @@ void main() { }); test('nullable argument flutter', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -3563,51 +3520,49 @@ void main() { enums: [], ); { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('doitFoo:(nullable NSNumber *)foo')); } { - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('- (void)doitFoo:(nullable NSNumber *)arg_foo')); } }); test('background platform channel', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -3628,24 +3583,23 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -3656,7 +3610,7 @@ void main() { }); test('transfers documentation comments', () { - final List comments = [ + final comments = [ ' api comment', ' api method comment', ' class comment', @@ -3664,12 +3618,12 @@ void main() { ' enum comment', ' enum member comment', ]; - int count = 0; + var count = 0; - final List unspacedComments = ['////////']; - int unspacedCount = 0; + final unspacedComments = ['////////']; + var unspacedCount = 0; - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'api', @@ -3730,32 +3684,31 @@ void main() { ), ], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); - for (final String comment in comments) { + final code = sink.toString(); + for (final comment in comments) { expect(code, contains('///$comment')); } expect(code, contains('/// ///')); }); test('creates custom codecs', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -3805,29 +3758,28 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains(' : FlutterStandardReader')); }); test('connection error contains channel name', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -3853,24 +3805,23 @@ void main() { enums: [], containsFlutterApi: true, ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -3881,14 +3832,14 @@ void main() { }); test('header of FlutterApi uses correct enum name with prefix', () { - final Enum enum1 = Enum( + final enum1 = Enum( name: 'Enum1', members: [ EnumMember(name: 'one'), EnumMember(name: 'two'), ], ); - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -3910,38 +3861,37 @@ void main() { classes: [], enums: [enum1], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - prefix: 'FLT', - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + prefix: 'FLT', + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, isNot(contains('FLTFLT'))); expect(code, contains('FLTEnum1Box')); }); test('source of FlutterApi uses correct enum name with prefix', () { - final Enum enum1 = Enum( + final enum1 = Enum( name: 'Enum1', members: [ EnumMember(name: 'one'), EnumMember(name: 'two'), ], ); - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -3963,43 +3913,42 @@ void main() { classes: [], enums: [enum1], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - prefix: 'FLT', - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + prefix: 'FLT', + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, isNot(contains('FLTFLT'))); expect(code, contains('FLTEnum1Box')); }); test('header of HostApi uses correct enum name with prefix', () { - final Enum enum1 = Enum( + final enum1 = Enum( name: 'Enum1', members: [ EnumMember(name: 'one'), EnumMember(name: 'two'), ], ); - final TypeDeclaration enumType = TypeDeclaration( + final enumType = TypeDeclaration( baseName: 'Enum1', isNullable: false, associatedEnum: enum1, ); - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -4017,43 +3966,42 @@ void main() { classes: [], enums: [enum1], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.header, - languageOptions: const InternalObjcOptions( - prefix: 'FLT', - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + prefix: 'FLT', + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, isNot(contains('FLTFLT'))); expect(code, contains('FLTEnum1Box')); }); test('source of HostApi uses correct enum name with prefix', () { - final Enum enum1 = Enum( + final enum1 = Enum( name: 'Enum1', members: [ EnumMember(name: 'one'), EnumMember(name: 'two'), ], ); - final TypeDeclaration enumType = TypeDeclaration( + final enumType = TypeDeclaration( baseName: 'Enum1', isNullable: false, associatedEnum: enum1, ); - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -4071,26 +4019,84 @@ void main() { classes: [], enums: [enum1], ); - final StringBuffer sink = StringBuffer(); - const ObjcGenerator generator = ObjcGenerator(); - final OutputFileOptions generatorOptions = - OutputFileOptions( - fileType: FileType.source, - languageOptions: const InternalObjcOptions( - prefix: 'FLT', - objcHeaderOut: '', - objcSourceOut: '', - headerIncludePath: '', - ), - ); + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + prefix: 'FLT', + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); generator.generate( generatorOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, isNot(contains('FLTFLT'))); expect(code, contains('FLTEnum1Box')); }); + + test('data class equality', () { + final root = Root( + apis: [], + classes: [ + Class( + name: 'Foo', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'int', isNullable: false), + name: 'bar', + ), + ], + ), + ], + enums: [], + ); + { + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.header, + languageOptions: const InternalObjcOptions( + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); + generator.generate( + generatorOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + } + { + final sink = StringBuffer(); + const generator = ObjcGenerator(); + final generatorOptions = OutputFileOptions( + fileType: FileType.source, + languageOptions: const InternalObjcOptions( + prefix: 'ABC', + objcHeaderOut: '', + objcSourceOut: '', + headerIncludePath: '', + ), + ); + generator.generate( + generatorOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final code = sink.toString(); + expect(code, contains('- (BOOL)isEqual:(id)object {')); + expect(code, contains('- (NSUInteger)hash {')); + } + }); } diff --git a/packages/pigeon/test/pigeon_lib_test.dart b/packages/pigeon/test/pigeon_lib_test.dart index b2409c4dbc58..7b2d3b78a1c7 100644 --- a/packages/pigeon/test/pigeon_lib_test.dart +++ b/packages/pigeon/test/pigeon_lib_test.dart @@ -45,8 +45,8 @@ void main() { /// after the [callback] is executed. void withTempFile(String filename, void Function(File) callback) { final Directory dir = Directory.systemTemp.createTempSync(); - final String path = '${dir.path}/$filename'; - final File file = File(path); + final path = '${dir.path}/$filename'; + final file = File(path); file.createSync(); try { callback(file); @@ -137,6 +137,13 @@ void main() { expect(opts.kotlinOptions?.package, equals('com.google.foo')); }); + test('parse args - kotlin_use_generated_annotation', () { + final PigeonOptions opts = Pigeon.parseArgs([ + '--kotlin_use_generated_annotation', + ]); + expect(opts.kotlinOptions!.useGeneratedAnnotation, isTrue); + }); + test('parse args - cpp_header_out', () { final PigeonOptions opts = Pigeon.parseArgs([ '--cpp_header_out', @@ -177,7 +184,7 @@ void main() { }); test('simple parse api', () { - const String code = ''' + const code = ''' class Input1 { String? input; } @@ -196,12 +203,12 @@ abstract class Api1 { } '''; final ParseResults parseResult = parseSource(code); - expect(parseResult.errors.length, equals(0)); + expect(parseResult.errors, isEmpty); final Root root = parseResult.root; - expect(root.classes.length, equals(3)); - expect(root.apis.length, equals(1)); + expect(root.classes, hasLength(3)); + expect(root.apis, hasLength(1)); expect(root.apis[0].name, equals('Api1')); - expect(root.apis[0].methods.length, equals(1)); + expect(root.apis[0].methods, hasLength(1)); expect(root.apis[0].methods[0].name, equals('doit')); expect(root.apis[0].methods[0].parameters[0].name, equals('input')); expect( @@ -226,24 +233,24 @@ abstract class Api1 { expect(output, isNotNull); expect(unused, isNotNull); - expect(input?.fields.length, equals(1)); + expect(input?.fields, hasLength(1)); expect(input?.fields[0].name, equals('input')); expect(input?.fields[0].type.baseName, equals('String')); expect(input?.fields[0].type.isNullable, isTrue); - expect(output?.fields.length, equals(1)); + expect(output?.fields, hasLength(1)); expect(output?.fields[0].name, equals('output')); expect(output?.fields[0].type.baseName, equals('String')); expect(output?.fields[0].type.isNullable, isTrue); - expect(unused?.fields.length, equals(1)); + expect(unused?.fields, hasLength(1)); expect(unused?.fields[0].name, equals('field')); expect(unused?.fields[0].type.baseName, equals('String')); expect(unused?.fields[0].type.isNullable, isTrue); }); test('invalid datatype', () { - const String source = ''' + const source = ''' class InvalidDatatype { dynamic something; } @@ -254,13 +261,13 @@ abstract class Api { } '''; final ParseResults results = parseSource(source); - expect(results.errors.length, 1); + expect(results.errors, hasLength(1)); expect(results.errors[0].message, contains('InvalidDatatype')); expect(results.errors[0].message, contains('dynamic')); }); test('Only allow one api annotation', () { - const String source = ''' + const source = ''' @HostApi() @FlutterApi() abstract class Api { @@ -268,7 +275,7 @@ abstract class Api { } '''; final ParseResults results = parseSource(source); - expect(results.errors.length, 1); + expect(results.errors, hasLength(1)); expect( results.errors[0].message, contains( @@ -278,7 +285,7 @@ abstract class Api { }); test('Only allow one api annotation plus @ConfigurePigeon', () { - const String source = ''' + const source = ''' @ConfigurePigeon(InternalPigeonOptions( dartOut: 'stdout', javaOut: 'stdout', @@ -291,11 +298,11 @@ abstract class Api { '''; final ParseResults results = parseSource(source); - expect(results.errors.length, 0); + expect(results.errors, isEmpty); }); test('enum in classes', () { - const String code = ''' + const code = ''' enum Enum1 { one, two, @@ -311,17 +318,17 @@ abstract class Api { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, equals(0)); - expect(results.root.classes.length, equals(1)); + expect(results.errors, isEmpty); + expect(results.root.classes, hasLength(1)); expect(results.root.classes[0].name, equals('ClassWithEnum')); - expect(results.root.classes[0].fields.length, equals(1)); + expect(results.root.classes[0].fields, hasLength(1)); expect(results.root.classes[0].fields[0].type.baseName, equals('Enum1')); expect(results.root.classes[0].fields[0].type.isNullable, isTrue); expect(results.root.classes[0].fields[0].name, equals('enum1')); }); test('two methods', () { - const String code = ''' + const code = ''' class Input1 { String? input; } @@ -337,15 +344,15 @@ abstract class ApiTwoMethods { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 0); - expect(results.root.apis.length, 1); - expect(results.root.apis[0].methods.length, equals(2)); + expect(results.errors, isEmpty); + expect(results.root.apis, hasLength(1)); + expect(results.root.apis[0].methods, hasLength(2)); expect(results.root.apis[0].methods[0].name, equals('method1')); expect(results.root.apis[0].methods[1].name, equals('method2')); }); test('nested', () { - const String code = ''' + const code = ''' class Input1 { String? input; } @@ -360,18 +367,18 @@ abstract class Api { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, equals(0)); - expect(results.root.classes.length, equals(2)); + expect(results.errors, isEmpty); + expect(results.root.classes, hasLength(2)); final Class nested = results.root.classes.firstWhere( (Class x) => x.name == 'Nested', ); - expect(nested.fields.length, equals(1)); + expect(nested.fields, hasLength(1)); expect(nested.fields[0].type.baseName, equals('Input1')); expect(nested.fields[0].type.isNullable, isTrue); }); test('flutter api', () { - const String code = ''' + const code = ''' class Input1 { String? input; } @@ -386,14 +393,14 @@ abstract class AFlutterApi { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, equals(0)); - expect(results.root.apis.length, equals(1)); + expect(results.errors, isEmpty); + expect(results.root.apis, hasLength(1)); expect(results.root.apis[0].name, equals('AFlutterApi')); expect(results.root.apis[0], isA()); }); test('void host api', () { - const String code = ''' + const code = ''' class Input1 { String? input; } @@ -404,15 +411,15 @@ abstract class VoidApi { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, equals(0)); - expect(results.root.apis.length, equals(1)); - expect(results.root.apis[0].methods.length, equals(1)); + expect(results.errors, isEmpty); + expect(results.root.apis, hasLength(1)); + expect(results.root.apis[0].methods, hasLength(1)); expect(results.root.apis[0].name, equals('VoidApi')); expect(results.root.apis[0].methods[0].returnType.isVoid, isTrue); }); test('void arg host api', () { - const String code = ''' + const code = ''' class Output1 { String? output; } @@ -423,9 +430,9 @@ abstract class VoidArgApi { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, equals(0)); - expect(results.root.apis.length, equals(1)); - expect(results.root.apis[0].methods.length, equals(1)); + expect(results.errors, isEmpty); + expect(results.root.apis, hasLength(1)); + expect(results.root.apis[0].methods, hasLength(1)); expect(results.root.apis[0].name, equals('VoidArgApi')); expect( results.root.apis[0].methods[0].returnType.baseName, @@ -435,7 +442,7 @@ abstract class VoidArgApi { }); test('mockDartClass', () { - const String code = ''' + const code = ''' class Output1 { String? output; } @@ -446,8 +453,8 @@ abstract class ApiWithMockDartClass { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, equals(0)); - expect(results.root.apis.length, equals(1)); + expect(results.errors, isEmpty); + expect(results.root.apis, hasLength(1)); expect( (results.root.apis[0] as AstHostApi).dartHostTestHandler, equals('ApiWithMockDartClassMock'), @@ -455,7 +462,7 @@ abstract class ApiWithMockDartClass { }); test('only visible from nesting', () { - const String code = ''' + const code = ''' class OnlyVisibleFromNesting { String? foo; } @@ -470,14 +477,13 @@ abstract class NestorApi { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 0); - expect(results.root.apis.length, 1); + expect(results.errors, isEmpty); + expect(results.root.apis, hasLength(1)); final List classNames = results.root.classes .map((Class x) => x.name) .toList(); - expect(classNames.length, 2); - expect(classNames.contains('Nestor'), true); - expect(classNames.contains('OnlyVisibleFromNesting'), true); + expect(classNames, hasLength(2)); + expect(classNames, containsAll(['Nestor', 'OnlyVisibleFromNesting'])); }); test('copyright flag', () { @@ -489,13 +495,13 @@ abstract class NestorApi { }); test('Dart generator copyright flag', () { - final Root root = Root(apis: [], classes: [], enums: []); - const PigeonOptions options = PigeonOptions( + final root = Root(apis: [], classes: [], enums: []); + const options = PigeonOptions( copyrightHeader: './copyright_header.txt', dartOut: '', ); - final DartGeneratorAdapter dartGeneratorAdapter = DartGeneratorAdapter(); - final StringBuffer buffer = StringBuffer(); + const dartGeneratorAdapter = DartGeneratorAdapter(); + final buffer = StringBuffer(); dartGeneratorAdapter.generate( buffer, InternalPigeonOptions.fromPigeonOptions(options), @@ -506,13 +512,13 @@ abstract class NestorApi { }); test('Java generator copyright flag', () { - final Root root = Root(apis: [], classes: [], enums: []); - const PigeonOptions options = PigeonOptions( + final root = Root(apis: [], classes: [], enums: []); + const options = PigeonOptions( javaOut: 'Foo.java', copyrightHeader: './copyright_header.txt', ); - final JavaGeneratorAdapter javaGeneratorAdapter = JavaGeneratorAdapter(); - final StringBuffer buffer = StringBuffer(); + const javaGeneratorAdapter = JavaGeneratorAdapter(); + final buffer = StringBuffer(); javaGeneratorAdapter.generate( buffer, InternalPigeonOptions.fromPigeonOptions(options), @@ -523,15 +529,14 @@ abstract class NestorApi { }); test('Objc header generator copyright flag', () { - final Root root = Root(apis: [], classes: [], enums: []); - const PigeonOptions options = PigeonOptions( + final root = Root(apis: [], classes: [], enums: []); + const options = PigeonOptions( copyrightHeader: './copyright_header.txt', objcHeaderOut: '', objcSourceOut: '', ); - final ObjcGeneratorAdapter objcHeaderGeneratorAdapter = - ObjcGeneratorAdapter(); - final StringBuffer buffer = StringBuffer(); + const objcHeaderGeneratorAdapter = ObjcGeneratorAdapter(); + final buffer = StringBuffer(); objcHeaderGeneratorAdapter.generate( buffer, InternalPigeonOptions.fromPigeonOptions(options), @@ -542,15 +547,14 @@ abstract class NestorApi { }); test('Objc source generator copyright flag', () { - final Root root = Root(apis: [], classes: [], enums: []); - const PigeonOptions options = PigeonOptions( + final root = Root(apis: [], classes: [], enums: []); + const options = PigeonOptions( copyrightHeader: './copyright_header.txt', objcHeaderOut: '', objcSourceOut: '', ); - final ObjcGeneratorAdapter objcSourceGeneratorAdapter = - ObjcGeneratorAdapter(); - final StringBuffer buffer = StringBuffer(); + const objcSourceGeneratorAdapter = ObjcGeneratorAdapter(); + final buffer = StringBuffer(); objcSourceGeneratorAdapter.generate( buffer, InternalPigeonOptions.fromPigeonOptions(options), @@ -561,13 +565,13 @@ abstract class NestorApi { }); test('Swift generator copyright flag', () { - final Root root = Root(apis: [], classes: [], enums: []); - const PigeonOptions options = PigeonOptions( + final root = Root(apis: [], classes: [], enums: []); + const options = PigeonOptions( swiftOut: 'Foo.swift', copyrightHeader: './copyright_header.txt', ); - final SwiftGeneratorAdapter swiftGeneratorAdapter = SwiftGeneratorAdapter(); - final StringBuffer buffer = StringBuffer(); + const swiftGeneratorAdapter = SwiftGeneratorAdapter(); + final buffer = StringBuffer(); swiftGeneratorAdapter.generate( buffer, InternalPigeonOptions.fromPigeonOptions(options), @@ -578,14 +582,14 @@ abstract class NestorApi { }); test('C++ header generator copyright flag', () { - final Root root = Root(apis: [], classes: [], enums: []); - const PigeonOptions options = PigeonOptions( + final root = Root(apis: [], classes: [], enums: []); + const options = PigeonOptions( cppSourceOut: '', cppHeaderOut: 'Foo.h', copyrightHeader: './copyright_header.txt', ); - final CppGeneratorAdapter cppHeaderGeneratorAdapter = CppGeneratorAdapter(); - final StringBuffer buffer = StringBuffer(); + const cppHeaderGeneratorAdapter = CppGeneratorAdapter(); + final buffer = StringBuffer(); cppHeaderGeneratorAdapter.generate( buffer, InternalPigeonOptions.fromPigeonOptions(options), @@ -596,16 +600,14 @@ abstract class NestorApi { }); test('C++ source generator copyright flag', () { - final Root root = Root(apis: [], classes: [], enums: []); - const PigeonOptions options = PigeonOptions( + final root = Root(apis: [], classes: [], enums: []); + const options = PigeonOptions( copyrightHeader: './copyright_header.txt', cppHeaderOut: '', cppSourceOut: '', ); - final CppGeneratorAdapter cppSourceGeneratorAdapter = CppGeneratorAdapter( - fileTypeList: [FileType.source], - ); - final StringBuffer buffer = StringBuffer(); + const cppSourceGeneratorAdapter = CppGeneratorAdapter(); + final buffer = StringBuffer(); cppSourceGeneratorAdapter.generate( buffer, InternalPigeonOptions.fromPigeonOptions(options), @@ -616,7 +618,7 @@ abstract class NestorApi { }); test('nested enum', () { - const String code = ''' + const code = ''' enum NestedEnum { one, two } class NestedEnum1 { @@ -638,14 +640,14 @@ abstract class NestedEnumApi { } '''; final ParseResults parseResult = parseSource(code); - expect(parseResult.errors.length, equals(0)); - expect(parseResult.root.apis.length, 1); - expect(parseResult.root.classes.length, 3); - expect(parseResult.root.enums.length, 1); + expect(parseResult.errors, isEmpty); + expect(parseResult.root.apis, hasLength(1)); + expect(parseResult.root.classes, hasLength(3)); + expect(parseResult.root.enums, hasLength(1)); }); test('test circular references', () { - const String code = ''' + const code = ''' class Foo { Bar? bar; } @@ -660,24 +662,24 @@ abstract class NotificationsHostApi { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 0); - expect(results.root.classes.length, 2); + expect(results.errors, isEmpty); + expect(results.root.classes, hasLength(2)); final Class foo = results.root.classes.firstWhere( (Class aClass) => aClass.name == 'Foo', ); - expect(foo.fields.length, 1); + expect(foo.fields, hasLength(1)); expect(foo.fields[0].type.baseName, 'Bar'); }); test('test compilation error', () { - const String code = 'Hello\n'; + const code = 'Hello\n'; final ParseResults results = parseSource(code); - expect(results.errors.length, greaterThanOrEqualTo(1)); + expect(results.errors, hasLength(greaterThanOrEqualTo(1))); expect(results.errors[0].lineNumber, 1); }); test('test method in data class error', () { - const String code = ''' + const code = ''' class Foo { int? x; int? foo() { return x; } @@ -689,13 +691,13 @@ abstract class Api { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 1); + expect(results.errors, hasLength(1)); expect(results.errors[0].lineNumber, 3); expect(results.errors[0].message, contains('Method')); }); test('test field initialization', () { - const String code = ''' + const code = ''' class Foo { int? x = 123; } @@ -706,13 +708,13 @@ abstract class Api { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 1); + expect(results.errors, hasLength(1)); expect(results.errors[0].lineNumber, 2); expect(results.errors[0].message, contains('Initialization')); }); test('test field in api error', () { - const String code = ''' + const code = ''' class Foo { int? x; } @@ -724,13 +726,13 @@ abstract class Api { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 1); + expect(results.errors, hasLength(1)); expect(results.errors[0].lineNumber, 7); expect(results.errors[0].message, contains('Field')); }); test('constructor in data class', () { - const String code = ''' + const code = ''' class Foo { int? x; Foo({this.x}); @@ -742,11 +744,11 @@ abstract class Api { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 0); + expect(results.errors, isEmpty); }); test('constructor body in data class', () { - const String code = ''' + const code = ''' class Foo { int? x; Foo({this.x}) { print('hi'); } @@ -758,13 +760,13 @@ abstract class Api { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 1); + expect(results.errors, hasLength(1)); expect(results.errors[0].lineNumber, 3); expect(results.errors[0].message, contains('Constructor')); }); test('constructor body in data class', () { - const String code = ''' + const code = ''' class Foo { int? x; Foo() : x = 0; @@ -776,13 +778,13 @@ abstract class Api { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 1); + expect(results.errors, hasLength(1)); expect(results.errors[0].lineNumber, 3); expect(results.errors[0].message, contains('Constructor')); }); test('constructor in api class', () { - const String code = ''' + const code = ''' class Foo { int? x; } @@ -794,26 +796,26 @@ abstract class Api { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 1); + expect(results.errors, hasLength(1)); expect(results.errors[0].lineNumber, 7); expect(results.errors[0].message, contains('Constructor')); }); test('test invalid import', () { - const String code = "import 'foo.dart';\n"; + const code = "import 'foo.dart';\n"; final ParseResults results = parseSource(code); - expect(results.errors.length, greaterThanOrEqualTo(1)); + expect(results.errors, hasLength(greaterThanOrEqualTo(1))); expect(results.errors[0].lineNumber, 1); }); test('test valid import', () { - const String code = "import 'package:pigeon/pigeon.dart';\n"; + const code = "import 'package:pigeon/pigeon.dart';\n"; final ParseResults parseResults = parseSource(code); - expect(parseResults.errors.length, 0); + expect(parseResults.errors, isEmpty); }); test('error with static field', () { - const String code = ''' + const code = ''' class WithStaticField { static int? x; int? y; @@ -825,13 +827,13 @@ abstract class WithStaticFieldApi { } '''; final ParseResults parseResult = parseSource(code); - expect(parseResult.errors.length, equals(1)); + expect(parseResult.errors, hasLength(1)); expect(parseResult.errors[0].message, contains('static field')); expect(parseResult.errors[0].lineNumber, isNotNull); }); test('parse generics', () { - const String code = ''' + const code = ''' class Foo { List? list; } @@ -842,14 +844,14 @@ abstract class Api { } '''; final ParseResults parseResult = parseSource(code); - expect(parseResult.errors.length, equals(0)); + expect(parseResult.errors, isEmpty); final NamedType field = parseResult.root.classes[0].fields[0]; - expect(field.type.typeArguments.length, 1); + expect(field.type.typeArguments, hasLength(1)); expect(field.type.typeArguments[0].baseName, 'int'); }); test('parse recursive generics', () { - const String code = ''' + const code = ''' class Foo { List?>? list; } @@ -860,15 +862,15 @@ abstract class Api { } '''; final ParseResults parseResult = parseSource(code); - expect(parseResult.errors.length, equals(0)); + expect(parseResult.errors, isEmpty); final NamedType field = parseResult.root.classes[0].fields[0]; - expect(field.type.typeArguments.length, 1); + expect(field.type.typeArguments, hasLength(1)); expect(field.type.typeArguments[0].baseName, 'List'); expect(field.type.typeArguments[0].typeArguments[0].baseName, 'int'); }); test('enums argument host', () { - const String code = ''' + const code = ''' enum Foo { one, two, @@ -880,11 +882,11 @@ abstract class Api { } '''; final ParseResults parseResult = parseSource(code); - expect(parseResult.errors.length, equals(0)); + expect(parseResult.errors, isEmpty); }); test('enums argument flutter', () { - const String code = ''' + const code = ''' enum Foo { one, @@ -897,11 +899,11 @@ abstract class Api { } '''; final ParseResults parseResult = parseSource(code); - expect(parseResult.errors.length, equals(0)); + expect(parseResult.errors, isEmpty); }); test('enums list argument', () { - const String code = ''' + const code = ''' enum Foo { one, two } @HostApi() @@ -910,11 +912,11 @@ abstract class Api { } '''; final ParseResults parseResult = parseSource(code); - expect(parseResult.errors.length, equals(0)); + expect(parseResult.errors, isEmpty); }); test('enums map argument key', () { - const String code = ''' + const code = ''' enum Foo { one, two } @HostApi() @@ -923,11 +925,11 @@ abstract class Api { } '''; final ParseResults parseResult = parseSource(code); - expect(parseResult.errors.length, equals(0)); + expect(parseResult.errors, isEmpty); }); test('enums map argument value', () { - const String code = ''' + const code = ''' enum Foo { one, two } @HostApi() @@ -936,11 +938,11 @@ abstract class Api { } '''; final ParseResults parseResult = parseSource(code); - expect(parseResult.errors.length, equals(0)); + expect(parseResult.errors, isEmpty); }); test('enums return value', () { - const String code = ''' + const code = ''' enum Foo { one, @@ -953,11 +955,11 @@ abstract class Api { } '''; final ParseResults parseResult = parseSource(code); - expect(parseResult.errors.length, equals(0)); + expect(parseResult.errors, isEmpty); }); test('return type generics', () { - const String code = ''' + const code = ''' @HostApi() abstract class Api { List doit(); @@ -982,7 +984,7 @@ abstract class Api { }); test('argument generics', () { - const String code = ''' + const code = ''' @HostApi() abstract class Api { void doit(int x, List value); @@ -1018,7 +1020,7 @@ abstract class Api { }); test('map generics', () { - const String code = ''' + const code = ''' class Foo { Map map; } @@ -1030,13 +1032,13 @@ abstract class Api { '''; final ParseResults parseResult = parseSource(code); final NamedType field = parseResult.root.classes[0].fields[0]; - expect(field.type.typeArguments.length, 2); + expect(field.type.typeArguments, hasLength(2)); expect(field.type.typeArguments[0].baseName, 'String'); expect(field.type.typeArguments[1].baseName, 'int'); }); test('two parameters', () { - const String code = ''' + const code = ''' class Input { String? input; } @@ -1047,21 +1049,21 @@ abstract class Api { } '''; final ParseResults results = parseSource(code); - expect(results.root.apis.length, 1); - expect(results.root.apis[0].methods.length, equals(1)); + expect(results.root.apis, hasLength(1)); + expect(results.root.apis[0].methods, hasLength(1)); expect(results.root.apis[0].methods[0].name, equals('method')); - expect(results.root.apis[0].methods[0].parameters.length, 2); + expect(results.root.apis[0].methods[0].parameters, hasLength(2)); }); test('no type name argument', () { - const String code = ''' + const code = ''' @HostApi() abstract class Api { void method(x); } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 1); + expect(results.errors, hasLength(1)); expect(results.errors[0].lineNumber, 3); expect( results.errors[0].message, @@ -1070,7 +1072,7 @@ abstract class Api { }); test('custom objc selector', () { - const String code = ''' + const code = ''' @HostApi() abstract class Api { @ObjCSelector('subtractValue:by:') @@ -1078,9 +1080,9 @@ abstract class Api { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 0); - expect(results.root.apis.length, 1); - expect(results.root.apis[0].methods.length, equals(1)); + expect(results.errors, isEmpty); + expect(results.root.apis, hasLength(1)); + expect(results.root.apis[0].methods, hasLength(1)); expect( results.root.apis[0].methods[0].objcSelector, equals('subtractValue:by:'), @@ -1088,7 +1090,7 @@ abstract class Api { }); test('custom objc invalid selector', () { - const String code = ''' + const code = ''' @HostApi() abstract class Api { @ObjCSelector('subtractValue:by:error:') @@ -1096,7 +1098,7 @@ abstract class Api { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 1); + expect(results.errors, hasLength(1)); expect(results.errors[0].lineNumber, 3); expect( results.errors[0].message, @@ -1105,7 +1107,7 @@ abstract class Api { }); test('custom objc no parameters', () { - const String code = ''' + const code = ''' @HostApi() abstract class Api { @ObjCSelector('foobar') @@ -1113,14 +1115,14 @@ abstract class Api { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 0); - expect(results.root.apis.length, 1); - expect(results.root.apis[0].methods.length, equals(1)); + expect(results.errors, isEmpty); + expect(results.root.apis, hasLength(1)); + expect(results.root.apis[0].methods, hasLength(1)); expect(results.root.apis[0].methods[0].objcSelector, equals('foobar')); }); test('custom swift valid function signature', () { - const String code = ''' + const code = ''' @HostApi() abstract class Api { @SwiftFunction('subtractValue(_:by:)') @@ -1128,9 +1130,9 @@ abstract class Api { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 0); - expect(results.root.apis.length, 1); - expect(results.root.apis[0].methods.length, equals(1)); + expect(results.errors, isEmpty); + expect(results.root.apis, hasLength(1)); + expect(results.root.apis[0].methods, hasLength(1)); expect( results.root.apis[0].methods[0].swiftFunction, equals('subtractValue(_:by:)'), @@ -1138,7 +1140,7 @@ abstract class Api { }); test('custom swift invalid function signature', () { - const String code = ''' + const code = ''' @HostApi() abstract class Api { @SwiftFunction('subtractValue(_:by:error:)') @@ -1146,7 +1148,7 @@ abstract class Api { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 1); + expect(results.errors, hasLength(1)); expect(results.errors[0].lineNumber, 3); expect( results.errors[0].message, @@ -1155,7 +1157,7 @@ abstract class Api { }); test('custom swift function signature no parameters', () { - const String code = ''' + const code = ''' @HostApi() abstract class Api { @SwiftFunction('foobar()') @@ -1163,22 +1165,21 @@ abstract class Api { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 0); - expect(results.root.apis.length, 1); - expect(results.root.apis[0].methods.length, equals(1)); + expect(results.errors, isEmpty); + expect(results.root.apis, hasLength(1)); + expect(results.root.apis[0].methods, hasLength(1)); expect(results.root.apis[0].methods[0].swiftFunction, equals('foobar()')); }); test('dart test has copyright', () { - final Root root = Root(apis: [], classes: [], enums: []); - const PigeonOptions options = PigeonOptions( + final root = Root(apis: [], classes: [], enums: []); + const options = PigeonOptions( copyrightHeader: './copyright_header.txt', dartTestOut: 'stdout', dartOut: 'stdout', ); - final DartTestGeneratorAdapter dartTestGeneratorAdapter = - DartTestGeneratorAdapter(); - final StringBuffer buffer = StringBuffer(); + const dartTestGeneratorAdapter = DartTestGeneratorAdapter(); + final buffer = StringBuffer(); dartTestGeneratorAdapter.generate( buffer, InternalPigeonOptions.fromPigeonOptions(options), @@ -1189,7 +1190,7 @@ abstract class Api { }); test('only class reference is type argument for return value', () { - const String code = ''' + const code = ''' class Foo { int? foo; } @@ -1200,13 +1201,13 @@ abstract class Api { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 0); - expect(results.root.classes.length, 1); + expect(results.errors, isEmpty); + expect(results.root.classes, hasLength(1)); expect(results.root.classes[0].name, 'Foo'); }); test('only class reference is type argument for argument', () { - const String code = ''' + const code = ''' class Foo { int? foo; } @@ -1217,13 +1218,13 @@ abstract class Api { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 0); - expect(results.root.classes.length, 1); + expect(results.errors, isEmpty); + expect(results.root.classes, hasLength(1)); expect(results.root.classes[0].name, 'Foo'); }); test('recurse into type parameters', () { - const String code = ''' + const code = ''' class Foo { int? foo; List bars; @@ -1239,48 +1240,76 @@ abstract class Api { } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 0); - expect(results.root.classes.length, 2); + expect(results.errors, isEmpty); + expect(results.root.classes, hasLength(2)); expect( - results.root.classes - .where((Class element) => element.name == 'Foo') - .length, - 1, + results.root.classes.where((Class element) => element.name == 'Foo'), + hasLength(1), ); expect( - results.root.classes - .where((Class element) => element.name == 'Bar') - .length, - 1, + results.root.classes.where((Class element) => element.name == 'Bar'), + hasLength(1), ); }); test('undeclared class in argument type argument', () { - const String code = ''' + const code = ''' @HostApi() abstract class Api { void storeAll(List foos); } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 1); + expect(results.errors, hasLength(1)); expect(results.errors[0].lineNumber, 3); expect(results.errors[0].message, contains('Unknown type: Foo')); }); + test('function return type is missing', () { + const code = ''' +@HostApi() +abstract class Api { + storeAll(List foos); +} +'''; + final ParseResults results = parseSource(code); + expect(results.errors, hasLength(1)); + expect(results.errors[0].lineNumber, 3); + expect( + results.errors[0].message, + contains('Expected a named type for the return type of ("Api.storeAll")'), + ); + }); + + test('function return type is record type', () { + const code = ''' +@HostApi() +abstract class Api { + (int, int) storeAll(List foos); +} +'''; + final ParseResults results = parseSource(code); + expect(results.errors, hasLength(1)); + expect(results.errors[0].lineNumber, 3); + expect( + results.errors[0].message, + contains('Expected a named type for the return type of ("Api.storeAll")'), + ); + }); + test('Object type argument', () { - const String code = ''' + const code = ''' @HostApi() abstract class Api { void storeAll(List foos); } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 0); + expect(results.errors, isEmpty); }); test('Export unreferenced enums', () { - const String code = ''' + const code = ''' enum MessageKey { title, subtitle, @@ -1298,12 +1327,12 @@ abstract class HostApiBridge { } '''; final ParseResults results = parseSource(code); - expect(results.root.enums.length, 1); + expect(results.root.enums, hasLength(1)); expect(results.root.enums[0].name, 'MessageKey'); }); test('@ConfigurePigeon JavaOptions.copyrightHeader', () { - const String code = ''' + const code = ''' @ConfigurePigeon(InternalPigeonOptions( javaOptions: JavaOptions(copyrightHeader: ['A', 'Header']), )) @@ -1318,7 +1347,7 @@ class Message { }); test('@ConfigurePigeon DartOptions.copyrightHeader', () { - const String code = ''' + const code = ''' @ConfigurePigeon(PigeonOptions( dartOptions: DartOptions(copyrightHeader: ['A', 'Header']), )) @@ -1333,7 +1362,7 @@ class Message { }); test('@ConfigurePigeon ObjcOptions.copyrightHeader', () { - const String code = ''' + const code = ''' @ConfigurePigeon(PigeonOptions( objcOptions: ObjcOptions(copyrightHeader: ['A', 'Header']), )) @@ -1348,7 +1377,7 @@ class Message { }); test('@ConfigurePigeon ObjcOptions.headerIncludePath', () { - const String code = ''' + const code = ''' @ConfigurePigeon(PigeonOptions( objcOptions: ObjcOptions(headerIncludePath: 'Header.path'), )) @@ -1363,7 +1392,7 @@ class Message { }); test('@ConfigurePigeon CppOptions.headerIncludePath', () { - const String code = ''' + const code = ''' @ConfigurePigeon(PigeonOptions( cppOptions: CppOptions(headerIncludePath: 'Header.path'), )) @@ -1378,7 +1407,7 @@ class Message { }); test('return nullable', () { - const String code = ''' + const code = ''' @HostApi() abstract class Api { int? calc(); @@ -1386,19 +1415,19 @@ abstract class Api { '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 0); + expect(results.errors, isEmpty); expect(results.root.apis[0].methods[0].returnType.isNullable, isTrue); }); test('nullable parameters', () { - const String code = ''' + const code = ''' @HostApi() abstract class Api { void calc(int? value); } '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 0); + expect(results.errors, isEmpty); expect( results.root.apis[0].methods[0].parameters[0].type.isNullable, isTrue, @@ -1406,7 +1435,7 @@ abstract class Api { }); test('task queue specified', () { - const String code = ''' + const code = ''' @HostApi() abstract class Api { @TaskQueue(type: TaskQueueType.serialBackgroundThread) @@ -1415,7 +1444,7 @@ abstract class Api { '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 0); + expect(results.errors, isEmpty); expect( results.root.apis[0].methods[0].taskQueueType, equals(TaskQueueType.serialBackgroundThread), @@ -1423,7 +1452,7 @@ abstract class Api { }); test('task queue unspecified', () { - const String code = ''' + const code = ''' @HostApi() abstract class Api { int? calc(); @@ -1431,7 +1460,7 @@ abstract class Api { '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 0); + expect(results.errors, isEmpty); expect( results.root.apis[0].methods[0].taskQueueType, equals(TaskQueueType.serial), @@ -1439,7 +1468,7 @@ abstract class Api { }); test('unsupported task queue on FlutterApi', () { - const String code = ''' + const code = ''' @FlutterApi() abstract class Api { @TaskQueue(type: TaskQueueType.serialBackgroundThread) @@ -1448,7 +1477,7 @@ abstract class Api { '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 1); + expect(results.errors, hasLength(1)); expect( results.errors[0].message, contains('Unsupported TaskQueue specification'), @@ -1456,11 +1485,9 @@ abstract class Api { }); test('generator validation', () async { - final Completer completer = Completer(); + final completer = Completer(); withTempFile('foo.dart', (File input) async { - final _ValidatorGeneratorAdapter generator = _ValidatorGeneratorAdapter( - stdout, - ); + final generator = _ValidatorGeneratorAdapter(stdout); final int result = await Pigeon.run( ['--input', input.path], adapters: [generator], @@ -1473,11 +1500,9 @@ abstract class Api { }); test('generator validation skipped', () async { - final Completer completer = Completer(); + final completer = Completer(); withTempFile('foo.dart', (File input) async { - final _ValidatorGeneratorAdapter generator = _ValidatorGeneratorAdapter( - null, - ); + final generator = _ValidatorGeneratorAdapter(null); final int result = await Pigeon.run( ['--input', input.path, '--dart_out', 'foo.dart'], adapters: [generator], @@ -1490,11 +1515,9 @@ abstract class Api { }); test('run with PigeonOptions', () async { - final Completer completer = Completer(); + final completer = Completer(); withTempFile('foo.dart', (File input) async { - final _ValidatorGeneratorAdapter generator = _ValidatorGeneratorAdapter( - null, - ); + final generator = _ValidatorGeneratorAdapter(null); final int result = await Pigeon.runWithOptions( PigeonOptions(input: input.path, dartOut: 'foo.dart'), adapters: [generator], @@ -1507,7 +1530,7 @@ abstract class Api { }); test('unsupported non-positional parameters on FlutterApi', () { - const String code = ''' + const code = ''' @FlutterApi() abstract class Api { int? calc({int? anInt}); @@ -1515,7 +1538,7 @@ abstract class Api { '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 1); + expect(results.errors, hasLength(1)); expect( results.errors[0].message, contains('FlutterApi method parameters must be positional'), @@ -1523,7 +1546,7 @@ abstract class Api { }); test('unsupported optional parameters on FlutterApi', () { - const String code = ''' + const code = ''' @FlutterApi() abstract class Api { int? calc([int? anInt]); @@ -1531,7 +1554,7 @@ abstract class Api { '''; final ParseResults results = parseSource(code); - expect(results.errors.length, 1); + expect(results.errors, hasLength(1)); expect( results.errors[0].message, contains('FlutterApi method parameters must not be optional'), @@ -1539,7 +1562,7 @@ abstract class Api { }); test('simple parse ProxyApi', () { - const String code = ''' + const code = ''' @ProxyApi() abstract class MyClass { MyClass(); @@ -1549,14 +1572,14 @@ abstract class MyClass { } '''; final ParseResults parseResult = parseSource(code); - expect(parseResult.errors.length, equals(0)); + expect(parseResult.errors, isEmpty); final Root root = parseResult.root; - expect(root.apis.length, equals(1)); + expect(root.apis, hasLength(1)); - final AstProxyApi proxyApi = root.apis.single as AstProxyApi; + final proxyApi = root.apis.single as AstProxyApi; expect(proxyApi.name, equals('MyClass')); expect(proxyApi.constructors.single.name, equals('')); - expect(proxyApi.methods.length, equals(2)); + expect(proxyApi.methods, hasLength(2)); for (final Method method in proxyApi.methods) { if (method.location == ApiLocation.host) { @@ -1569,7 +1592,7 @@ abstract class MyClass { group('ProxyApi validation', () { test('error with using data class', () { - const String code = ''' + const code = ''' class DataClass { late int input; } @@ -1580,7 +1603,7 @@ abstract class MyClass { } '''; final ParseResults parseResult = parseSource(code); - expect(parseResult.errors.length, equals(1)); + expect(parseResult.errors, hasLength(1)); expect( parseResult.errors.single.message, contains('ProxyApis do not support data classes'), @@ -1588,7 +1611,7 @@ abstract class MyClass { }); test('super class must be proxy api', () { - const String code = ''' + const code = ''' class DataClass { late int input; } @@ -1607,7 +1630,7 @@ abstract class MyClass extends DataClass { }); test('interface must be proxy api', () { - const String code = ''' + const code = ''' class DataClass { late int input; } @@ -1626,7 +1649,7 @@ abstract class MyClass implements DataClass { }); test('unattached fields can not be inherited', () { - const String code = ''' + const code = ''' @ProxyApi() abstract class MyClass extends MyOtherClass { } @@ -1648,7 +1671,7 @@ abstract class MyOtherClass { test( 'api is not used as an attached field while having an unattached field', () { - const String code = ''' + const code = ''' @ProxyApi() abstract class MyClass { @attached @@ -1674,7 +1697,7 @@ abstract class MyOtherClass { test( 'api is not used as an attached field while having a required Flutter method', () { - const String code = ''' + const code = ''' @ProxyApi() abstract class MyClass { @attached @@ -1698,7 +1721,7 @@ abstract class MyOtherClass { ); test('interfaces can only have callback methods', () { - const String code = ''' + const code = ''' @ProxyApi() abstract class MyClass implements MyOtherClass { } @@ -1719,7 +1742,7 @@ abstract class MyOtherClass { }); test('attached fields must be a ProxyApi', () { - const String code = ''' + const code = ''' @ProxyApi() abstract class MyClass { @attached @@ -1735,7 +1758,7 @@ abstract class MyClass { }); test('attached fields must not be nullable', () { - const String code = ''' + const code = ''' @ProxyApi() abstract class MyClass { @attached @@ -1751,7 +1774,7 @@ abstract class MyClass { }); test('callback methods with non-null return types must be non-null', () { - const String code = ''' + const code = ''' @ProxyApi() abstract class MyClass { late String Function()? aCallbackMethod; @@ -1766,18 +1789,51 @@ abstract class MyClass { ), ); }); + + test('constructor parameters can share name of attached fields', () { + const code = ''' +@ProxyApi() +abstract class MyClass { + MyClass(int aField); + + @attached + late MyClass aField; +} +'''; + final ParseResults parseResult = parseSource(code); + expect(parseResult.errors, isEmpty); + }); + + test('constructor parameters can not share name of unattached fields', () { + const code = ''' +@ProxyApi() +abstract class MyClass { + MyClass(int aField); + + late MyClass? aField; +} +'''; + final ParseResults parseResult = parseSource(code); + expect(parseResult.errors, isNotEmpty); + expect( + parseResult.errors[0].message, + contains( + 'Parameter names must not share a name with a field or callback method in constructor "" in API: "MyClass"', + ), + ); + }); }); group('event channel validation', () { test('methods cannot contain parameters', () { - const String code = ''' + const code = ''' @EventChannelApi() abstract class EventChannelApi { int streamInts(int event); } '''; final ParseResults parseResult = parseSource(code); - expect(parseResult.errors.length, equals(1)); + expect(parseResult.errors, hasLength(1)); expect( parseResult.errors.single.message, contains( @@ -1789,7 +1845,7 @@ abstract class EventChannelApi { group('sealed inheritance validation', () { test('super class must be sealed', () { - const String code = ''' + const code = ''' class DataClass {} class ChildClass extends DataClass { ChildClass(this.input); @@ -1810,7 +1866,7 @@ abstract class events { }); test('super class must be sealed', () { - const String code = ''' + const code = ''' sealed class DataClass { DataClass(this.input); int input; diff --git a/packages/pigeon/test/pigeon_test.dart b/packages/pigeon/test/pigeon_test.dart index 564cdcedf7ce..8756fdcbdc7a 100644 --- a/packages/pigeon/test/pigeon_test.dart +++ b/packages/pigeon/test/pigeon_test.dart @@ -7,22 +7,22 @@ import 'package:test/test.dart'; void main() { test('Should be able to import JavaOptions', () async { - const JavaOptions javaOptions = JavaOptions(); + const javaOptions = JavaOptions(); expect(javaOptions, isNotNull); }); test('Should be able to import ObjcOptions', () async { - const ObjcOptions objcOptions = ObjcOptions(); + const objcOptions = ObjcOptions(); expect(objcOptions, isNotNull); }); test('Should be able to import SwiftOptions', () async { - const SwiftOptions swiftOptions = SwiftOptions(); + const swiftOptions = SwiftOptions(); expect(swiftOptions, isNotNull); }); test('Should be able to import KotlinOptions', () async { - const KotlinOptions kotlinOptions = KotlinOptions(); + const kotlinOptions = KotlinOptions(); expect(kotlinOptions, isNotNull); }); } diff --git a/packages/pigeon/test/swift/proxy_api_test.dart b/packages/pigeon/test/swift/proxy_api_test.dart index b35d1ba82927..ccf1df2f97e1 100644 --- a/packages/pigeon/test/swift/proxy_api_test.dart +++ b/packages/pigeon/test/swift/proxy_api_test.dart @@ -11,7 +11,7 @@ const String DEFAULT_PACKAGE_NAME = 'test_package'; void main() { group('ProxyApi', () { test('one api', () { - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -81,8 +81,8 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const generator = SwiftGenerator(); generator.generate( const InternalSwiftOptions( fileSpecificClassNameComponent: 'MyFile', @@ -92,7 +92,7 @@ void main() { sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); // import @@ -174,7 +174,7 @@ void main() { group('imports', () { test('add check if every class does not support iOS', () { - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -190,21 +190,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const generator = SwiftGenerator(); generator.generate( const InternalSwiftOptions(swiftOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('#if !os(iOS)\nimport MyImport\n#endif')); }); test('add check if every class does not support macOS', () { - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -220,21 +220,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const generator = SwiftGenerator(); generator.generate( const InternalSwiftOptions(swiftOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('#if !os(macOS)\nimport MyImport\n#endif')); }); test('add check if for multiple unsupported platforms', () { - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -251,15 +251,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const generator = SwiftGenerator(); generator.generate( const InternalSwiftOptions(swiftOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, @@ -268,7 +268,7 @@ void main() { }); test('do not add check if at least one class is supported', () { - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -291,15 +291,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const generator = SwiftGenerator(); generator.generate( const InternalSwiftOptions(swiftOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, isNot(contains('#if !os(iOS)\nimport MyImport'))); }); @@ -307,13 +307,13 @@ void main() { group('inheritance', () { test('extends', () { - final AstProxyApi api2 = AstProxyApi( + final api2 = AstProxyApi( name: 'Api2', constructors: [], fields: [], methods: [], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -331,26 +331,26 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const generator = SwiftGenerator(); generator.generate( const InternalSwiftOptions(swiftOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('var pigeonApiApi2: PigeonApiApi2')); }); test('implements', () { - final AstProxyApi api2 = AstProxyApi( + final api2 = AstProxyApi( name: 'Api2', constructors: [], fields: [], methods: [], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -370,32 +370,32 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const generator = SwiftGenerator(); generator.generate( const InternalSwiftOptions(swiftOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('var pigeonApiApi2: PigeonApiApi2')); }); test('implements 2 ProxyApis', () { - final AstProxyApi api2 = AstProxyApi( + final api2 = AstProxyApi( name: 'Api2', constructors: [], fields: [], methods: [], ); - final AstProxyApi api3 = AstProxyApi( + final api3 = AstProxyApi( name: 'Api3', constructors: [], fields: [], methods: [], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -421,15 +421,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const generator = SwiftGenerator(); generator.generate( const InternalSwiftOptions(swiftOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('var pigeonApiApi2: PigeonApiApi2')); expect(code, contains('var pigeonApiApi3: PigeonApiApi3')); }); @@ -437,7 +437,7 @@ void main() { group('Constructors', () { test('empty name and no params constructor', () { - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -451,15 +451,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const generator = SwiftGenerator(); generator.generate( const InternalSwiftOptions(swiftOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect(code, contains('class PigeonApiApi: PigeonApiProtocolApi ')); expect( @@ -483,7 +483,7 @@ void main() { }); test('named constructor', () { - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -500,15 +500,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const generator = SwiftGenerator(); generator.generate( const InternalSwiftOptions(swiftOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect( collapsedCode, @@ -525,11 +525,11 @@ void main() { }); test('multiple params constructor', () { - final Enum anEnum = Enum( + final anEnum = Enum( name: 'AnEnum', members: [EnumMember(name: 'one')], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -597,15 +597,15 @@ void main() { classes: [], enums: [anEnum], ); - final StringBuffer sink = StringBuffer(); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const generator = SwiftGenerator(); generator.generate( const InternalSwiftOptions(swiftOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect(code, contains('class PigeonApiApi: PigeonApiProtocolApi ')); expect( @@ -628,7 +628,7 @@ void main() { test( 'host platform constructor calls new instance error for required callbacks', () { - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -647,8 +647,8 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const generator = SwiftGenerator(); generator.generate( const InternalSwiftOptions( errorClassName: 'TestError', @@ -658,7 +658,7 @@ void main() { sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect( @@ -673,11 +673,11 @@ void main() { group('Fields', () { test('constructor with fields', () { - final Enum anEnum = Enum( + final anEnum = Enum( name: 'AnEnum', members: [EnumMember(name: 'one')], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -742,15 +742,15 @@ void main() { classes: [], enums: [anEnum], ); - final StringBuffer sink = StringBuffer(); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const generator = SwiftGenerator(); generator.generate( const InternalSwiftOptions(swiftOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect( collapsedCode, @@ -814,13 +814,13 @@ void main() { }); test('attached field', () { - final AstProxyApi api2 = AstProxyApi( + final api2 = AstProxyApi( name: 'Api2', constructors: [], fields: [], methods: [], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -843,15 +843,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const generator = SwiftGenerator(); generator.generate( const InternalSwiftOptions(swiftOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -867,13 +867,13 @@ void main() { }); test('static attached field', () { - final AstProxyApi api2 = AstProxyApi( + final api2 = AstProxyApi( name: 'Api2', constructors: [], fields: [], methods: [], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -897,15 +897,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const generator = SwiftGenerator(); generator.generate( const InternalSwiftOptions(swiftOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains(r'func aField(pigeonApi: PigeonApiApi) throws -> Api2'), @@ -921,11 +921,11 @@ void main() { group('Host methods', () { test('multiple params method', () { - final Enum anEnum = Enum( + final anEnum = Enum( name: 'AnEnum', members: [EnumMember(name: 'one')], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -995,15 +995,15 @@ void main() { classes: [], enums: [anEnum], ); - final StringBuffer sink = StringBuffer(); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const generator = SwiftGenerator(); generator.generate( const InternalSwiftOptions(swiftOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect( collapsedCode, @@ -1025,7 +1025,7 @@ void main() { }); test('static method', () { - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -1045,15 +1045,15 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const generator = SwiftGenerator(); generator.generate( const InternalSwiftOptions(swiftOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect( collapsedCode, @@ -1068,11 +1068,11 @@ void main() { group('Flutter methods', () { test('multiple params flutter method', () { - final Enum anEnum = Enum( + final anEnum = Enum( name: 'AnEnum', members: [EnumMember(name: 'one')], ); - final Root root = Root( + final root = Root( apis: [ AstProxyApi( name: 'Api', @@ -1136,15 +1136,15 @@ void main() { classes: [], enums: [anEnum], ); - final StringBuffer sink = StringBuffer(); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const generator = SwiftGenerator(); generator.generate( const InternalSwiftOptions(swiftOut: ''), root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); final String collapsedCode = _collapseNewlineAndIndentation(code); expect( collapsedCode, @@ -1185,7 +1185,7 @@ void main() { /// void method( int param1, int param2, ) /// ``` String _collapseNewlineAndIndentation(String string) { - final StringBuffer result = StringBuffer(); + final result = StringBuffer(); for (final String line in string.split('\n')) { result.write('${line.trimLeft()} '); } diff --git a/packages/pigeon/test/swift_generator_test.dart b/packages/pigeon/test/swift_generator_test.dart index d30cd8ae4ede..fa567e2b02c8 100644 --- a/packages/pigeon/test/swift_generator_test.dart +++ b/packages/pigeon/test/swift_generator_test.dart @@ -25,7 +25,7 @@ final Enum emptyEnum = Enum( void main() { test('gen one class', () { - final Class classDefinition = Class( + final classDefinition = Class( name: 'Foobar', fields: [ NamedType( @@ -34,23 +34,21 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [], classes: [classDefinition], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('struct Foobar')); expect(code, contains('var field1: Int64? = nil')); expect( @@ -62,30 +60,24 @@ void main() { }); test('gen one enum', () { - final Enum anEnum = Enum( + final anEnum = Enum( name: 'Foobar', members: [ EnumMember(name: 'one'), EnumMember(name: 'two'), ], ); - final Root root = Root( - apis: [], - classes: [], - enums: [anEnum], - ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final root = Root(apis: [], classes: [], enums: [anEnum]); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('enum Foobar: Int')); expect(code, contains(' case one = 0')); expect(code, contains(' case two = 1')); @@ -93,7 +85,7 @@ void main() { }); test('primitive enum host', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Bar', @@ -127,18 +119,16 @@ void main() { ), ], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('enum Foo: Int')); expect( code, @@ -152,7 +142,7 @@ void main() { }); test('gen one host api', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -201,18 +191,16 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('protocol Api')); expect(code, matches('func doSomething.*Input.*Output')); expect(code, contains('doSomethingChannel.setMessageHandler')); @@ -220,7 +208,7 @@ void main() { }); test('all the simple datatypes header', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -276,18 +264,16 @@ void main() { enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('var aBool: Bool? = nil')); expect(code, contains('var aInt: Int64? = nil')); expect(code, contains('var aDouble: Double? = nil')); @@ -299,12 +285,10 @@ void main() { }); test('gen pigeon error type', () { - final Root root = Root(apis: [], classes: [], enums: []); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final root = Root(apis: [], classes: [], enums: []); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, @@ -312,7 +296,7 @@ void main() { sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('class PigeonError: Error')); expect(code, contains('let code: String')); expect(code, contains('let message: String?')); @@ -324,7 +308,7 @@ void main() { }); test('gen one flutter api', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -373,18 +357,16 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('class Api')); expect( code, @@ -398,7 +380,7 @@ void main() { }); test('gen host void api', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -434,25 +416,23 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, isNot(matches('.*doSomething(.*) ->'))); expect(code, matches('doSomething(.*)')); expect(code, isNot(contains('if ('))); }); test('gen flutter void return api', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -488,18 +468,16 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains('completion: @escaping (Result) -> Void'), @@ -509,7 +487,7 @@ void main() { }); test('gen host void argument api', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -540,18 +518,16 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('func doSomething() throws -> Output')); expect(code, contains('let result = try api.doSomething()')); expect(code, contains('reply(wrapResult(result))')); @@ -559,7 +535,7 @@ void main() { }); test('gen flutter void argument api', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -590,18 +566,16 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -613,7 +587,7 @@ void main() { }); test('gen list', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -628,25 +602,23 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('struct Foobar')); expect(code, contains('var field1: [Any?]? = nil')); expect(code, isNot(contains('if ('))); }); test('gen map', () { - final Root root = Root( + final root = Root( apis: [], classes: [ Class( @@ -661,25 +633,23 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('struct Foobar')); expect(code, contains('var field1: [AnyHashable?: Any?]? = nil')); expect(code, isNot(contains('if ('))); }); test('gen nested', () { - final Class classDefinition = Class( + final classDefinition = Class( name: 'Outer', fields: [ NamedType( @@ -692,7 +662,7 @@ void main() { ), ], ); - final Class nestedClass = Class( + final nestedClass = Class( name: 'Nested', fields: [ NamedType( @@ -701,23 +671,21 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [], classes: [classDefinition, nestedClass], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('struct Outer')); expect(code, contains('struct Nested')); expect(code, contains('var nested: Nested? = nil')); @@ -736,7 +704,7 @@ void main() { }); test('gen one async Host Api', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -786,18 +754,16 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('protocol Api')); expect(code, contains('api.doSomething(arg: argArg) { result in')); expect(code, contains('reply(wrapResult(res))')); @@ -805,7 +771,7 @@ void main() { }); test('gen one async Flutter Api', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -855,32 +821,30 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('class Api')); expect(code, matches('func doSomething.*Input.*completion.*Output.*Void')); expect(code, isNot(contains('if ('))); }); test('gen one enum class', () { - final Enum anEnum = Enum( + final anEnum = Enum( name: 'Enum1', members: [ EnumMember(name: 'one'), EnumMember(name: 'two'), ], ); - final Class classDefinition = Class( + final classDefinition = Class( name: 'EnumClass', fields: [ NamedType( @@ -893,23 +857,21 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [], classes: [classDefinition], enums: [anEnum], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('enum Enum1: Int')); expect(code, contains('case one = 0')); expect(code, contains('case two = 1')); @@ -917,27 +879,27 @@ void main() { }); test('header', () { - final Root root = Root(apis: [], classes: [], enums: []); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( + final root = Root(apis: [], classes: [], enums: []); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions( swiftOut: '', copyrightHeader: ['hello world', ''], ); - const SwiftGenerator generator = SwiftGenerator(); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, startsWith('// hello world')); // There should be no trailing whitespace on generated comments. expect(code, isNot(matches(RegExp(r'^//.* $', multiLine: true)))); }); test('generics - list', () { - final Class classDefinition = Class( + final classDefinition = Class( name: 'Foobar', fields: [ NamedType( @@ -952,29 +914,27 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [], classes: [classDefinition], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('struct Foobar')); expect(code, contains('var field1: [Int64?]')); }); test('generics - maps', () { - final Class classDefinition = Class( + final classDefinition = Class( name: 'Foobar', fields: [ NamedType( @@ -990,29 +950,27 @@ void main() { ), ], ); - final Root root = Root( + final root = Root( apis: [], classes: [classDefinition], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('struct Foobar')); expect(code, contains('var field1: [String?: String?]')); }); test('host generics argument', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1040,23 +998,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('func doit(arg: [Int64?]')); }); test('flutter generics argument', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1084,23 +1040,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('func doit(arg argArg: [Int64?]')); }); test('host generics return', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1123,25 +1077,23 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('func doit() throws -> [Int64?]')); expect(code, contains('let result = try api.doit()')); expect(code, contains('reply(wrapResult(result))')); }); test('flutter generics return', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1164,18 +1116,16 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -1187,7 +1137,7 @@ void main() { }); test('host multiple args', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1222,18 +1172,16 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('func add(x: Int64, y: Int64) throws -> Int64')); expect(code, contains('let args = message as! [Any?]')); expect(code, contains('let xArg = args[0] as! Int64')); @@ -1243,7 +1191,7 @@ void main() { }); test('flutter multiple args', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1278,18 +1226,16 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('let channel = FlutterBasicMessageChannel')); expect(code, contains('let result = listResponse[0] as! Int64')); expect(code, contains('completion(.success(result))')); @@ -1306,7 +1252,7 @@ void main() { }); test('return nullable host', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1326,23 +1272,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('func doit() throws -> Int64?')); }); test('return nullable host async', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1363,18 +1307,16 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -1384,7 +1326,7 @@ void main() { }); test('nullable argument host', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1409,23 +1351,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('let fooArg: Int64? = nilOrValue(args[0])')); }); test('nullable argument flutter', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1450,18 +1390,16 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -1471,7 +1409,7 @@ void main() { }); test('nonnull fields', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1510,23 +1448,21 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('var input: String\n')); }); test('transfers documentation comments', () { - final List comments = [ + final comments = [ ' api comment', ' api method comment', ' class comment', @@ -1534,12 +1470,12 @@ void main() { ' enum comment', ' enum member comment', ]; - int count = 0; + var count = 0; - final List unspacedComments = ['////////']; - int unspacedCount = 0; + final unspacedComments = ['////////']; + var unspacedCount = 0; - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'api', @@ -1600,26 +1536,24 @@ void main() { ), ], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); - for (final String comment in comments) { + final code = sink.toString(); + for (final comment in comments) { expect(code, contains('///$comment')); } expect(code, contains('/// ///')); }); test('creates custom codecs', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1669,23 +1603,21 @@ void main() { ], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains(': FlutterStandardReader ')); }); test('swift function signature', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1718,23 +1650,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('func setValue(_ value: Int64, for key: String)')); }); test('swift function signature with same name argument', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1760,23 +1690,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('func removeValue(key: String)')); }); test('swift function signature with no arguments', () { - final Root root = Root( + final root = Root( apis: [ AstHostApi( name: 'Api', @@ -1794,23 +1722,21 @@ void main() { classes: [], enums: [], ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions swiftOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( swiftOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect(code, contains('func removeAll()')); }); test('connection error contains channel name', () { - final Root root = Root( + final root = Root( apis: [ AstFlutterApi( name: 'Api', @@ -1836,18 +1762,16 @@ void main() { enums: [], containsFlutterApi: true, ); - final StringBuffer sink = StringBuffer(); - const InternalSwiftOptions kotlinOptions = InternalSwiftOptions( - swiftOut: '', - ); - const SwiftGenerator generator = SwiftGenerator(); + final sink = StringBuffer(); + const kotlinOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); generator.generate( kotlinOptions, root, sink, dartPackageName: DEFAULT_PACKAGE_NAME, ); - final String code = sink.toString(); + final code = sink.toString(); expect( code, contains( @@ -1861,4 +1785,72 @@ void main() { ), ); }); + + test('data class equality', () { + final classDefinition = Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'int', isNullable: true), + name: 'field1', + ), + ], + ); + final root = Root( + apis: [], + classes: [classDefinition], + enums: [], + ); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); + generator.generate( + swiftOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final code = sink.toString(); + expect( + code, + contains('static func == (lhs: Foobar, rhs: Foobar) -> Bool {'), + ); + expect(code, contains('func hash(into hasher: inout Hasher) {')); + }); + + test('data class equality multi-field', () { + final classDefinition = Class( + name: 'Foobar', + fields: [ + NamedType( + type: const TypeDeclaration(baseName: 'int', isNullable: true), + name: 'field1', + ), + NamedType( + type: const TypeDeclaration(baseName: 'String', isNullable: true), + name: 'field2', + ), + ], + ); + final root = Root( + apis: [], + classes: [classDefinition], + enums: [], + ); + final sink = StringBuffer(); + const swiftOptions = InternalSwiftOptions(swiftOut: ''); + const generator = SwiftGenerator(); + generator.generate( + swiftOptions, + root, + sink, + dartPackageName: DEFAULT_PACKAGE_NAME, + ); + final code = sink.toString(); + expect( + code, + contains('static func == (lhs: Foobar, rhs: Foobar) -> Bool {'), + ); + expect(code, contains('func hash(into hasher: inout Hasher) {')); + }); } diff --git a/packages/pigeon/test/version_test.dart b/packages/pigeon/test/version_test.dart index 766c77da7674..53cb80b35e67 100644 --- a/packages/pigeon/test/version_test.dart +++ b/packages/pigeon/test/version_test.dart @@ -9,9 +9,9 @@ import 'package:test/test.dart'; void main() { test('pigeon version matches pubspec', () { - final String pubspecPath = '${Directory.current.path}/pubspec.yaml'; + final pubspecPath = '${Directory.current.path}/pubspec.yaml'; final String pubspec = File(pubspecPath).readAsStringSync(); - final RegExp regex = RegExp(r'version:\s*(.*?) #'); + final regex = RegExp(r'version:\s*(.*?) #'); final RegExpMatch? match = regex.firstMatch(pubspec); expect(match, isNotNull); expect( diff --git a/packages/pigeon/tool/generate.dart b/packages/pigeon/tool/generate.dart index b32381eb09b1..ed9e2bde1117 100644 --- a/packages/pigeon/tool/generate.dart +++ b/packages/pigeon/tool/generate.dart @@ -28,7 +28,7 @@ const String _overflowFiller = 'overflow'; const List _fileGroups = [_test, _example]; Future main(List args) async { - final ArgParser parser = ArgParser() + final parser = ArgParser() ..addFlag( _formatFlag, abbr: 'f', diff --git a/packages/pigeon/tool/run_tests.dart b/packages/pigeon/tool/run_tests.dart index b0885d01b59c..6f84cdc234b6 100644 --- a/packages/pigeon/tool/run_tests.dart +++ b/packages/pigeon/tool/run_tests.dart @@ -28,7 +28,7 @@ void _validateTestCoverage(List> shards) { if (missing.isNotEmpty) { print('The following test suites are not being run on any host:'); - for (final String suite in missing) { + for (final suite in missing) { print(' $suite'); } exit(1); @@ -185,7 +185,7 @@ Future> _modifiedFiles({ Future main(List args) async { // Run most tests on Linux, since Linux tends to be the easiest and cheapest. - const List linuxHostTests = [ + const linuxHostTests = [ commandLineTests, androidJavaUnitTests, androidJavaLint, @@ -196,7 +196,7 @@ Future main(List args) async { linuxUnitTests, linuxIntegrationTests, ]; - const List macOSHostTests = [ + const macOSHostTests = [ iOSObjCUnitTests, // Currently these are testing exactly the same thing as // macOS*IntegrationTests, so we don't need to run both by default. This @@ -210,10 +210,7 @@ Future main(List args) async { macOSSwiftIntegrationTests, ]; // Run Windows tests on Windows, since that's the only place they can run. - const List windowsHostTests = [ - windowsUnitTests, - windowsIntegrationTests, - ]; + const windowsHostTests = [windowsUnitTests, windowsIntegrationTests]; _validateTestCoverage(>[ linuxHostTests, diff --git a/packages/pigeon/tool/shared/flutter_utils.dart b/packages/pigeon/tool/shared/flutter_utils.dart index 97f6abe3652a..c6e3ed9f5347 100644 --- a/packages/pigeon/tool/shared/flutter_utils.dart +++ b/packages/pigeon/tool/shared/flutter_utils.dart @@ -18,7 +18,7 @@ Future getDeviceForPlatform(String platform) async { return null; } - String output = result.stdout as String; + var output = result.stdout as String; // --machine doesn't currently prevent the tool from printing banners; // see https://github.com/flutter/flutter/issues/86055. This workaround // can be removed once that is fixed. @@ -26,11 +26,11 @@ Future getDeviceForPlatform(String platform) async { final List> devices = (jsonDecode(output) as List).cast>(); - for (final Map deviceInfo in devices) { + for (final deviceInfo in devices) { final String targetPlatform = (deviceInfo['targetPlatform'] as String?) ?? ''; if (targetPlatform.startsWith(platform)) { - final String? deviceId = deviceInfo['id'] as String?; + final deviceId = deviceInfo['id'] as String?; if (deviceId != null) { return deviceId; } diff --git a/packages/pigeon/tool/shared/generation.dart b/packages/pigeon/tool/shared/generation.dart index 48ee3daf16a7..c71a7401dc1b 100644 --- a/packages/pigeon/tool/shared/generation.dart +++ b/packages/pigeon/tool/shared/generation.dart @@ -54,14 +54,12 @@ String _snakeToPascalCase(String snake) { // TODO(stuartmorgan): Remove the need for this when addressing // https://github.com/flutter/flutter/issues/115168. String _javaFilenameForName(String inputName) { - const Map specialCases = { - 'message': 'MessagePigeon', - }; + const specialCases = {'message': 'MessagePigeon'}; return specialCases[inputName] ?? _snakeToPascalCase(inputName); } Future generateExamplePigeons() async { - int success = 0; + var success = 0; success = await runPigeon( input: './example/app/pigeons/messages.dart', basePath: './example/app', @@ -81,7 +79,7 @@ Future generateTestPigeons({ }) async { // TODO(stuartmorgan): Make this dynamic rather than hard-coded. Or eliminate // it entirely; see https://github.com/flutter/flutter/issues/115169. - const Set inputs = { + const inputs = { 'core_tests', 'enum', 'event_channel_tests', @@ -96,8 +94,8 @@ Future generateTestPigeons({ 'proxy_api_tests', }; - const String testPluginName = 'test_plugin'; - const String alternateTestPluginName = 'alternate_language_test_plugin'; + const testPluginName = 'test_plugin'; + const alternateTestPluginName = 'alternate_language_test_plugin'; final String outputBase = p.join(baseDir, 'platform_tests', testPluginName); final String alternateOutputBase = p.join( baseDir, @@ -110,7 +108,7 @@ Future generateTestPigeons({ 'shared_test_plugin_code', ); - for (final String input in inputs) { + for (final input in inputs) { final String pascalCaseName = _snakeToPascalCase(input); final Set skipLanguages = _unsupportedFiles[input] ?? {}; @@ -118,7 +116,7 @@ Future generateTestPigeons({ final bool kotlinErrorClassGenerationTestFiles = input == 'core_tests' || input == 'primitive'; - final String kotlinErrorName = kotlinErrorClassGenerationTestFiles + final kotlinErrorName = kotlinErrorClassGenerationTestFiles ? 'FlutterError' : '${pascalCaseName}Error'; @@ -174,9 +172,9 @@ Future generateTestPigeons({ } // Generate the alternate language test plugin output. - final String objcBase = + final objcBase = '$alternateOutputBase/darwin/$alternateTestPluginName/Sources/$alternateTestPluginName/'; - final String objcBaseRelativeHeaderPath = + final objcBaseRelativeHeaderPath = 'include/$alternateTestPluginName/$pascalCaseName.gen.h'; generateCode = await runPigeon( input: './pigeons/$input.dart', @@ -210,6 +208,21 @@ Future generateTestPigeons({ return generateCode; } } + + // Test case for useGeneratedAnnotation feature with core_tests + final String corePascalCaseName = _snakeToPascalCase('core_tests'); + final int generateCodeWithAnnotation = await runPigeon( + input: './pigeons/core_tests.dart', + kotlinOut: + '$outputBase/android/src/main/kotlin/com/example/test_plugin/annotation/${corePascalCaseName}WithAnnotation.gen.kt', + kotlinPackage: 'com.example.test_plugin.annotation', + kotlinErrorClassName: 'FlutterError', + kotlinUseGeneratedAnnotation: true, + ); + if (generateCodeWithAnnotation != 0) { + return generateCodeWithAnnotation; + } + return 0; } @@ -219,6 +232,7 @@ Future runPigeon({ String? kotlinPackage, String? kotlinErrorClassName, bool kotlinIncludeErrorClass = true, + bool kotlinUseGeneratedAnnotation = false, bool swiftIncludeErrorClass = true, String? swiftOut, String? swiftErrorClassName, @@ -259,15 +273,14 @@ Future runPigeon({ // parse results in advance when overflow is included to avoid exposing as public option final ParseResults parseResults = Pigeon().parseFile(input); if (injectOverflowTypes) { - final List addedEnums = List.generate( - totalCustomCodecKeysAllowed - 1, - (final int tag) { - return Enum( - name: 'FillerEnum$tag', - members: [EnumMember(name: 'FillerMember$tag')], - ); - }, - ); + final addedEnums = List.generate(totalCustomCodecKeysAllowed - 1, ( + final int tag, + ) { + return Enum( + name: 'FillerEnum$tag', + members: [EnumMember(name: 'FillerMember$tag')], + ); + }); addedEnums.addAll(parseResults.root.enums); parseResults.root.enums = addedEnums; } @@ -278,7 +291,7 @@ Future runPigeon({ copyrightHeader: copyrightHeader, dartOut: dartOut, dartTestOut: dartTestOut, - dartOptions: const DartOptions(), + dartOptions: const DartOptions(ignoreLints: false), cppHeaderOut: cppHeaderOut, cppSourceOut: cppSourceOut, cppOptions: CppOptions(namespace: cppNamespace), @@ -294,6 +307,7 @@ Future runPigeon({ package: kotlinPackage, errorClassName: kotlinErrorClassName, includeErrorClass: kotlinIncludeErrorClass, + useGeneratedAnnotation: kotlinUseGeneratedAnnotation, ), objcHeaderOut: objcHeaderOut, objcSourceOut: objcSourceOut, @@ -334,7 +348,7 @@ Future formatAllFiles({ GeneratorLanguage.swift, }, }) { - final String dartCommand = Platform.isWindows ? 'dart.exe' : 'dart'; + final dartCommand = Platform.isWindows ? 'dart.exe' : 'dart'; return runProcess( dartCommand, [ diff --git a/packages/pigeon/tool/shared/process_utils.dart b/packages/pigeon/tool/shared/process_utils.dart index 2055ecd4fec5..e795f00b5d0c 100644 --- a/packages/pigeon/tool/shared/process_utils.dart +++ b/packages/pigeon/tool/shared/process_utils.dart @@ -25,8 +25,8 @@ Future runProcess( return process.exitCode; } - final List stdoutBuffer = []; - final List stderrBuffer = []; + final stdoutBuffer = []; + final stderrBuffer = []; final Future stdoutFuture = process.stdout.forEach(stdoutBuffer.addAll); final Future stderrFuture = process.stderr.forEach(stderrBuffer.addAll); final int exitCode = await process.exitCode; diff --git a/packages/pigeon/tool/shared/test_runner.dart b/packages/pigeon/tool/shared/test_runner.dart index 055f0b700a6a..810e4746cb17 100644 --- a/packages/pigeon/tool/shared/test_runner.dart +++ b/packages/pigeon/tool/shared/test_runner.dart @@ -88,7 +88,7 @@ Future _runFormat(String baseDir, {required bool ciMode}) async { } Future _runTests(List testsToRun, {required bool ciMode}) async { - for (final String test in testsToRun) { + for (final test in testsToRun) { final TestInfo? info = testSuites[test]; if (info != null) { _printHeading('Running $test', ciMode: ciMode); @@ -107,9 +107,9 @@ Future _runTests(List testsToRun, {required bool ciMode}) async { } void _printHeading(String heading, {required bool ciMode}) { - String timestamp = ''; + var timestamp = ''; if (ciMode) { - final DateTime now = DateTime.now(); + final now = DateTime.now(); timestamp = ' [start time ${now.hour}:${now.minute}:${now.second}]'; } print('##############################'); diff --git a/packages/pigeon/tool/shared/test_suites.dart b/packages/pigeon/tool/shared/test_suites.dart index c00db8547412..fe86925792aa 100644 --- a/packages/pigeon/tool/shared/test_suites.dart +++ b/packages/pigeon/tool/shared/test_suites.dart @@ -171,9 +171,9 @@ Future _runAndroidKotlinLint({bool ciMode = false}) async { } Future _runAndroidUnitTests(String testPluginPath) async { - final String examplePath = './$testPluginPath/example'; - final String androidProjectPath = '$examplePath/android'; - final File gradleFile = File(p.join(androidProjectPath, 'gradlew')); + final examplePath = './$testPluginPath/example'; + final androidProjectPath = '$examplePath/android'; + final gradleFile = File(p.join(androidProjectPath, 'gradlew')); if (!gradleFile.existsSync()) { final int compileCode = await runFlutterBuild(examplePath, 'apk'); if (compileCode != 0) { @@ -188,9 +188,9 @@ Future _runAndroidLint({ required String testPluginName, required String testPluginPath, }) async { - final String examplePath = './$testPluginPath/example'; - final String androidProjectPath = '$examplePath/android'; - final File gradleFile = File(p.join(androidProjectPath, 'gradlew')); + final examplePath = './$testPluginPath/example'; + final androidProjectPath = '$examplePath/android'; + final gradleFile = File(p.join(androidProjectPath, 'gradlew')); if (!gradleFile.existsSync()) { final int compileCode = await runFlutterBuild( examplePath, @@ -222,7 +222,7 @@ Future _runMobileIntegrationTests( return _noDeviceAvailableExitCode; } - final String examplePath = './$testPluginPath/example'; + final examplePath = './$testPluginPath/example'; return runFlutterCommand(examplePath, 'test', [ _integrationTestFileRelativePath, '-d', @@ -244,8 +244,8 @@ Future _runDartUnitTests({bool ciMode = false}) async { } Future _analyzeFlutterUnitTests(String flutterUnitTestsPath) async { - final String messagePath = '$flutterUnitTestsPath/lib/message.gen.dart'; - final String messageTestPath = '$flutterUnitTestsPath/test/message_test.dart'; + final messagePath = '$flutterUnitTestsPath/lib/message.gen.dart'; + final messageTestPath = '$flutterUnitTestsPath/test/message_test.dart'; final int generateTestCode = await runPigeon( input: 'pigeons/message.dart', dartOut: messagePath, @@ -271,7 +271,7 @@ Future _analyzeFlutterUnitTests(String flutterUnitTestsPath) async { } Future _runFlutterUnitTests({bool ciMode = false}) async { - const String flutterUnitTestsPath = 'platform_tests/shared_test_plugin_code'; + const flutterUnitTestsPath = 'platform_tests/shared_test_plugin_code'; final int analyzeCode = await _analyzeFlutterUnitTests(flutterUnitTestsPath); if (analyzeCode != 0) { return analyzeCode; @@ -303,8 +303,7 @@ Future _runIOSObjCIntegrationTests({bool ciMode = false}) async { return _noDeviceAvailableExitCode; } - const String examplePath = - './$_alternateLanguageTestPluginRelativePath/example'; + const examplePath = './$_alternateLanguageTestPluginRelativePath/example'; return runFlutterCommand(examplePath, 'test', [ _integrationTestFileRelativePath, '-d', @@ -313,8 +312,7 @@ Future _runIOSObjCIntegrationTests({bool ciMode = false}) async { } Future _runMacOSObjCIntegrationTests({bool ciMode = false}) async { - const String examplePath = - './$_alternateLanguageTestPluginRelativePath/example'; + const examplePath = './$_alternateLanguageTestPluginRelativePath/example'; return runFlutterCommand(examplePath, 'test', [ _integrationTestFileRelativePath, '-d', @@ -323,7 +321,7 @@ Future _runMacOSObjCIntegrationTests({bool ciMode = false}) async { } Future _runMacOSSwiftUnitTests({bool ciMode = false}) async { - const String examplePath = './$_testPluginRelativePath/example'; + const examplePath = './$_testPluginRelativePath/example'; final int compileCode = await runFlutterBuild(examplePath, 'macos'); if (compileCode != 0) { return compileCode; @@ -336,7 +334,7 @@ Future _runMacOSSwiftUnitTests({bool ciMode = false}) async { } Future _runMacOSSwiftIntegrationTests({bool ciMode = false}) async { - const String examplePath = './$_testPluginRelativePath/example'; + const examplePath = './$_testPluginRelativePath/example'; return runFlutterCommand(examplePath, 'test', [ _integrationTestFileRelativePath, '-d', @@ -349,7 +347,7 @@ Future _runIOSSwiftUnitTests({bool ciMode = false}) async { } Future _runIOSPluginUnitTests(String testPluginPath) async { - final String examplePath = './$testPluginPath/example'; + final examplePath = './$testPluginPath/example'; final int compileCode = await runFlutterBuild( examplePath, 'ios', @@ -359,10 +357,10 @@ Future _runIOSPluginUnitTests(String testPluginPath) async { return compileCode; } - const String deviceName = 'Pigeon-Test-iPhone'; - const String deviceType = 'com.apple.CoreSimulator.SimDeviceType.iPhone-14'; - const String deviceRuntime = 'com.apple.CoreSimulator.SimRuntime.iOS-18-2'; - const String deviceOS = '18.2'; + const deviceName = 'Pigeon-Test-iPhone'; + const deviceType = 'com.apple.CoreSimulator.SimDeviceType.iPhone-14'; + const deviceRuntime = 'com.apple.CoreSimulator.SimRuntime.iOS-18-2'; + const deviceOS = '18.2'; await _createSimulator(deviceName, deviceType, deviceRuntime); return runXcodeBuild( '$examplePath/ios', @@ -380,7 +378,7 @@ Future _createSimulator( // Delete any existing simulators with the same name until it fails. It will // fail once there are no simulators with the name. Having more than one may // cause issues when builds target the device. - int deleteResult = 0; + var deleteResult = 0; while (deleteResult == 0) { deleteResult = await _deleteSimulator(deviceName); } @@ -405,18 +403,17 @@ Future _runIOSSwiftIntegrationTests({bool ciMode = false}) async { } Future _runLinuxUnitTests({bool ciMode = false}) async { - const String examplePath = './$_testPluginRelativePath/example'; + const examplePath = './$_testPluginRelativePath/example'; final int compileCode = await runFlutterBuild(examplePath, 'linux'); if (compileCode != 0) { return compileCode; } - const String buildDirBase = '$examplePath/build/linux'; - const String buildRelativeBinaryPath = - 'debug/plugins/test_plugin/test_plugin_test'; - const String arm64Path = '$buildDirBase/arm64/$buildRelativeBinaryPath'; - const String x64Path = '$buildDirBase/x64/$buildRelativeBinaryPath'; - final String testBinary = File(arm64Path).existsSync() ? arm64Path : x64Path; + const buildDirBase = '$examplePath/build/linux'; + const buildRelativeBinaryPath = 'debug/plugins/test_plugin/test_plugin_test'; + const arm64Path = '$buildDirBase/arm64/$buildRelativeBinaryPath'; + const x64Path = '$buildDirBase/x64/$buildRelativeBinaryPath'; + final testBinary = File(arm64Path).existsSync() ? arm64Path : x64Path; if (ciMode) { // To avoid having all custom tests in the repo run under xvfb, xvfb-run is // done here rather than at the CI config level. Ideally, Pigeon tests @@ -429,7 +426,7 @@ Future _runLinuxUnitTests({bool ciMode = false}) async { } Future _runLinuxIntegrationTests({bool ciMode = false}) async { - const String examplePath = './$_testPluginRelativePath/example'; + const examplePath = './$_testPluginRelativePath/example'; return runFlutterCommand( examplePath, 'test', @@ -443,7 +440,7 @@ Future _runLinuxIntegrationTests({bool ciMode = false}) async { } Future _runWindowsUnitTests({bool ciMode = false}) async { - const String examplePath = './$_testPluginRelativePath/example'; + const examplePath = './$_testPluginRelativePath/example'; final int compileCode = await runFlutterBuild(examplePath, 'windows'); if (compileCode != 0) { return compileCode; @@ -458,11 +455,11 @@ Future _runWindowsUnitTests({bool ciMode = false}) async { // support a version of Flutter without // https://github.com/flutter/flutter/issues/129807, and just construct the // version of the path with the current architecture. - const String buildDirBase = '$examplePath/build/windows'; - const String buildRelativeBinaryPath = + const buildDirBase = '$examplePath/build/windows'; + const buildRelativeBinaryPath = 'plugins/test_plugin/Debug/test_plugin_test.exe'; - const String arm64Path = '$buildDirBase/arm64/$buildRelativeBinaryPath'; - const String x64Path = '$buildDirBase/x64/$buildRelativeBinaryPath'; + const arm64Path = '$buildDirBase/arm64/$buildRelativeBinaryPath'; + const x64Path = '$buildDirBase/x64/$buildRelativeBinaryPath'; if (File(arm64Path).existsSync()) { return runProcess(arm64Path, []); } else { @@ -471,7 +468,7 @@ Future _runWindowsUnitTests({bool ciMode = false}) async { } Future _runWindowsIntegrationTests({bool ciMode = false}) async { - const String examplePath = './$_testPluginRelativePath/example'; + const examplePath = './$_testPluginRelativePath/example'; return runFlutterCommand(examplePath, 'test', [ _integrationTestFileRelativePath, '-d', @@ -482,7 +479,7 @@ Future _runWindowsIntegrationTests({bool ciMode = false}) async { Future _runCommandLineTests({bool ciMode = false}) async { final Directory tempDir = Directory.systemTemp.createTempSync('pigeon'); final String tempOutput = p.join(tempDir.path, 'pigeon_output'); - const String pigeonScript = 'bin/pigeon.dart'; + const pigeonScript = 'bin/pigeon.dart'; final String snapshot = p.join(tempDir.path, 'pigeon.dart.dill'); // Precompile to make the repeated calls faster. @@ -496,7 +493,7 @@ Future _runCommandLineTests({bool ciMode = false}) async { return 1; } - final List> testArguments = >[ + final testArguments = >[ // Test with no arguments. [], // Test dartOut in ConfigurePigeon overrides output. @@ -513,8 +510,8 @@ Future _runCommandLineTests({bool ciMode = false}) async { ], ]; - int exitCode = 0; - for (final List arguments in testArguments) { + var exitCode = 0; + for (final arguments in testArguments) { print('Testing dart $pigeonScript ${arguments.join(', ')}'); exitCode = await runProcess( 'dart', diff --git a/packages/pigeon/tool/test.dart b/packages/pigeon/tool/test.dart index 5754778c1914..926205cefe60 100644 --- a/packages/pigeon/tool/test.dart +++ b/packages/pigeon/tool/test.dart @@ -26,7 +26,7 @@ const String _format = 'format'; const String _overflow = 'overflow'; Future main(List args) async { - final ArgParser parser = ArgParser() + final parser = ArgParser() ..addMultiOption(_testFlag, abbr: 't', help: 'Only run specified tests.') ..addFlag( _noGen, @@ -59,7 +59,7 @@ Future main(List args) async { ); final ArgResults argResults = parser.parse(args); - List testsToRun = []; + var testsToRun = []; if (argResults.wasParsed(_listFlag)) { print('available tests:'); @@ -84,12 +84,12 @@ ${parser.usage}'''); // If no tests are provided, run everything that is supported on the current // platform. if (testsToRun.isEmpty) { - const List dartTests = [ + const dartTests = [ dartUnitTests, flutterUnitTests, commandLineTests, ]; - const List androidTests = [ + const androidTests = [ androidJavaUnitTests, androidKotlinUnitTests, androidJavaIntegrationTests, @@ -97,25 +97,19 @@ ${parser.usage}'''); androidJavaLint, androidKotlinLint, ]; - const List iOSTests = [ + const iOSTests = [ iOSObjCUnitTests, iOSObjCIntegrationTests, iOSSwiftUnitTests, iOSSwiftIntegrationTests, ]; - const List linuxTests = [ - linuxUnitTests, - linuxIntegrationTests, - ]; - const List macOSTests = [ + const linuxTests = [linuxUnitTests, linuxIntegrationTests]; + const macOSTests = [ macOSObjCIntegrationTests, macOSSwiftUnitTests, macOSSwiftIntegrationTests, ]; - const List windowsTests = [ - windowsUnitTests, - windowsIntegrationTests, - ]; + const windowsTests = [windowsUnitTests, windowsIntegrationTests]; if (Platform.isMacOS) { testsToRun = [ diff --git a/packages/plugin_platform_interface/CHANGELOG.md b/packages/plugin_platform_interface/CHANGELOG.md index d4f0629c9661..193008d197f2 100644 --- a/packages/plugin_platform_interface/CHANGELOG.md +++ b/packages/plugin_platform_interface/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. ## 2.1.8 diff --git a/packages/plugin_platform_interface/lib/plugin_platform_interface.dart b/packages/plugin_platform_interface/lib/plugin_platform_interface.dart index d7c0f6b0915e..2a40957e252a 100644 --- a/packages/plugin_platform_interface/lib/plugin_platform_interface.dart +++ b/packages/plugin_platform_interface/lib/plugin_platform_interface.dart @@ -86,7 +86,7 @@ abstract class PlatformInterface { required bool preventConstObject, }) { if (instance is MockPlatformInterfaceMixin) { - bool assertionsEnabled = false; + var assertionsEnabled = false; assert(() { assertionsEnabled = true; return true; diff --git a/packages/plugin_platform_interface/pubspec.yaml b/packages/plugin_platform_interface/pubspec.yaml index d94551ea3842..fa38a362bf84 100644 --- a/packages/plugin_platform_interface/pubspec.yaml +++ b/packages/plugin_platform_interface/pubspec.yaml @@ -18,7 +18,7 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 2.1.8 environment: - sdk: ^3.8.0 + sdk: ^3.9.0 dependencies: meta: ^1.3.0 diff --git a/packages/pointer_interceptor/pointer_interceptor/CHANGELOG.md b/packages/pointer_interceptor/pointer_interceptor/CHANGELOG.md index 3f8575892ef2..a3be826bdf89 100644 --- a/packages/pointer_interceptor/pointer_interceptor/CHANGELOG.md +++ b/packages/pointer_interceptor/pointer_interceptor/CHANGELOG.md @@ -1,6 +1,10 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. +* Updates README to reflect currently supported OS versions for the latest + versions of the endorsed platform implementations. + * Applications built with older versions of Flutter will continue to + use compatible versions of the platform implementations. ## 0.10.1+2 diff --git a/packages/pointer_interceptor/pointer_interceptor/README.md b/packages/pointer_interceptor/pointer_interceptor/README.md index ebeb90cc02d5..2e5c3bfcc09f 100644 --- a/packages/pointer_interceptor/pointer_interceptor/README.md +++ b/packages/pointer_interceptor/pointer_interceptor/README.md @@ -2,7 +2,7 @@ | | iOS | Web | |-------------|---------|-----| -| **Support** | iOS 12+ | Any | +| **Support** | iOS 13+ | Any | `PointerInterceptor` is a widget that prevents mouse events from being captured by an underlying [`HtmlElementView`](https://api.flutter.dev/flutter/widgets/HtmlElementView-class.html) in web, or an underlying [`PlatformView`](https://api.flutter.dev/flutter/widgets/PlatformViewLink-class.html) on iOS. diff --git a/packages/pointer_interceptor/pointer_interceptor/example/ios/Flutter/AppFrameworkInfo.plist b/packages/pointer_interceptor/pointer_interceptor/example/ios/Flutter/AppFrameworkInfo.plist index 7c5696400627..391a902b2beb 100644 --- a/packages/pointer_interceptor/pointer_interceptor/example/ios/Flutter/AppFrameworkInfo.plist +++ b/packages/pointer_interceptor/pointer_interceptor/example/ios/Flutter/AppFrameworkInfo.plist @@ -20,7 +20,5 @@ ???? CFBundleVersion 1.0 - MinimumOSVersion - 12.0 diff --git a/packages/pointer_interceptor/pointer_interceptor/example/ios/Flutter/Debug.xcconfig b/packages/pointer_interceptor/pointer_interceptor/example/ios/Flutter/Debug.xcconfig index ec97fc6f3021..592ceee85b89 100644 --- a/packages/pointer_interceptor/pointer_interceptor/example/ios/Flutter/Debug.xcconfig +++ b/packages/pointer_interceptor/pointer_interceptor/example/ios/Flutter/Debug.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" diff --git a/packages/pointer_interceptor/pointer_interceptor/example/ios/Flutter/Release.xcconfig b/packages/pointer_interceptor/pointer_interceptor/example/ios/Flutter/Release.xcconfig index c4855bfe2000..592ceee85b89 100644 --- a/packages/pointer_interceptor/pointer_interceptor/example/ios/Flutter/Release.xcconfig +++ b/packages/pointer_interceptor/pointer_interceptor/example/ios/Flutter/Release.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" diff --git a/packages/pointer_interceptor/pointer_interceptor/example/ios/Podfile b/packages/pointer_interceptor/pointer_interceptor/example/ios/Podfile deleted file mode 100644 index 01d4aa611bb9..000000000000 --- a/packages/pointer_interceptor/pointer_interceptor/example/ios/Podfile +++ /dev/null @@ -1,40 +0,0 @@ -# Uncomment this line to define a global platform for your project -# platform :ios, '12.0' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_ios_podfile_setup - -target 'Runner' do - use_frameworks! - - flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_ios_build_settings(target) - end -end diff --git a/packages/pointer_interceptor/pointer_interceptor/example/ios/Runner.xcodeproj/project.pbxproj b/packages/pointer_interceptor/pointer_interceptor/example/ios/Runner.xcodeproj/project.pbxproj index f094be1b0316..924bbe6bb7f5 100644 --- a/packages/pointer_interceptor/pointer_interceptor/example/ios/Runner.xcodeproj/project.pbxproj +++ b/packages/pointer_interceptor/pointer_interceptor/example/ios/Runner.xcodeproj/project.pbxproj @@ -15,7 +15,6 @@ 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; F25BFF892B037A720088B2C7 /* DummyPlatformViewFactory.swift in Sources */ = {isa = PBXBuildFile; fileRef = F25BFF882B037A6C0088B2C7 /* DummyPlatformViewFactory.swift */; }; - F7B3FF2A19BF60DCE2927CCE /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = ABC6D95C6CA2BCA05B3C28FD /* Pods_Runner.framework */; }; /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -32,13 +31,12 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 095E300DCC1C42BD0A014AAC /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; - 53AC91685EB02A84FAE15CFA /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; @@ -47,8 +45,6 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - ABC6D95C6CA2BCA05B3C28FD /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - EBBA6242570F249EF7490E9D /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; F25BFF882B037A6C0088B2C7 /* DummyPlatformViewFactory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DummyPlatformViewFactory.swift; sourceTree = ""; }; /* End PBXFileReference section */ @@ -58,7 +54,6 @@ buildActionMask = 2147483647; files = ( 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, - F7B3FF2A19BF60DCE2927CCE /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -68,9 +63,6 @@ 1C9A5A1A7487CB72068132AF /* Pods */ = { isa = PBXGroup; children = ( - EBBA6242570F249EF7490E9D /* Pods-Runner.debug.xcconfig */, - 095E300DCC1C42BD0A014AAC /* Pods-Runner.release.xcconfig */, - 53AC91685EB02A84FAE15CFA /* Pods-Runner.profile.xcconfig */, ); path = Pods; sourceTree = ""; @@ -78,6 +70,7 @@ 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, 9740EEB21CF90195004384FC /* Debug.xcconfig */, 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, @@ -93,7 +86,6 @@ 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, 1C9A5A1A7487CB72068132AF /* Pods */, - FC5EF6E923E6BF75C542BDC7 /* Frameworks */, ); sourceTree = ""; }; @@ -121,14 +113,6 @@ path = Runner; sourceTree = ""; }; - FC5EF6E923E6BF75C542BDC7 /* Frameworks */ = { - isa = PBXGroup; - children = ( - ABC6D95C6CA2BCA05B3C28FD /* Pods_Runner.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -136,7 +120,6 @@ isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - 4B32A7E5952A8E40E6FE6E6C /* [CP] Check Pods Manifest.lock */, 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, @@ -224,28 +207,6 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; }; - 4B32A7E5952A8E40E6FE6E6C /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; 9740EEB61CF901F6004384FC /* Run Script */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; @@ -337,7 +298,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -415,7 +376,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -464,7 +425,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; diff --git a/packages/pointer_interceptor/pointer_interceptor/example/lib/platforms/native_widget_ios.dart b/packages/pointer_interceptor/pointer_interceptor/example/lib/platforms/native_widget_ios.dart index dabf9178b5d8..37f4ca4e89e1 100644 --- a/packages/pointer_interceptor/pointer_interceptor/example/lib/platforms/native_widget_ios.dart +++ b/packages/pointer_interceptor/pointer_interceptor/example/lib/platforms/native_widget_ios.dart @@ -16,8 +16,8 @@ class NativeWidget extends StatelessWidget { @override Widget build(BuildContext context) { - const String viewType = 'dummy_platform_view'; - final Map creationParams = {}; + const viewType = 'dummy_platform_view'; + final creationParams = {}; return UiKitView( viewType: viewType, diff --git a/packages/pointer_interceptor/pointer_interceptor/example/pubspec.yaml b/packages/pointer_interceptor/pointer_interceptor/example/pubspec.yaml index eb28f3a8e103..5bfe78bc828d 100644 --- a/packages/pointer_interceptor/pointer_interceptor/example/pubspec.yaml +++ b/packages/pointer_interceptor/pointer_interceptor/example/pubspec.yaml @@ -4,8 +4,8 @@ publish_to: 'none' version: 1.0.0 environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" dependencies: flutter: diff --git a/packages/pointer_interceptor/pointer_interceptor/pubspec.yaml b/packages/pointer_interceptor/pointer_interceptor/pubspec.yaml index b5a5a6c181b9..fd2bbcbdbfc1 100644 --- a/packages/pointer_interceptor/pointer_interceptor/pubspec.yaml +++ b/packages/pointer_interceptor/pointer_interceptor/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.10.1+2 environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" flutter: plugin: diff --git a/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/Flutter/AppFrameworkInfo.plist b/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/Flutter/AppFrameworkInfo.plist index b053eb6e360c..eb0b351a6f53 100644 --- a/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/Flutter/AppFrameworkInfo.plist +++ b/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/Flutter/AppFrameworkInfo.plist @@ -20,7 +20,5 @@ ???? CFBundleVersion 1.0 - MinimumOSVersion - 13.0 diff --git a/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/Flutter/Debug.xcconfig b/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/Flutter/Debug.xcconfig index ec97fc6f3021..592ceee85b89 100644 --- a/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/Flutter/Debug.xcconfig +++ b/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/Flutter/Debug.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" diff --git a/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/Flutter/Release.xcconfig b/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/Flutter/Release.xcconfig index c4855bfe2000..592ceee85b89 100644 --- a/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/Flutter/Release.xcconfig +++ b/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/Flutter/Release.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" diff --git a/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/Podfile b/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/Podfile deleted file mode 100644 index 620e46eba607..000000000000 --- a/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/Podfile +++ /dev/null @@ -1,43 +0,0 @@ -# Uncomment this line to define a global platform for your project -# platform :ios, '13.0' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_ios_podfile_setup - -target 'Runner' do - use_frameworks! - - flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) - target 'RunnerTests' do - inherit! :search_paths - end -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_ios_build_settings(target) - end -end diff --git a/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/Runner.xcodeproj/project.pbxproj b/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/Runner.xcodeproj/project.pbxproj index 9366431d7ca5..7d5a6ab19eb5 100644 --- a/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/Runner.xcodeproj/project.pbxproj +++ b/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/Runner.xcodeproj/project.pbxproj @@ -10,13 +10,11 @@ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; - 46643191504C316CD4ABDB75 /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F7324BF52939888500E1D0F3 /* Pods_RunnerTests.framework */; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; - E168ED82D399C1A9329D0876 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F1F367B2EDD332D4B9230AF1 /* Pods_Runner.framework */; }; F21CDFA32B056EBD0017C279 /* RunnerUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F21CDFA22B056EBD0017C279 /* RunnerUITests.swift */; }; F21CDFAD2B0591E30017C279 /* DummyPlatformViewFactory.swift in Sources */ = {isa = PBXBuildFile; fileRef = F21CDFAC2B0591E30017C279 /* DummyPlatformViewFactory.swift */; }; /* End PBXBuildFile section */ @@ -52,17 +50,16 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 0572F01CACAE4D575F1A1128 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; - 2DD5F6BD11575A75FA2A0EBC /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 37A897E52BBF8D001E20DCBE /* 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 = ""; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; - 4231BCCD2D6A3407E2AA20F2 /* 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 = ""; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 784666492D4C4C64000A1A5F /* FlutterFramework */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterFramework; path = Flutter/ephemeral/Packages/.packages/FlutterFramework; sourceTree = ""; }; + 78DABEA22ED26510000E7860 /* pointer_interceptor_ios */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = pointer_interceptor_ios; path = ../../ios/pointer_interceptor_ios; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; @@ -71,14 +68,10 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - B65B5543E4E11276FC0745D9 /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; - CDA7125E540D71A7A056DCE6 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; - F1F367B2EDD332D4B9230AF1 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; F21CDF922B056DB70017C279 /* RunnerUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerUITests.swift; sourceTree = ""; }; F21CDFA02B056EBD0017C279 /* RunnerUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; F21CDFA22B056EBD0017C279 /* RunnerUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerUITests.swift; sourceTree = ""; }; F21CDFAC2B0591E30017C279 /* DummyPlatformViewFactory.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DummyPlatformViewFactory.swift; sourceTree = ""; }; - F7324BF52939888500E1D0F3 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -86,7 +79,6 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 46643191504C316CD4ABDB75 /* Pods_RunnerTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -95,7 +87,6 @@ buildActionMask = 2147483647; files = ( 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, - E168ED82D399C1A9329D0876 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -120,6 +111,9 @@ 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( + 78DABEA22ED26510000E7860 /* pointer_interceptor_ios */, + 784666492D4C4C64000A1A5F /* FlutterFramework */, + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, 9740EEB21CF90195004384FC /* Debug.xcconfig */, 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, @@ -138,7 +132,6 @@ 97C146EF1CF9000F007C117D /* Products */, 331C8082294A63A400263BE5 /* RunnerTests */, DBD25E199A731479B0BACE39 /* Pods */, - ACDADE5C43240D66CC8F6502 /* Frameworks */, ); sourceTree = ""; }; @@ -168,24 +161,9 @@ path = Runner; sourceTree = ""; }; - ACDADE5C43240D66CC8F6502 /* Frameworks */ = { - isa = PBXGroup; - children = ( - F1F367B2EDD332D4B9230AF1 /* Pods_Runner.framework */, - F7324BF52939888500E1D0F3 /* Pods_RunnerTests.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; DBD25E199A731479B0BACE39 /* Pods */ = { isa = PBXGroup; children = ( - 2DD5F6BD11575A75FA2A0EBC /* Pods-Runner.debug.xcconfig */, - CDA7125E540D71A7A056DCE6 /* Pods-Runner.release.xcconfig */, - 0572F01CACAE4D575F1A1128 /* Pods-Runner.profile.xcconfig */, - 37A897E52BBF8D001E20DCBE /* Pods-RunnerTests.debug.xcconfig */, - 4231BCCD2D6A3407E2AA20F2 /* Pods-RunnerTests.release.xcconfig */, - B65B5543E4E11276FC0745D9 /* Pods-RunnerTests.profile.xcconfig */, ); path = Pods; sourceTree = ""; @@ -213,7 +191,6 @@ isa = PBXNativeTarget; buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; buildPhases = ( - DB9D75B7E0C58FFA3FAAD55B /* [CP] Check Pods Manifest.lock */, 331C807D294A63A400263BE5 /* Sources */, 331C807F294A63A400263BE5 /* Resources */, 92C054B3F5E4DE78794EA034 /* Frameworks */, @@ -232,7 +209,6 @@ isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - C53E3297221374298B80F1DF /* [CP] Check Pods Manifest.lock */, 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, @@ -378,50 +354,6 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; }; - C53E3297221374298B80F1DF /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; - DB9D75B7E0C58FFA3FAAD55B /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -560,7 +492,6 @@ }; 331C8088294A63A400263BE5 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 37A897E52BBF8D001E20DCBE /* Pods-RunnerTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CODE_SIGN_STYLE = Automatic; @@ -571,14 +502,13 @@ PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 6.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; }; name = Debug; }; 331C8089294A63A400263BE5 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 4231BCCD2D6A3407E2AA20F2 /* Pods-RunnerTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CODE_SIGN_STYLE = Automatic; @@ -587,14 +517,13 @@ MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = flutter.dev.pointerInterceptorIosExample.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 6.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; }; name = Release; }; 331C808A294A63A400263BE5 /* Profile */ = { isa = XCBuildConfiguration; - baseConfigurationReference = B65B5543E4E11276FC0745D9 /* Pods-RunnerTests.profile.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CODE_SIGN_STYLE = Automatic; @@ -603,7 +532,7 @@ MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = flutter.dev.pointerInterceptorIosExample.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; + SWIFT_VERSION = 6.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; }; name = Profile; diff --git a/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/RunnerTests/RunnerTests.swift b/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/RunnerTests/RunnerTests.swift index e75747b942cc..9b76f99fcbe8 100644 --- a/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/RunnerTests/RunnerTests.swift +++ b/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/RunnerTests/RunnerTests.swift @@ -2,26 +2,22 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -import Flutter +import Testing import UIKit -import XCTest @testable import pointer_interceptor_ios -class RunnerTests: XCTestCase { - func testNonDebugMode() { +@MainActor +struct RunnerTests { + @Test(arguments: [ + (false, UIColor.clear), + (true, UIColor(red: 1, green: 0, blue: 0, alpha: 0.5)), + ]) + func debugMode(debug: Bool, expectedColor: UIColor) { let view = PointerInterceptorView( - frame: CGRect(x: 0, y: 0, width: 180, height: 48.0), debug: false) + frame: CGRect(x: 0, y: 0, width: 180, height: 48.0), debug: debug) let debugView = view.view() - XCTAssertTrue(debugView.backgroundColor == UIColor.clear) - } - - func testDebugMode() { - let view = PointerInterceptorView( - frame: CGRect(x: 0, y: 0, width: 180, height: 48.0), debug: true) - - let debugView = view.view() - XCTAssertTrue(debugView.backgroundColor == UIColor(red: 1, green: 0, blue: 0, alpha: 0.5)) + #expect(debugView.backgroundColor == expectedColor) } } diff --git a/packages/pointer_interceptor/pointer_interceptor_ios/example/lib/main.dart b/packages/pointer_interceptor/pointer_interceptor_ios/example/lib/main.dart index ce131717bc62..f41d224e7835 100644 --- a/packages/pointer_interceptor/pointer_interceptor_ios/example/lib/main.dart +++ b/packages/pointer_interceptor/pointer_interceptor_ios/example/lib/main.dart @@ -15,8 +15,8 @@ class _DummyPlatformView extends StatelessWidget { @override Widget build(BuildContext context) { - const String viewType = 'dummy_platform_view'; - final Map creationParams = {}; + const viewType = 'dummy_platform_view'; + final creationParams = {}; return UiKitView( viewType: viewType, diff --git a/packages/pointer_interceptor/pointer_interceptor_platform_interface/CHANGELOG.md b/packages/pointer_interceptor/pointer_interceptor_platform_interface/CHANGELOG.md index 00109ecd1150..d00d7f195f60 100644 --- a/packages/pointer_interceptor/pointer_interceptor_platform_interface/CHANGELOG.md +++ b/packages/pointer_interceptor/pointer_interceptor_platform_interface/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. ## 0.10.0+1 diff --git a/packages/pointer_interceptor/pointer_interceptor_platform_interface/pubspec.yaml b/packages/pointer_interceptor/pointer_interceptor_platform_interface/pubspec.yaml index 7606f2a7ae1f..e43117259807 100644 --- a/packages/pointer_interceptor/pointer_interceptor_platform_interface/pubspec.yaml +++ b/packages/pointer_interceptor/pointer_interceptor_platform_interface/pubspec.yaml @@ -6,8 +6,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.10.0+1 environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" dependencies: flutter: diff --git a/packages/pointer_interceptor/pointer_interceptor_platform_interface/test/default_pointer_interceptor_test.dart b/packages/pointer_interceptor/pointer_interceptor_platform_interface/test/default_pointer_interceptor_test.dart index a310e985fd07..8355102ff36b 100644 --- a/packages/pointer_interceptor/pointer_interceptor_platform_interface/test/default_pointer_interceptor_test.dart +++ b/packages/pointer_interceptor/pointer_interceptor_platform_interface/test/default_pointer_interceptor_test.dart @@ -13,7 +13,7 @@ void main() { final PointerInterceptorPlatform defaultPointerInterceptor = PointerInterceptorPlatform.instance; - final Container testChild = Container(); + final testChild = Container(); expect(defaultPointerInterceptor.buildWidget(child: testChild), testChild); }); } diff --git a/packages/pointer_interceptor/pointer_interceptor_platform_interface/test/pointer_interceptor_platform_test.dart b/packages/pointer_interceptor/pointer_interceptor_platform_interface/test/pointer_interceptor_platform_test.dart index 3a666e1e7597..4caa0bd235e4 100644 --- a/packages/pointer_interceptor/pointer_interceptor_platform_interface/test/pointer_interceptor_platform_test.dart +++ b/packages/pointer_interceptor/pointer_interceptor_platform_interface/test/pointer_interceptor_platform_test.dart @@ -15,7 +15,7 @@ void main() { final PointerInterceptorPlatform unimplementedPointerInterceptorPlatform = UnimplementedPointerInterceptorPlatform(); - final Container testChild = Container(); + final testChild = Container(); expect( () => unimplementedPointerInterceptorPlatform.buildWidget( child: testChild, diff --git a/packages/pointer_interceptor/pointer_interceptor_web/CHANGELOG.md b/packages/pointer_interceptor/pointer_interceptor_web/CHANGELOG.md index 7df220e9fd07..9b293d6e71af 100644 --- a/packages/pointer_interceptor/pointer_interceptor_web/CHANGELOG.md +++ b/packages/pointer_interceptor/pointer_interceptor_web/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. ## 0.10.3 diff --git a/packages/pointer_interceptor/pointer_interceptor_web/example/integration_test/widget_test.dart b/packages/pointer_interceptor/pointer_interceptor_web/example/integration_test/widget_test.dart index 77cff645976a..c2b5be5877a1 100644 --- a/packages/pointer_interceptor/pointer_interceptor_web/example/integration_test/widget_test.dart +++ b/packages/pointer_interceptor/pointer_interceptor_web/example/integration_test/widget_test.dart @@ -91,8 +91,8 @@ void main() { ); expect(element.tagName.toLowerCase(), 'div'); - for (int i = 0; i <= 4; i++) { - final web.MouseEvent event = web.MouseEvent( + for (var i = 0; i <= 4; i++) { + final event = web.MouseEvent( 'mousedown', web.MouseEventInit(button: i, cancelable: true), ); diff --git a/packages/pointer_interceptor/pointer_interceptor_web/example/pubspec.yaml b/packages/pointer_interceptor/pointer_interceptor_web/example/pubspec.yaml index 7e26f72ebab8..f957e7b83066 100644 --- a/packages/pointer_interceptor/pointer_interceptor_web/example/pubspec.yaml +++ b/packages/pointer_interceptor/pointer_interceptor_web/example/pubspec.yaml @@ -3,8 +3,8 @@ description: "Demonstrates how to use the pointer_interceptor_web plugin." publish_to: 'none' environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" dependencies: cupertino_icons: ^1.0.2 diff --git a/packages/pointer_interceptor/pointer_interceptor_web/pubspec.yaml b/packages/pointer_interceptor/pointer_interceptor_web/pubspec.yaml index 0e3204ba3461..a9e498f6ac08 100644 --- a/packages/pointer_interceptor/pointer_interceptor_web/pubspec.yaml +++ b/packages/pointer_interceptor/pointer_interceptor_web/pubspec.yaml @@ -5,8 +5,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 0.10.3 environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" flutter: plugin: diff --git a/packages/quick_actions/quick_actions/CHANGELOG.md b/packages/quick_actions/quick_actions/CHANGELOG.md index 44eff9160dec..320339fb081c 100644 --- a/packages/quick_actions/quick_actions/CHANGELOG.md +++ b/packages/quick_actions/quick_actions/CHANGELOG.md @@ -1,7 +1,10 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. -* Updates README to indicate that Andoid SDK <21 is no longer supported. +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. +* Updates README to reflect currently supported OS versions for the latest + versions of the endorsed platform implementations. + * Applications built with older versions of Flutter will continue to + use compatible versions of the platform implementations. ## 1.1.0 diff --git a/packages/quick_actions/quick_actions/README.md b/packages/quick_actions/quick_actions/README.md index d9e0297cc6db..72dcd42220ee 100644 --- a/packages/quick_actions/quick_actions/README.md +++ b/packages/quick_actions/quick_actions/README.md @@ -9,9 +9,9 @@ on iOS and to the [App Shortcuts](https://developer.android.com/guide/topics/ui/shortcuts.html) APIs on Android. -| | Android | iOS | -|-------------|-----------|------| -| **Support** | SDK 21+\* | 9.0+ | +| | Android | iOS | +|-------------|-----------|-------| +| **Support** | SDK 24+\* | 13.0+ | ## Usage @@ -45,7 +45,7 @@ quick action. ### Android -\* The plugin will compile and run on SDK 16+, but will be a no-op below SDK 25 +\* The plugin will compile and run on SDK 24, but will be a no-op below SDK 25 (Android 7.1). If the drawables used as icons are not referenced other than in your Dart code, diff --git a/packages/quick_actions/quick_actions/example/android/app/gradle/wrapper/gradle-wrapper.properties b/packages/quick_actions/quick_actions/example/android/app/gradle/wrapper/gradle-wrapper.properties index 0c68fbc1dadd..4a647536b632 100644 --- a/packages/quick_actions/quick_actions/example/android/app/gradle/wrapper/gradle-wrapper.properties +++ b/packages/quick_actions/quick_actions/example/android/app/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.0-all.zip +networkTimeout=10000 zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists - diff --git a/packages/quick_actions/quick_actions/example/android/app/src/debug/AndroidManifest.xml b/packages/quick_actions/quick_actions/example/android/app/src/debug/AndroidManifest.xml index bee689df1735..ad14be24354e 100644 --- a/packages/quick_actions/quick_actions/example/android/app/src/debug/AndroidManifest.xml +++ b/packages/quick_actions/quick_actions/example/android/app/src/debug/AndroidManifest.xml @@ -4,7 +4,7 @@ to allow setting breakpoints, to provide hot reload, etc. --> - + ???? CFBundleVersion 1.0 - MinimumOSVersion - 12.0 diff --git a/packages/quick_actions/quick_actions/example/ios/Flutter/Debug.xcconfig b/packages/quick_actions/quick_actions/example/ios/Flutter/Debug.xcconfig index ec97fc6f3021..592ceee85b89 100644 --- a/packages/quick_actions/quick_actions/example/ios/Flutter/Debug.xcconfig +++ b/packages/quick_actions/quick_actions/example/ios/Flutter/Debug.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" diff --git a/packages/quick_actions/quick_actions/example/ios/Flutter/Release.xcconfig b/packages/quick_actions/quick_actions/example/ios/Flutter/Release.xcconfig index c4855bfe2000..592ceee85b89 100644 --- a/packages/quick_actions/quick_actions/example/ios/Flutter/Release.xcconfig +++ b/packages/quick_actions/quick_actions/example/ios/Flutter/Release.xcconfig @@ -1,2 +1 @@ -#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" diff --git a/packages/quick_actions/quick_actions/example/ios/Podfile b/packages/quick_actions/quick_actions/example/ios/Podfile deleted file mode 100644 index 01d4aa611bb9..000000000000 --- a/packages/quick_actions/quick_actions/example/ios/Podfile +++ /dev/null @@ -1,40 +0,0 @@ -# Uncomment this line to define a global platform for your project -# platform :ios, '12.0' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_ios_podfile_setup - -target 'Runner' do - use_frameworks! - - flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_ios_build_settings(target) - end -end diff --git a/packages/quick_actions/quick_actions/example/ios/Runner.xcodeproj/project.pbxproj b/packages/quick_actions/quick_actions/example/ios/Runner.xcodeproj/project.pbxproj index 2b193815a91b..b5b5f00de4f5 100644 --- a/packages/quick_actions/quick_actions/example/ios/Runner.xcodeproj/project.pbxproj +++ b/packages/quick_actions/quick_actions/example/ios/Runner.xcodeproj/project.pbxproj @@ -11,7 +11,6 @@ 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; - 91D5522EB65E8FD8A1A8FEA5 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 65E9E1A69E00E453A620EE16 /* Pods_Runner.framework */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; @@ -33,12 +32,10 @@ /* Begin PBXFileReference section */ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; - 258A707F7F5E75508EA6CBB5 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; - 489B9F06437C3EC3C24CCFF7 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; - 65E9E1A69E00E453A620EE16 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; @@ -47,7 +44,6 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - E04C971B2BC180B7F1721E5B /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -56,7 +52,6 @@ buildActionMask = 2147483647; files = ( 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, - 91D5522EB65E8FD8A1A8FEA5 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -66,24 +61,14 @@ 6AEEE814FD5A1A7548F4A15A /* Pods */ = { isa = PBXGroup; children = ( - 258A707F7F5E75508EA6CBB5 /* Pods-Runner.debug.xcconfig */, - 489B9F06437C3EC3C24CCFF7 /* Pods-Runner.release.xcconfig */, - E04C971B2BC180B7F1721E5B /* Pods-Runner.profile.xcconfig */, ); path = Pods; sourceTree = ""; }; - 7428BFE57AC84D10FDE3026A /* Frameworks */ = { - isa = PBXGroup; - children = ( - 65E9E1A69E00E453A620EE16 /* Pods_Runner.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, 9740EEB21CF90195004384FC /* Debug.xcconfig */, 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, @@ -99,7 +84,6 @@ 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, 6AEEE814FD5A1A7548F4A15A /* Pods */, - 7428BFE57AC84D10FDE3026A /* Frameworks */, ); sourceTree = ""; }; @@ -133,7 +117,6 @@ isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - 8F1FD4D99F6E5F7BAB7F5DD3 /* [CP] Check Pods Manifest.lock */, 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, @@ -221,28 +204,6 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; }; - 8F1FD4D99F6E5F7BAB7F5DD3 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; 9740EEB61CF901F6004384FC /* Run Script */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; @@ -335,7 +296,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -414,7 +375,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -465,7 +426,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; diff --git a/packages/quick_actions/quick_actions/example/lib/main.dart b/packages/quick_actions/quick_actions/example/lib/main.dart index 8a450d7e2b8c..0c08713fb5fe 100644 --- a/packages/quick_actions/quick_actions/example/lib/main.dart +++ b/packages/quick_actions/quick_actions/example/lib/main.dart @@ -38,7 +38,7 @@ class _MyHomePageState extends State { void initState() { super.initState(); - const QuickActions quickActions = QuickActions(); + const quickActions = QuickActions(); quickActions.initialize((String shortcutType) { setState(() { shortcut = shortcutType; diff --git a/packages/quick_actions/quick_actions/example/pubspec.yaml b/packages/quick_actions/quick_actions/example/pubspec.yaml index 198113858ff8..d9883248bc58 100644 --- a/packages/quick_actions/quick_actions/example/pubspec.yaml +++ b/packages/quick_actions/quick_actions/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the quick_actions plugin. publish_to: none environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" dependencies: flutter: @@ -18,7 +18,6 @@ dependencies: path: ../ dev_dependencies: - espresso: ^0.4.0 flutter_test: sdk: flutter integration_test: diff --git a/packages/quick_actions/quick_actions/pubspec.yaml b/packages/quick_actions/quick_actions/pubspec.yaml index 9802bb0a0b8c..c4374dc4ed79 100644 --- a/packages/quick_actions/quick_actions/pubspec.yaml +++ b/packages/quick_actions/quick_actions/pubspec.yaml @@ -6,8 +6,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 1.1.0 environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" flutter: plugin: diff --git a/packages/quick_actions/quick_actions/test/quick_actions_test.dart b/packages/quick_actions/quick_actions/test/quick_actions_test.dart index f07248c2cb4c..7ce442feece4 100644 --- a/packages/quick_actions/quick_actions/test/quick_actions_test.dart +++ b/packages/quick_actions/quick_actions/test/quick_actions_test.dart @@ -15,12 +15,12 @@ void main() { }); test('constructor() should return valid QuickActions instance', () { - const QuickActions quickActions = QuickActions(); + const quickActions = QuickActions(); expect(quickActions, isNotNull); }); test('initialize() PlatformInterface', () async { - const QuickActions quickActions = QuickActions(); + const quickActions = QuickActions(); void handler(String type) {} await quickActions.initialize(handler); @@ -28,7 +28,7 @@ void main() { }); test('setShortcutItems() PlatformInterface', () { - const QuickActions quickActions = QuickActions(); + const quickActions = QuickActions(); void handler(String type) {} quickActions.initialize(handler); quickActions.setShortcutItems([]); @@ -40,7 +40,7 @@ void main() { }); test('clearShortcutItems() PlatformInterface', () { - const QuickActions quickActions = QuickActions(); + const quickActions = QuickActions(); void handler(String type) {} quickActions.initialize(handler); diff --git a/packages/quick_actions/quick_actions_android/CHANGELOG.md b/packages/quick_actions/quick_actions_android/CHANGELOG.md index b6c6e29e5382..fcacbb356d3c 100644 --- a/packages/quick_actions/quick_actions_android/CHANGELOG.md +++ b/packages/quick_actions/quick_actions_android/CHANGELOG.md @@ -1,3 +1,8 @@ +## 1.0.28 + +* Updates build files from Groovy to Kotlin. +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. + ## 1.0.27 * Bumps com.android.tools.build:gradle from 8.12.1 to 8.13.1. diff --git a/packages/quick_actions/quick_actions_android/android/build.gradle b/packages/quick_actions/quick_actions_android/android/build.gradle deleted file mode 100644 index 429c726f6ba6..000000000000 --- a/packages/quick_actions/quick_actions_android/android/build.gradle +++ /dev/null @@ -1,60 +0,0 @@ -group = 'io.flutter.plugins.quickactions' -version = '1.0-SNAPSHOT' - -buildscript { - repositories { - google() - mavenCentral() - } - - dependencies { - classpath 'com.android.tools.build:gradle:8.13.1' - } -} - -rootProject.allprojects { - repositories { - google() - mavenCentral() - } -} - -apply plugin: 'com.android.library' - -android { - namespace = "io.flutter.plugins.quickactions" - compileSdk = flutter.compileSdkVersion - - defaultConfig { - minSdkVersion 21 - testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - } - lintOptions { - checkAllWarnings = true - warningsAsErrors = true - disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency', 'NewerVersionAvailable' - } - - dependencies { - implementation("androidx.annotation:annotation:1.9.1") - testImplementation("junit:junit:4.13.2") - testImplementation("org.mockito:mockito-core:5.19.0") - } - - compileOptions { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 - } - - testOptions { - unitTests.includeAndroidResources = true - unitTests.returnDefaultValues = true - unitTests.all { - testLogging { - events "passed", "skipped", "failed", "standardOut", "standardError" - outputs.upToDateWhen {false} - showStandardStreams = true - } - } - } -} diff --git a/packages/quick_actions/quick_actions_android/android/build.gradle.kts b/packages/quick_actions/quick_actions_android/android/build.gradle.kts new file mode 100644 index 000000000000..bb8fa232e967 --- /dev/null +++ b/packages/quick_actions/quick_actions_android/android/build.gradle.kts @@ -0,0 +1,65 @@ +group = "io.flutter.plugins.quickactions" +version = "1.0-SNAPSHOT" + +buildscript { + repositories { + google() + mavenCentral() + } + + dependencies { + classpath("com.android.tools.build:gradle:8.13.1") + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +plugins { + id("com.android.library") +} + +android { + namespace = "io.flutter.plugins.quickactions" + compileSdk = flutter.compileSdkVersion + + defaultConfig { + minSdk = 24 + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + lint { + checkAllWarnings = true + warningsAsErrors = true + disable.addAll(setOf("AndroidGradlePluginVersion", "InvalidPackage", "GradleDependency", "NewerVersionAvailable")) + } + + dependencies { + implementation("androidx.annotation:annotation:1.9.1") + testImplementation("junit:junit:4.13.2") + testImplementation("org.mockito:mockito-core:5.23.0") + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + testOptions { + unitTests { + isIncludeAndroidResources = true + isReturnDefaultValues = true + all { + it.outputs.upToDateWhen { false } + it.testLogging { + events("passed", "skipped", "failed", "standardOut", "standardError") + showStandardStreams = true + } + } + } + } +} diff --git a/packages/quick_actions/quick_actions_android/android/settings.gradle b/packages/quick_actions/quick_actions_android/android/settings.gradle deleted file mode 100644 index 75248241ec35..000000000000 --- a/packages/quick_actions/quick_actions_android/android/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'quick_actions' diff --git a/packages/quick_actions/quick_actions_android/android/settings.gradle.kts b/packages/quick_actions/quick_actions_android/android/settings.gradle.kts new file mode 100644 index 000000000000..300d89d29631 --- /dev/null +++ b/packages/quick_actions/quick_actions_android/android/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "quick_actions" diff --git a/packages/quick_actions/quick_actions_android/example/android/app/gradle/wrapper/gradle-wrapper.properties b/packages/quick_actions/quick_actions_android/example/android/app/gradle/wrapper/gradle-wrapper.properties index 0c68fbc1dadd..4a647536b632 100644 --- a/packages/quick_actions/quick_actions_android/example/android/app/gradle/wrapper/gradle-wrapper.properties +++ b/packages/quick_actions/quick_actions_android/example/android/app/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.0-all.zip +networkTimeout=10000 zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists - diff --git a/packages/quick_actions/quick_actions_android/example/android/app/src/debug/AndroidManifest.xml b/packages/quick_actions/quick_actions_android/example/android/app/src/debug/AndroidManifest.xml index bee689df1735..ad14be24354e 100644 --- a/packages/quick_actions/quick_actions_android/example/android/app/src/debug/AndroidManifest.xml +++ b/packages/quick_actions/quick_actions_android/example/android/app/src/debug/AndroidManifest.xml @@ -4,7 +4,7 @@ to allow setting breakpoints, to provide hot reload, etc. --> - + { void initState() { super.initState(); - final QuickActionsAndroid quickActions = QuickActionsAndroid(); + final quickActions = QuickActionsAndroid(); quickActions.initialize((String shortcutType) { setState(() { shortcut = '$shortcutType has launched'; diff --git a/packages/quick_actions/quick_actions_android/example/pubspec.yaml b/packages/quick_actions/quick_actions_android/example/pubspec.yaml index 697dcba09935..4c8788be9b1d 100644 --- a/packages/quick_actions/quick_actions_android/example/pubspec.yaml +++ b/packages/quick_actions/quick_actions_android/example/pubspec.yaml @@ -3,8 +3,8 @@ description: Demonstrates how to use the quick_actions plugin. publish_to: none environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" dependencies: flutter: diff --git a/packages/quick_actions/quick_actions_android/lib/quick_actions_android.dart b/packages/quick_actions/quick_actions_android/lib/quick_actions_android.dart index 5a69f8badd5a..496fd0daced1 100644 --- a/packages/quick_actions/quick_actions_android/lib/quick_actions_android.dart +++ b/packages/quick_actions/quick_actions_android/lib/quick_actions_android.dart @@ -26,8 +26,7 @@ class QuickActionsAndroid extends QuickActionsPlatform { @override Future initialize(QuickActionHandler handler) async { - final _QuickActionHandlerApi quickActionsHandlerApi = - _QuickActionHandlerApi(); + final quickActionsHandlerApi = _QuickActionHandlerApi(); AndroidQuickActionsFlutterApi.setUp(quickActionsHandlerApi); _handler = handler; final String? action = await _hostApi.getLaunchAction(); diff --git a/packages/quick_actions/quick_actions_android/pubspec.yaml b/packages/quick_actions/quick_actions_android/pubspec.yaml index d468da6bbd51..dd05368fd9de 100644 --- a/packages/quick_actions/quick_actions_android/pubspec.yaml +++ b/packages/quick_actions/quick_actions_android/pubspec.yaml @@ -2,7 +2,7 @@ name: quick_actions_android description: An implementation for the Android platform of the Flutter `quick_actions` plugin. repository: https://github.com/flutter/packages/tree/main/packages/quick_actions/quick_actions_android issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+in_app_purchase%22 -version: 1.0.27 +version: 1.0.28 environment: sdk: ^3.9.0 diff --git a/packages/quick_actions/quick_actions_android/test/quick_actions_android_test.dart b/packages/quick_actions/quick_actions_android/test/quick_actions_android_test.dart index f15060ffcdf6..dc7acffcca69 100644 --- a/packages/quick_actions/quick_actions_android/test/quick_actions_android_test.dart +++ b/packages/quick_actions/quick_actions_android/test/quick_actions_android_test.dart @@ -24,8 +24,8 @@ ShortcutItem shortcutItemMessageToShortcutItem(ShortcutItemMessage item) { void main() { TestWidgetsFlutterBinding.ensureInitialized(); - final _FakeQuickActionsApi api = _FakeQuickActionsApi(); - final QuickActionsAndroid quickActions = QuickActionsAndroid(api: api); + final api = _FakeQuickActionsApi(); + final quickActions = QuickActionsAndroid(api: api); test('registerWith() registers correct instance', () { QuickActionsAndroid.registerWith(); @@ -40,7 +40,7 @@ void main() { }); test('initialize', () async { - final Completer quickActionsHandler = Completer(); + final quickActionsHandler = Completer(); await quickActions.initialize((_) => quickActionsHandler.complete(true)); expect(quickActionsHandler.future, completion(isTrue)); @@ -49,7 +49,7 @@ void main() { test('setShortCutItems', () async { await quickActions.initialize((String type) {}); - const ShortcutItem item = ShortcutItem( + const item = ShortcutItem( type: 'test', localizedTitle: 'title', icon: 'icon.svg', @@ -63,7 +63,7 @@ void main() { test('clearShortCutItems', () { quickActions.initialize((String type) {}); - const ShortcutItem item = ShortcutItem( + const item = ShortcutItem( type: 'test', localizedTitle: 'title', icon: 'icon.svg', @@ -75,11 +75,11 @@ void main() { }); test('Shortcut item can be constructed', () { - const String type = 'type'; - const String localizedTitle = 'title'; - const String icon = 'foo'; + const type = 'type'; + const localizedTitle = 'title'; + const icon = 'foo'; - const ShortcutItem item = ShortcutItem( + const item = ShortcutItem( type: type, localizedTitle: localizedTitle, icon: icon, @@ -110,7 +110,7 @@ class _FakeQuickActionsApi implements AndroidQuickActionsApi { @override Future setShortcutItems(List itemsList) async { await clearShortcutItems(); - for (final ShortcutItemMessage? element in itemsList) { + for (final element in itemsList) { items.add(shortcutItemMessageToShortcutItem(element!)); } } diff --git a/packages/quick_actions/quick_actions_ios/example/.gitignore b/packages/quick_actions/quick_actions_ios/example/.gitignore new file mode 100644 index 000000000000..3820a95c65c3 --- /dev/null +++ b/packages/quick_actions/quick_actions_ios/example/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/packages/quick_actions/quick_actions_ios/example/.metadata b/packages/quick_actions/quick_actions_ios/example/.metadata new file mode 100644 index 000000000000..5998223843fe --- /dev/null +++ b/packages/quick_actions/quick_actions_ios/example/.metadata @@ -0,0 +1,30 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "67323de285b00232883f53b84095eb72be97d35c" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 67323de285b00232883f53b84095eb72be97d35c + base_revision: 67323de285b00232883f53b84095eb72be97d35c + - platform: ios + create_revision: 67323de285b00232883f53b84095eb72be97d35c + base_revision: 67323de285b00232883f53b84095eb72be97d35c + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/packages/quick_actions/quick_actions_ios/example/integration_test/quick_actions_test.dart b/packages/quick_actions/quick_actions_ios/example/integration_test/quick_actions_test.dart index 56f229354690..328da2f4b829 100644 --- a/packages/quick_actions/quick_actions_ios/example/integration_test/quick_actions_test.dart +++ b/packages/quick_actions/quick_actions_ios/example/integration_test/quick_actions_test.dart @@ -10,10 +10,10 @@ void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('Can set shortcuts', (WidgetTester tester) async { - final QuickActionsIos quickActions = QuickActionsIos(); + final quickActions = QuickActionsIos(); await quickActions.initialize((String value) {}); - const ShortcutItem shortCutItem = ShortcutItem( + const shortCutItem = ShortcutItem( type: 'action_one', localizedTitle: 'Action one', icon: 'AppIcon', diff --git a/packages/quick_actions/quick_actions_ios/example/ios/.gitignore b/packages/quick_actions/quick_actions_ios/example/ios/.gitignore new file mode 100644 index 000000000000..7a7f9873ad7d --- /dev/null +++ b/packages/quick_actions/quick_actions_ios/example/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Flutter/AppFrameworkInfo.plist b/packages/quick_actions/quick_actions_ios/example/ios/Flutter/AppFrameworkInfo.plist index 1f6b98f117b2..391a902b2beb 100644 --- a/packages/quick_actions/quick_actions_ios/example/ios/Flutter/AppFrameworkInfo.plist +++ b/packages/quick_actions/quick_actions_ios/example/ios/Flutter/AppFrameworkInfo.plist @@ -20,11 +20,5 @@ ???? CFBundleVersion 1.0 - UIRequiredDeviceCapabilities - - arm64 - - MinimumOSVersion - 13.0 diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Flutter/Debug.xcconfig b/packages/quick_actions/quick_actions_ios/example/ios/Flutter/Debug.xcconfig index e8efba114687..592ceee85b89 100644 --- a/packages/quick_actions/quick_actions_ios/example/ios/Flutter/Debug.xcconfig +++ b/packages/quick_actions/quick_actions_ios/example/ios/Flutter/Debug.xcconfig @@ -1,2 +1 @@ -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Flutter/Release.xcconfig b/packages/quick_actions/quick_actions_ios/example/ios/Flutter/Release.xcconfig index 399e9340e6f6..592ceee85b89 100644 --- a/packages/quick_actions/quick_actions_ios/example/ios/Flutter/Release.xcconfig +++ b/packages/quick_actions/quick_actions_ios/example/ios/Flutter/Release.xcconfig @@ -1,2 +1 @@ -#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Podfile b/packages/quick_actions/quick_actions_ios/example/ios/Podfile deleted file mode 100644 index 6eafd7e2e953..000000000000 --- a/packages/quick_actions/quick_actions_ios/example/ios/Podfile +++ /dev/null @@ -1,41 +0,0 @@ -# Uncomment this line to define a global platform for your project -# platform :ios, '13.0' - -# CocoaPods analytics sends network stats synchronously affecting flutter build latency. -ENV['COCOAPODS_DISABLE_STATS'] = 'true' - -project 'Runner', { - 'Debug' => :debug, - 'Profile' => :release, - 'Release' => :release, -} - -def flutter_root - generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) - unless File.exist?(generated_xcode_build_settings_path) - raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" - end - - File.foreach(generated_xcode_build_settings_path) do |line| - matches = line.match(/FLUTTER_ROOT\=(.*)/) - return matches[1].strip if matches - end - raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" -end - -require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - -flutter_ios_podfile_setup - -target 'Runner' do - flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) - target 'RunnerTests' do - inherit! :search_paths - end -end - -post_install do |installer| - installer.pods_project.targets.each do |target| - flutter_additional_ios_build_settings(target) - end -end diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner.xcodeproj/project.pbxproj b/packages/quick_actions/quick_actions_ios/example/ios/Runner.xcodeproj/project.pbxproj index c50a5183a257..de1bcff445d7 100644 --- a/packages/quick_actions/quick_actions_ios/example/ios/Runner.xcodeproj/project.pbxproj +++ b/packages/quick_actions/quick_actions_ios/example/ios/Runner.xcodeproj/project.pbxproj @@ -8,29 +8,26 @@ /* Begin PBXBuildFile section */ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; - 2632072169FF635893D8EB4D /* libPods-RunnerTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 436668746754BEEA28B76E55 /* libPods-RunnerTests.a */; }; + 331585A52F352C8600FACB51 /* RunnerUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331585A22F352C8600FACB51 /* RunnerUITests.swift */; }; + 331585A82F352CE600FACB51 /* QuickActionsPluginTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331585A72F352CE600FACB51 /* QuickActionsPluginTests.swift */; }; + 331585AE2F352D1800FACB51 /* MockShortcutItemProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331585AC2F352D1800FACB51 /* MockShortcutItemProvider.swift */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; - 6A841C2B6AED5CF8DB2A1894 /* libPods-Runner.a in Frameworks */ = {isa = PBXBuildFile; fileRef = C35AD3650AB6BF850E016715 /* libPods-Runner.a */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; - 978B8F6F1D3862AE00F588F7 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */; }; - 97C146F31CF9000F007C117D /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 97C146F21CF9000F007C117D /* main.m */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; - E092A7EE28D10802005C7F67 /* QuickActionsPluginTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E092A7EB28D10802005C7F67 /* QuickActionsPluginTests.swift */; }; - E092A7F128D10890005C7F67 /* MockShortcutItemProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = E092A7F028D10890005C7F67 /* MockShortcutItemProvider.swift */; }; - E092A7F628D128EB005C7F67 /* RunnerUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E092A7F528D128EB005C7F67 /* RunnerUITests.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ - 33E20B3726EFCDFC00A4A191 /* PBXContainerItemProxy */ = { + 3315859C2F352C6B00FACB51 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 97C146E61CF9000F007C117D /* Project object */; proxyType = 1; remoteGlobalIDString = 97C146ED1CF9000F007C117D; remoteInfo = Runner; }; - 686BE83225E58CCF00862533 /* PBXContainerItemProxy */ = { + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 97C146E61CF9000F007C117D /* Project object */; proxyType = 1; @@ -55,43 +52,36 @@ /* Begin PBXFileReference section */ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; - 33E20B3226EFCDFC00A4A191 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 33E20B3626EFCDFC00A4A191 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 331585962F352C6B00FACB51 /* RunnerUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331585A22F352C8600FACB51 /* RunnerUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerUITests.swift; sourceTree = ""; }; + 331585A72F352CE600FACB51 /* QuickActionsPluginTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QuickActionsPluginTests.swift; sourceTree = ""; }; + 331585AC2F352D1800FACB51 /* MockShortcutItemProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockShortcutItemProvider.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; - 436668746754BEEA28B76E55 /* libPods-RunnerTests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-RunnerTests.a"; sourceTree = BUILT_PRODUCTS_DIR; }; - 5278439583922091276A37C9 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; - 686BE82D25E58CCF00862533 /* RunnerUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 686BE83125E58CCF00862533 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 784666492D4C4C64000A1A5F /* FlutterFramework */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterFramework; path = Flutter/ephemeral/Packages/.packages/FlutterFramework; sourceTree = ""; }; + 78DABEA22ED26510000E7860 /* quick_actions_ios */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = quick_actions_ios; path = ../../ios/quick_actions_ios; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; - 7AFFD8ED1D35381100E5BB4D /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; - 7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; - 96F949A6B78E2DC62B93C4F8 /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 97C146F21CF9000F007C117D /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 9D27FE1F0F21D4D47DDA16DE /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; - C35AD3650AB6BF850E016715 /* libPods-Runner.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-Runner.a"; sourceTree = BUILT_PRODUCTS_DIR; }; - E092A7EB28D10802005C7F67 /* QuickActionsPluginTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QuickActionsPluginTests.swift; sourceTree = ""; }; - E092A7F028D10890005C7F67 /* MockShortcutItemProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockShortcutItemProvider.swift; sourceTree = ""; }; - E092A7F528D128EB005C7F67 /* RunnerUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerUITests.swift; sourceTree = ""; }; - F0609304FBCAEC2289164BD5 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ - 33E20B2F26EFCDFC00A4A191 /* Frameworks */ = { + 331585932F352C6B00FACB51 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 2632072169FF635893D8EB4D /* libPods-RunnerTests.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; - 686BE82A25E58CCF00862533 /* Frameworks */ = { + 8C572A24CDFB4B16C53DB292 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( @@ -103,35 +93,43 @@ buildActionMask = 2147483647; files = ( 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, - 6A841C2B6AED5CF8DB2A1894 /* libPods-Runner.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 33E20B3326EFCDFC00A4A191 /* RunnerTests */ = { + 331585A42F352C8600FACB51 /* RunnerUITests */ = { isa = PBXGroup; children = ( - E092A7F228D10908005C7F67 /* Mocks */, - 33E20B3626EFCDFC00A4A191 /* Info.plist */, - E092A7EB28D10802005C7F67 /* QuickActionsPluginTests.swift */, + 331585A22F352C8600FACB51 /* RunnerUITests.swift */, ); - path = RunnerTests; + path = RunnerUITests; sourceTree = ""; }; - 686BE82E25E58CCF00862533 /* RunnerUITests */ = { + 331585AD2F352D1800FACB51 /* Mocks */ = { isa = PBXGroup; children = ( - 686BE83125E58CCF00862533 /* Info.plist */, - E092A7F528D128EB005C7F67 /* RunnerUITests.swift */, + 331585AC2F352D1800FACB51 /* MockShortcutItemProvider.swift */, ); - path = RunnerUITests; + path = Mocks; + sourceTree = ""; + }; + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331585A72F352CE600FACB51 /* QuickActionsPluginTests.swift */, + 331585AD2F352D1800FACB51 /* Mocks */, + ); + path = RunnerTests; sourceTree = ""; }; 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( + 78DABEA22ED26510000E7860 /* quick_actions_ios */, + 784666492D4C4C64000A1A5F /* FlutterFramework */, + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, 9740EEB21CF90195004384FC /* Debug.xcconfig */, 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, @@ -145,11 +143,9 @@ children = ( 9740EEB11CF90186004384FC /* Flutter */, 97C146F01CF9000F007C117D /* Runner */, - 686BE82E25E58CCF00862533 /* RunnerUITests */, - 33E20B3326EFCDFC00A4A191 /* RunnerTests */, 97C146EF1CF9000F007C117D /* Products */, - D0FE95BE2380323DD75CB891 /* Pods */, - A44AD0D63DEF785A2A2DEE28 /* Frameworks */, + 331C8082294A63A400263BE5 /* RunnerTests */, + 331585A42F352C8600FACB51 /* RunnerUITests */, ); sourceTree = ""; }; @@ -157,8 +153,8 @@ isa = PBXGroup; children = ( 97C146EE1CF9000F007C117D /* Runner.app */, - 686BE82D25E58CCF00862533 /* RunnerUITests.xctest */, - 33E20B3226EFCDFC00A4A191 /* RunnerTests.xctest */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + 331585962F352C6B00FACB51 /* RunnerUITests.xctest */, ); name = Products; sourceTree = ""; @@ -166,100 +162,61 @@ 97C146F01CF9000F007C117D /* Runner */ = { isa = PBXGroup; children = ( - 7AFFD8ED1D35381100E5BB4D /* AppDelegate.h */, - 7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */, 97C146FA1CF9000F007C117D /* Main.storyboard */, 97C146FD1CF9000F007C117D /* Assets.xcassets */, 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, 97C147021CF9000F007C117D /* Info.plist */, - 97C146F11CF9000F007C117D /* Supporting Files */, 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, ); path = Runner; sourceTree = ""; }; - 97C146F11CF9000F007C117D /* Supporting Files */ = { - isa = PBXGroup; - children = ( - 97C146F21CF9000F007C117D /* main.m */, - ); - name = "Supporting Files"; - sourceTree = ""; - }; - A44AD0D63DEF785A2A2DEE28 /* Frameworks */ = { - isa = PBXGroup; - children = ( - C35AD3650AB6BF850E016715 /* libPods-Runner.a */, - 436668746754BEEA28B76E55 /* libPods-RunnerTests.a */, - ); - name = Frameworks; - sourceTree = ""; - }; - D0FE95BE2380323DD75CB891 /* Pods */ = { - isa = PBXGroup; - children = ( - 5278439583922091276A37C9 /* Pods-Runner.debug.xcconfig */, - F0609304FBCAEC2289164BD5 /* Pods-Runner.release.xcconfig */, - 9D27FE1F0F21D4D47DDA16DE /* Pods-RunnerTests.debug.xcconfig */, - 96F949A6B78E2DC62B93C4F8 /* Pods-RunnerTests.release.xcconfig */, - ); - name = Pods; - sourceTree = ""; - }; - E092A7F228D10908005C7F67 /* Mocks */ = { - isa = PBXGroup; - children = ( - E092A7F028D10890005C7F67 /* MockShortcutItemProvider.swift */, - ); - path = Mocks; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ - 33E20B3126EFCDFC00A4A191 /* RunnerTests */ = { + 331585952F352C6B00FACB51 /* RunnerUITests */ = { isa = PBXNativeTarget; - buildConfigurationList = 33E20B3B26EFCDFC00A4A191 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildConfigurationList = 331585A12F352C6B00FACB51 /* Build configuration list for PBXNativeTarget "RunnerUITests" */; buildPhases = ( - 3B2E8279C112D7129C8D23F1 /* [CP] Check Pods Manifest.lock */, - 33E20B2E26EFCDFC00A4A191 /* Sources */, - 33E20B2F26EFCDFC00A4A191 /* Frameworks */, - 33E20B3026EFCDFC00A4A191 /* Resources */, + 331585922F352C6B00FACB51 /* Sources */, + 331585932F352C6B00FACB51 /* Frameworks */, + 331585942F352C6B00FACB51 /* Resources */, ); buildRules = ( ); dependencies = ( - 33E20B3826EFCDFC00A4A191 /* PBXTargetDependency */, + 3315859D2F352C6B00FACB51 /* PBXTargetDependency */, ); - name = RunnerTests; - productName = RunnerTests; - productReference = 33E20B3226EFCDFC00A4A191 /* RunnerTests.xctest */; - productType = "com.apple.product-type.bundle.unit-test"; + name = RunnerUITests; + productName = RunnerUITests; + productReference = 331585962F352C6B00FACB51 /* RunnerUITests.xctest */; + productType = "com.apple.product-type.bundle.ui-testing"; }; - 686BE82C25E58CCF00862533 /* RunnerUITests */ = { + 331C8080294A63A400263BE5 /* RunnerTests */ = { isa = PBXNativeTarget; - buildConfigurationList = 686BE83625E58CCF00862533 /* Build configuration list for PBXNativeTarget "RunnerUITests" */; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; buildPhases = ( - 686BE82925E58CCF00862533 /* Sources */, - 686BE82A25E58CCF00862533 /* Frameworks */, - 686BE82B25E58CCF00862533 /* Resources */, + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + 8C572A24CDFB4B16C53DB292 /* Frameworks */, ); buildRules = ( ); dependencies = ( - 686BE83325E58CCF00862533 /* PBXTargetDependency */, + 331C8086294A63A400263BE5 /* PBXTargetDependency */, ); - name = RunnerUITests; - productName = RunnerUITests; - productReference = 686BE82D25E58CCF00862533 /* RunnerUITests.xctest */; - productType = "com.apple.product-type.bundle.ui-testing"; + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; }; 97C146ED1CF9000F007C117D /* Runner */ = { isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( - C6989ECD8FF0836301D734B4 /* [CP] Check Pods Manifest.lock */, 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, @@ -285,27 +242,28 @@ 97C146E61CF9000F007C117D /* Project object */ = { isa = PBXProject; attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 2620; LastUpgradeCheck = 1510; - ORGANIZATIONNAME = "The Flutter Authors"; + ORGANIZATIONNAME = ""; TargetAttributes = { - 33E20B3126EFCDFC00A4A191 = { - CreatedOnToolsVersion = 12.5; - LastSwiftMigration = 1330; + 331585952F352C6B00FACB51 = { + CreatedOnToolsVersion = 26.2; TestTargetID = 97C146ED1CF9000F007C117D; }; - 686BE82C25E58CCF00862533 = { - CreatedOnToolsVersion = 12.4; - LastSwiftMigration = 1330; - ProvisioningStyle = Automatic; + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + LastSwiftMigration = 2620; TestTargetID = 97C146ED1CF9000F007C117D; }; 97C146ED1CF9000F007C117D = { CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; }; }; }; buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; - compatibilityVersion = "Xcode 3.2"; + compatibilityVersion = "Xcode 9.3"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( @@ -321,21 +279,21 @@ projectRoot = ""; targets = ( 97C146ED1CF9000F007C117D /* Runner */, - 686BE82C25E58CCF00862533 /* RunnerUITests */, - 33E20B3126EFCDFC00A4A191 /* RunnerTests */, + 331C8080294A63A400263BE5 /* RunnerTests */, + 331585952F352C6B00FACB51 /* RunnerUITests */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ - 33E20B3026EFCDFC00A4A191 /* Resources */ = { + 331585942F352C6B00FACB51 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; - 686BE82B25E58CCF00862533 /* Resources */ = { + 331C807F294A63A400263BE5 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( @@ -372,28 +330,6 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; }; - 3B2E8279C112D7129C8D23F1 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; 9740EEB61CF901F6004384FC /* Run Script */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; @@ -409,41 +345,23 @@ shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; }; - C6989ECD8FF0836301D734B4 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; - showEnvVarsInLog = 0; - }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ - 33E20B2E26EFCDFC00A4A191 /* Sources */ = { + 331585922F352C6B00FACB51 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - E092A7EE28D10802005C7F67 /* QuickActionsPluginTests.swift in Sources */, - E092A7F128D10890005C7F67 /* MockShortcutItemProvider.swift in Sources */, + 331585A52F352C8600FACB51 /* RunnerUITests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; - 686BE82925E58CCF00862533 /* Sources */ = { + 331C807D294A63A400263BE5 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - E092A7F628D128EB005C7F67 /* RunnerUITests.swift in Sources */, + 331585A82F352CE600FACB51 /* QuickActionsPluginTests.swift in Sources */, + 331585AE2F352D1800FACB51 /* MockShortcutItemProvider.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -451,8 +369,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 978B8F6F1D3862AE00F588F7 /* AppDelegate.m in Sources */, - 97C146F31CF9000F007C117D /* main.m in Sources */, + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -460,15 +377,15 @@ /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ - 33E20B3826EFCDFC00A4A191 /* PBXTargetDependency */ = { + 3315859D2F352C6B00FACB51 /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 97C146ED1CF9000F007C117D /* Runner */; - targetProxy = 33E20B3726EFCDFC00A4A191 /* PBXContainerItemProxy */; + targetProxy = 3315859C2F352C6B00FACB51 /* PBXContainerItemProxy */; }; - 686BE83325E58CCF00862533 /* PBXTargetDependency */ = { + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 97C146ED1CF9000F007C117D /* Runner */; - targetProxy = 686BE83225E58CCF00862533 /* PBXContainerItemProxy */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ @@ -492,108 +409,205 @@ /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ - 33E20B3926EFCDFC00A4A191 /* Debug */ = { + 249021D3217E4FDB00AE95B9 /* Profile */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 9D27FE1F0F21D4D47DDA16DE /* Pods-RunnerTests.debug.xcconfig */; buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; - INFOPLIST_FILE = RunnerTests/Info.plist; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", - "@loader_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.RunnerTests; + PRODUCT_BUNDLE_IDENTIFIER = com.example.quickActionsExample; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 3315859E2F352C6B00FACB51 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 26.2; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.RunnerUITests; PRODUCT_NAME = "$(TARGET_NAME)"; + STRING_CATALOG_GENERATE_SYMBOLS = NO; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = NO; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; SWIFT_VERSION = 5.0; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/Runner"; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = Runner; }; name = Debug; }; - 33E20B3A26EFCDFC00A4A191 /* Release */ = { + 3315859F2F352C6B00FACB51 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 96F949A6B78E2DC62B93C4F8 /* Pods-RunnerTests.release.xcconfig */; buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CLANG_ENABLE_MODULES = YES; - INFOPLIST_FILE = RunnerTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.RunnerTests; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 26.2; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.RunnerUITests; PRODUCT_NAME = "$(TARGET_NAME)"; + STRING_CATALOG_GENERATE_SYMBOLS = NO; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; SWIFT_VERSION = 5.0; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/Runner"; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = Runner; }; name = Release; }; - 686BE83425E58CCF00862533 /* Debug */ = { + 331585A02F352C6B00FACB51 /* Profile */ = { isa = XCBuildConfiguration; buildSettings = { CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; CODE_SIGN_STYLE = Automatic; - GCC_C_LANGUAGE_STANDARD = gnu11; - INFOPLIST_FILE = RunnerUITests/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; - MTL_FAST_MATH = YES; - PRODUCT_BUNDLE_IDENTIFIER = com.google.RunnerUITests; + CURRENT_PROJECT_VERSION = 1; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 26.2; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.RunnerUITests; PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + STRING_CATALOG_GENERATE_SYMBOLS = NO; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; TEST_TARGET_NAME = Runner; }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.quickActionsExample.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; name = Debug; }; - 686BE83525E58CCF00862533 /* Release */ = { + 331C8089294A63A400263BE5 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + BUNDLE_LOADER = "$(TEST_HOST)"; CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; CODE_SIGN_STYLE = Automatic; - GCC_C_LANGUAGE_STANDARD = gnu11; - INFOPLIST_FILE = RunnerUITests/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 13.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MTL_FAST_MATH = YES; - PRODUCT_BUNDLE_IDENTIFIER = com.google.RunnerUITests; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.quickActionsExample.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - TEST_TARGET_NAME = Runner; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; }; name = Release; }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.quickActionsExample.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; 97C147031CF9000F007C117D /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; @@ -623,6 +637,7 @@ DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; @@ -649,7 +664,7 @@ isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; @@ -679,6 +694,7 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; @@ -690,6 +706,9 @@ IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; @@ -700,22 +719,20 @@ baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.quickActionsExample; + PRODUCT_BUNDLE_IDENTIFIER = com.example.quickActionsExample; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; }; name = Debug; }; @@ -724,42 +741,41 @@ baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); - LIBRARY_SEARCH_PATHS = ( - "$(inherited)", - "$(PROJECT_DIR)/Flutter", - ); - PRODUCT_BUNDLE_IDENTIFIER = dev.flutter.plugins.quickActionsExample; + PRODUCT_BUNDLE_IDENTIFIER = com.example.quickActionsExample; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ - 33E20B3B26EFCDFC00A4A191 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + 331585A12F352C6B00FACB51 /* Build configuration list for PBXNativeTarget "RunnerUITests" */ = { isa = XCConfigurationList; buildConfigurations = ( - 33E20B3926EFCDFC00A4A191 /* Debug */, - 33E20B3A26EFCDFC00A4A191 /* Release */, + 3315859E2F352C6B00FACB51 /* Debug */, + 3315859F2F352C6B00FACB51 /* Release */, + 331585A02F352C6B00FACB51 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - 686BE83625E58CCF00862533 /* Build configuration list for PBXNativeTarget "RunnerUITests" */ = { + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { isa = XCConfigurationList; buildConfigurations = ( - 686BE83425E58CCF00862533 /* Debug */, - 686BE83525E58CCF00862533 /* Release */, + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; @@ -769,6 +785,7 @@ buildConfigurations = ( 97C147031CF9000F007C117D /* Debug */, 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; @@ -778,6 +795,7 @@ buildConfigurations = ( 97C147061CF9000F007C117D /* Debug */, 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/packages/quick_actions/quick_actions_ios/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000000..919434a6254f --- /dev/null +++ b/packages/quick_actions/quick_actions_ios/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/packages/quick_actions/quick_actions_ios/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 000000000000..18d981003d68 --- /dev/null +++ b/packages/quick_actions/quick_actions_ios/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/packages/quick_actions/quick_actions_ios/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 000000000000..f9b0d7c5ea15 --- /dev/null +++ b/packages/quick_actions/quick_actions_ios/example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/packages/quick_actions/quick_actions_ios/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index 8fee1e557bc1..e72c61d23f82 100644 --- a/packages/quick_actions/quick_actions_ios/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/packages/quick_actions/quick_actions_ios/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -1,7 +1,7 @@ + version = "1.7"> @@ -44,6 +44,7 @@ buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + customLLDBInitFile = "$(SRCROOT)/Flutter/ephemeral/flutter_lldbinit" shouldUseLaunchSchemeArgsEnv = "YES"> + skipped = "NO" + parallelizable = "YES"> + skipped = "NO" + parallelizable = "YES"> @@ -81,6 +84,7 @@ buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + customLLDBInitFile = "$(SRCROOT)/Flutter/ephemeral/flutter_lldbinit" launchStyle = "0" useCustomWorkingDirectory = "NO" ignoresPersistentStateOnLaunch = "NO" @@ -100,7 +104,7 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/packages/quick_actions/quick_actions_ios/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 000000000000..f9b0d7c5ea15 --- /dev/null +++ b/packages/quick_actions/quick_actions_ios/example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/AppDelegate.h b/packages/quick_actions/quick_actions_ios/example/ios/Runner/AppDelegate.h deleted file mode 100644 index 721cca1e11bb..000000000000 --- a/packages/quick_actions/quick_actions_ios/example/ios/Runner/AppDelegate.h +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import -#import - -@interface AppDelegate : FlutterAppDelegate - -@end diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/AppDelegate.m b/packages/quick_actions/quick_actions_ios/example/ios/Runner/AppDelegate.m deleted file mode 100644 index db08d8255c6b..000000000000 --- a/packages/quick_actions/quick_actions_ios/example/ios/Runner/AppDelegate.m +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "AppDelegate.h" -#include "GeneratedPluginRegistrant.h" - -@implementation AppDelegate - -- (BOOL)application:(UIApplication *)application - didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - [GeneratedPluginRegistrant registerWithRegistry:self]; - // Override point for customization after application launch. - [super application:application didFinishLaunchingWithOptions:launchOptions]; - return NO; -} -@end diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/AppDelegate.swift b/packages/quick_actions/quick_actions_ios/example/ios/Runner/AppDelegate.swift new file mode 100644 index 000000000000..6fa401143d5a --- /dev/null +++ b/packages/quick_actions/quick_actions_ios/example/ios/Runner/AppDelegate.swift @@ -0,0 +1,19 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + super.application(application, didFinishLaunchingWithOptions: launchOptions) + // For UI integration tests. See https://github.com/flutter/plugins/pull/3811. + return false + } +} diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json index d22f10b2ab63..d36b1fab2d9d 100644 --- a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json +++ b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -107,6 +107,12 @@ "idiom" : "ipad", "filename" : "Icon-App-83.5x83.5@2x.png", "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" } ], "info" : { diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 000000000000..dc9ada4725e9 Binary files /dev/null and b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png index 28c6bf03016f..7353c41ecf9c 100644 Binary files a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png and b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png index 2ccbfd967d96..797d452e4589 100644 Binary files a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png and b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png index f091b6b0bca8..6ed2d933e112 100644 Binary files a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png and b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png index 4cde12118dda..4cd7b0099ca8 100644 Binary files a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png and b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png index d0ef06e7edb8..fe730945a01f 100644 Binary files a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png and b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png index dcdc2306c285..321773cd857a 100644 Binary files a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png and b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png index 2ccbfd967d96..797d452e4589 100644 Binary files a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png and b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png index c8f9ed8f5cee..502f463a9bc8 100644 Binary files a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png and b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png index a6d6b8609df0..0ec303439225 100644 Binary files a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png and b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png index a6d6b8609df0..0ec303439225 100644 Binary files a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png and b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png index 75b2d164a5a9..e9f5fea27c70 100644 Binary files a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png and b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png index c4df70d39da7..84ac32ae7d98 100644 Binary files a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png and b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png index 6a84f41e14e2..8953cba09064 100644 Binary files a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png and b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png index d0e1f5853602..0467bf12aa4d 100644 Binary files a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png and b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 000000000000..0bedcf2fd467 --- /dev/null +++ b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 000000000000..9da19eacad3b Binary files /dev/null and b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 000000000000..9da19eacad3b Binary files /dev/null and b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 000000000000..9da19eacad3b Binary files /dev/null and b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Base.lproj/LaunchScreen.storyboard b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Base.lproj/LaunchScreen.storyboard index ebf48f603974..f2e259c7c939 100644 --- a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Base.lproj/LaunchScreen.storyboard +++ b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -1,8 +1,8 @@ - + - + @@ -10,13 +10,20 @@ - - + + - - + + + + + + + + + @@ -24,4 +31,7 @@ + + + diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Info.plist b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Info.plist index f572a5d0dfda..fd3b62987824 100644 --- a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Info.plist +++ b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Info.plist @@ -3,7 +3,9 @@ CFBundleDevelopmentRegion - en + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Quick Actions Example CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier @@ -15,21 +17,17 @@ CFBundlePackageType APPL CFBundleShortVersionString - 1.0 + $(FLUTTER_BUILD_NAME) CFBundleSignature ???? CFBundleVersion - 1 + $(FLUTTER_BUILD_NUMBER) LSRequiresIPhoneOS UILaunchStoryboardName LaunchScreen UIMainStoryboardFile Main - UIRequiredDeviceCapabilities - - arm64 - UISupportedInterfaceOrientations UIInterfaceOrientationPortrait diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/Runner-Bridging-Header.h b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 000000000000..ba04211afd0a --- /dev/null +++ b/packages/quick_actions/quick_actions_ios/example/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1,5 @@ +// Copyright 2013 The Flutter Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import "GeneratedPluginRegistrant.h" diff --git a/packages/quick_actions/quick_actions_ios/example/ios/Runner/main.m b/packages/quick_actions/quick_actions_ios/example/ios/Runner/main.m deleted file mode 100644 index fc7b5903f185..000000000000 --- a/packages/quick_actions/quick_actions_ios/example/ios/Runner/main.m +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2013 The Flutter Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import -#import -#import "AppDelegate.h" - -int main(int argc, char *argv[]) { - @autoreleasepool { - return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); - } -} diff --git a/packages/quick_actions/quick_actions_ios/example/ios/RunnerTests/QuickActionsPluginTests.swift b/packages/quick_actions/quick_actions_ios/example/ios/RunnerTests/QuickActionsPluginTests.swift index 2be89907b435..98766194b3bc 100644 --- a/packages/quick_actions/quick_actions_ios/example/ios/RunnerTests/QuickActionsPluginTests.swift +++ b/packages/quick_actions/quick_actions_ios/example/ios/RunnerTests/QuickActionsPluginTests.swift @@ -3,7 +3,7 @@ // found in the LICENSE file. import Flutter -import XCTest +import Testing @testable import quick_actions_ios @@ -19,9 +19,10 @@ class MockFlutterApi: IOSQuickActionsFlutterApiProtocol { } } -class QuickActionsPluginTests: XCTestCase { +@MainActor +struct QuickActionsPluginTests { - func testHandleMethodCall_setShortcutItems() { + @Test func handleMethodCallSetShortcutItems() { let rawItem = ShortcutItemMessage( type: "SearchTheThing", localizedTitle: "Search the thing", @@ -43,10 +44,10 @@ class QuickActionsPluginTests: XCTestCase { shortcutItemProvider: mockShortcutItemProvider) plugin.setShortcutItems(itemsList: [rawItem]) - XCTAssertEqual(mockShortcutItemProvider.shortcutItems, [item], "Must set shortcut items.") + #expect(mockShortcutItemProvider.shortcutItems == [item]) } - func testHandleMethodCall_clearShortcutItems() { + @Test func handleMethodCallClearShortcutItems() { let item = UIApplicationShortcutItem( type: "SearchTheThing", localizedTitle: "Search the thing", @@ -65,11 +66,11 @@ class QuickActionsPluginTests: XCTestCase { plugin.clearShortcutItems() - XCTAssertEqual(mockShortcutItemProvider.shortcutItems, [], "Must clear shortcut items.") + #expect(mockShortcutItemProvider.shortcutItems == []) } - func testApplicationPerformActionForShortcutItem() { + @Test func applicationPerformActionForShortcutItem() async { let flutterApi: MockFlutterApi = MockFlutterApi() let mockShortcutItemProvider = MockShortcutItemProvider() @@ -84,24 +85,24 @@ class QuickActionsPluginTests: XCTestCase { icon: UIApplicationShortcutIcon(templateImageName: "search_the_thing.png"), userInfo: nil) - let invokeMethodExpectation = expectation(description: "invokeMethod must be called.") - flutterApi.launchActionCallback = { aString in - XCTAssertEqual(aString, item.type) - invokeMethodExpectation.fulfill() - } + await confirmation("invokeMethod must be called") { confirmed in + flutterApi.launchActionCallback = { aString in + #expect(aString == item.type) + confirmed() + } - let actionResult = plugin.application( - UIApplication.shared, - performActionFor: item - ) { success in - // noop - } + let actionResult = plugin.application( + UIApplication.shared, + performActionFor: item + ) { success in + // noop + } - XCTAssert(actionResult, "performActionForShortcutItem must return true.") - waitForExpectations(timeout: 1) + #expect(actionResult, "performActionForShortcutItem must return true.") + } } - func testApplicationDidFinishLaunchingWithOptions_launchWithShortcut() { + @Test func applicationDidFinishLaunchingWithOptionsLaunchWithShortcut() { let flutterApi: MockFlutterApi = MockFlutterApi() let mockShortcutItemProvider = MockShortcutItemProvider() @@ -119,11 +120,11 @@ class QuickActionsPluginTests: XCTestCase { let launchResult = plugin.application( UIApplication.shared, didFinishLaunchingWithOptions: [UIApplication.LaunchOptionsKey.shortcutItem: item]) - XCTAssertFalse( - launchResult, "didFinishLaunchingWithOptions must return false if launched from shortcut.") + #expect( + !launchResult, "didFinishLaunchingWithOptions must return false if launched from shortcut.") } - func testApplicationDidFinishLaunchingWithOptions_launchWithoutShortcut() { + @Test func applicationDidFinishLaunchingWithOptionsLaunchWithoutShortcut() { let flutterApi: MockFlutterApi = MockFlutterApi() let mockShortcutItemProvider = MockShortcutItemProvider() @@ -132,11 +133,11 @@ class QuickActionsPluginTests: XCTestCase { shortcutItemProvider: mockShortcutItemProvider) let launchResult = plugin.application(UIApplication.shared, didFinishLaunchingWithOptions: [:]) - XCTAssert( + #expect( launchResult, "didFinishLaunchingWithOptions must return true if not launched from shortcut.") } - func testApplicationDidBecomeActive_launchWithoutShortcut() { + @Test func applicationDidBecomeActiveLaunchWithoutShortcut() { let flutterApi: MockFlutterApi = MockFlutterApi() let mockShortcutItemProvider = MockShortcutItemProvider() @@ -145,13 +146,13 @@ class QuickActionsPluginTests: XCTestCase { shortcutItemProvider: mockShortcutItemProvider) let launchResult = plugin.application(UIApplication.shared, didFinishLaunchingWithOptions: [:]) - XCTAssert( + #expect( launchResult, "didFinishLaunchingWithOptions must return true if not launched from shortcut.") plugin.applicationDidBecomeActive(UIApplication.shared) } - func testApplicationDidBecomeActive_launchWithShortcut() { + @Test func applicationDidBecomeActiveLaunchWithShortcut() async { let item = UIApplicationShortcutItem( type: "SearchTheThing", localizedTitle: "Search the thing", @@ -166,24 +167,24 @@ class QuickActionsPluginTests: XCTestCase { flutterApi: flutterApi, shortcutItemProvider: mockShortcutItemProvider) - let invokeMethodExpectation = expectation(description: "invokeMethod must be called.") - flutterApi.launchActionCallback = { aString in - XCTAssertEqual(aString, item.type) - invokeMethodExpectation.fulfill() - } + await confirmation("invokeMethod must be called") { confirmed in + flutterApi.launchActionCallback = { aString in + #expect(aString == item.type) + confirmed() + } - let launchResult = plugin.application( - UIApplication.shared, - didFinishLaunchingWithOptions: [UIApplication.LaunchOptionsKey.shortcutItem: item]) + let launchResult = plugin.application( + UIApplication.shared, + didFinishLaunchingWithOptions: [UIApplication.LaunchOptionsKey.shortcutItem: item]) - XCTAssertFalse( - launchResult, "didFinishLaunchingWithOptions must return false if launched from shortcut.") + #expect( + !launchResult, "didFinishLaunchingWithOptions must return false if launched from shortcut.") - plugin.applicationDidBecomeActive(UIApplication.shared) - waitForExpectations(timeout: 1) + plugin.applicationDidBecomeActive(UIApplication.shared) + } } - func testApplicationDidBecomeActive_launchWithShortcut_becomeActiveTwice() { + @Test func applicationDidBecomeActiveLaunchWithShortcutBecomeActiveTwice() async { let item = UIApplicationShortcutItem( type: "SearchTheThing", localizedTitle: "Search the thing", @@ -198,25 +199,28 @@ class QuickActionsPluginTests: XCTestCase { flutterApi: flutterApi, shortcutItemProvider: mockShortcutItemProvider) - let invokeMethodExpectation = expectation(description: "invokeMethod must be called.") + await confirmation("shortcut should be handled when application becomes active") { confirmed in + flutterApi.launchActionCallback = { aString in + #expect(aString == item.type) + confirmed() + } - var invokeMethodCount = 0 - flutterApi.launchActionCallback = { aString in - XCTAssertEqual(aString, item.type) - invokeMethodCount += 1 - invokeMethodExpectation.fulfill() - } + let launchResult = plugin.application( + UIApplication.shared, + didFinishLaunchingWithOptions: [UIApplication.LaunchOptionsKey.shortcutItem: item]) - let launchResult = plugin.application( - UIApplication.shared, - didFinishLaunchingWithOptions: [UIApplication.LaunchOptionsKey.shortcutItem: item]) + #expect( + !launchResult, "didFinishLaunchingWithOptions must return false if launched from shortcut.") - XCTAssertFalse( - launchResult, "didFinishLaunchingWithOptions must return false if launched from shortcut.") - - plugin.applicationDidBecomeActive(UIApplication.shared) - waitForExpectations(timeout: 1) + plugin.applicationDidBecomeActive(UIApplication.shared) + } + await confirmation("shortcut should only be handled once per launch", expectedCount: 0) { + confirmed in + flutterApi.launchActionCallback = { _ in + confirmed() + } - XCTAssertEqual(invokeMethodCount, 1, "shortcut should only be handled once per launch.") + plugin.applicationDidBecomeActive(UIApplication.shared) + } } } diff --git a/packages/quick_actions/quick_actions_ios/example/lib/main.dart b/packages/quick_actions/quick_actions_ios/example/lib/main.dart index 9f323bcf6fc9..768638538ced 100644 --- a/packages/quick_actions/quick_actions_ios/example/lib/main.dart +++ b/packages/quick_actions/quick_actions_ios/example/lib/main.dart @@ -38,7 +38,7 @@ class _MyHomePageState extends State { void initState() { super.initState(); - final QuickActionsIos quickActions = QuickActionsIos(); + final quickActions = QuickActionsIos(); quickActions.initialize((String shortcutType) { setState(() { shortcut = shortcutType; diff --git a/packages/quick_actions/quick_actions_ios/lib/quick_actions_ios.dart b/packages/quick_actions/quick_actions_ios/lib/quick_actions_ios.dart index 85db5fe7757d..4c057f6553ec 100644 --- a/packages/quick_actions/quick_actions_ios/lib/quick_actions_ios.dart +++ b/packages/quick_actions/quick_actions_ios/lib/quick_actions_ios.dart @@ -26,8 +26,7 @@ class QuickActionsIos extends QuickActionsPlatform { @override Future initialize(QuickActionHandler handler) async { - final _QuickActionHandlerApi quickActionsHandlerApi = - _QuickActionHandlerApi(); + final quickActionsHandlerApi = _QuickActionHandlerApi(); IOSQuickActionsFlutterApi.setUp(quickActionsHandlerApi); _handler = handler; } diff --git a/packages/quick_actions/quick_actions_ios/test/quick_actions_ios_test.dart b/packages/quick_actions/quick_actions_ios/test/quick_actions_ios_test.dart index e8870782149d..ab2240576fa7 100644 --- a/packages/quick_actions/quick_actions_ios/test/quick_actions_ios_test.dart +++ b/packages/quick_actions/quick_actions_ios/test/quick_actions_ios_test.dart @@ -11,8 +11,8 @@ import 'package:quick_actions_platform_interface/quick_actions_platform_interfac void main() { TestWidgetsFlutterBinding.ensureInitialized(); - final _FakeQuickActionsApi api = _FakeQuickActionsApi(); - final QuickActionsIos quickActions = QuickActionsIos(api: api); + final api = _FakeQuickActionsApi(); + final quickActions = QuickActionsIos(api: api); test('registerWith() registers correct instance', () { QuickActionsIos.registerWith(); @@ -27,7 +27,7 @@ void main() { test('setShortcutItems', () async { await quickActions.initialize((String type) {}); - const ShortcutItem item = ShortcutItem( + const item = ShortcutItem( type: 'test', localizedTitle: 'title', localizedSubtitle: 'subtitle', @@ -43,7 +43,7 @@ void main() { test('clearShortCutItems', () { quickActions.initialize((String type) {}); - const ShortcutItem item = ShortcutItem( + const item = ShortcutItem( type: 'test', localizedTitle: 'title', localizedSubtitle: 'subtitle', @@ -56,12 +56,12 @@ void main() { }); test('Shortcut item can be constructed', () { - const String type = 'type'; - const String localizedTitle = 'title'; - const String localizedSubtitle = 'subtitle'; - const String icon = 'foo'; + const type = 'type'; + const localizedTitle = 'title'; + const localizedSubtitle = 'subtitle'; + const icon = 'foo'; - const ShortcutItem item = ShortcutItem( + const item = ShortcutItem( type: type, localizedTitle: localizedTitle, localizedSubtitle: localizedSubtitle, @@ -88,7 +88,7 @@ class _FakeQuickActionsApi implements IOSQuickActionsApi { @override Future setShortcutItems(List itemsList) async { await clearShortcutItems(); - for (final ShortcutItemMessage? element in itemsList) { + for (final element in itemsList) { items.add(shortcutItemMessageToShortcutItem(element!)); } } diff --git a/packages/quick_actions/quick_actions_platform_interface/CHANGELOG.md b/packages/quick_actions/quick_actions_platform_interface/CHANGELOG.md index c3f5df9627b3..92b36fc07180 100644 --- a/packages/quick_actions/quick_actions_platform_interface/CHANGELOG.md +++ b/packages/quick_actions/quick_actions_platform_interface/CHANGELOG.md @@ -1,6 +1,6 @@ ## NEXT -* Updates minimum supported SDK version to Flutter 3.32/Dart 3.8. +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. ## 1.1.0 diff --git a/packages/quick_actions/quick_actions_platform_interface/pubspec.yaml b/packages/quick_actions/quick_actions_platform_interface/pubspec.yaml index cafba50c7bf1..962370d72be3 100644 --- a/packages/quick_actions/quick_actions_platform_interface/pubspec.yaml +++ b/packages/quick_actions/quick_actions_platform_interface/pubspec.yaml @@ -7,8 +7,8 @@ issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+ version: 1.1.0 environment: - sdk: ^3.8.0 - flutter: ">=3.32.0" + sdk: ^3.9.0 + flutter: ">=3.35.0" dependencies: flutter: diff --git a/packages/quick_actions/quick_actions_platform_interface/test/method_channel_quick_actions_test.dart b/packages/quick_actions/quick_actions_platform_interface/test/method_channel_quick_actions_test.dart index 384627a55664..d9f5b7cfe148 100644 --- a/packages/quick_actions/quick_actions_platform_interface/test/method_channel_quick_actions_test.dart +++ b/packages/quick_actions/quick_actions_platform_interface/test/method_channel_quick_actions_test.dart @@ -13,9 +13,9 @@ void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('$MethodChannelQuickActions', () { - final MethodChannelQuickActions quickActions = MethodChannelQuickActions(); + final quickActions = MethodChannelQuickActions(); - final List log = []; + final log = []; setUp(() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger @@ -39,7 +39,7 @@ void main() { }); test('initialize', () async { - final Completer quickActionsHandler = Completer(); + final quickActionsHandler = Completer(); await quickActions.initialize( (_) => quickActionsHandler.complete(true), ); @@ -109,10 +109,10 @@ void main() { ); test('setShortcutItems with demo data', () async { - const String type = 'type'; - const String localizedTitle = 'localizedTitle'; - const String localizedSubtitle = 'localizedSubtitle'; - const String icon = 'icon'; + const type = 'type'; + const localizedTitle = 'localizedTitle'; + const localizedSubtitle = 'localizedSubtitle'; + const icon = 'icon'; await quickActions.setShortcutItems(const [ ShortcutItem( type: type, @@ -161,12 +161,12 @@ void main() { group('$ShortcutItem', () { test('Shortcut item can be constructed', () { - const String type = 'type'; - const String localizedTitle = 'title'; - const String localizedSubtitle = 'subtitle'; - const String icon = 'foo'; + const type = 'type'; + const localizedTitle = 'title'; + const localizedSubtitle = 'subtitle'; + const icon = 'foo'; - const ShortcutItem item = ShortcutItem( + const item = ShortcutItem( type: type, localizedTitle: localizedTitle, localizedSubtitle: localizedSubtitle, diff --git a/packages/quick_actions/quick_actions_platform_interface/test/quick_actions_platform_interface_test.dart b/packages/quick_actions/quick_actions_platform_interface/test/quick_actions_platform_interface_test.dart index 69e0cd8d5932..7614088b9cfe 100644 --- a/packages/quick_actions/quick_actions_platform_interface/test/quick_actions_platform_interface_test.dart +++ b/packages/quick_actions/quick_actions_platform_interface/test/quick_actions_platform_interface_test.dart @@ -39,8 +39,7 @@ void main() { 'Default implementation of initialize() should throw unimplemented error', () { // Arrange - final ExtendsQuickActionsPlatform quickActionsPlatform = - ExtendsQuickActionsPlatform(); + final quickActionsPlatform = ExtendsQuickActionsPlatform(); // Act & Assert expect( @@ -54,8 +53,7 @@ void main() { 'Default implementation of setShortcutItems() should throw unimplemented error', () { // Arrange - final ExtendsQuickActionsPlatform quickActionsPlatform = - ExtendsQuickActionsPlatform(); + final quickActionsPlatform = ExtendsQuickActionsPlatform(); // Act & Assert expect( @@ -69,8 +67,7 @@ void main() { 'Default implementation of clearShortcutItems() should throw unimplemented error', () { // Arrange - final ExtendsQuickActionsPlatform quickActionsPlatform = - ExtendsQuickActionsPlatform(); + final quickActionsPlatform = ExtendsQuickActionsPlatform(); // Act & Assert expect( diff --git a/packages/rfw/CHANGELOG.md b/packages/rfw/CHANGELOG.md index ba7879f14f7f..2aa690d15f0e 100644 --- a/packages/rfw/CHANGELOG.md +++ b/packages/rfw/CHANGELOG.md @@ -1,3 +1,20 @@ +## 1.1.3 + +* Fixes dartdoc comments that accidentally used HTML. + +## 1.1.2 + +* Removes outdated call for feedback from the README. + +## 1.1.1 + +* Removes obsolete scripting language integration section in README.md. + +## 1.1.0 + +* Adds support for the `Flexible` core widget. +* Updates minimum supported SDK version to Flutter 3.35/Dart 3.9. + ## 1.0.32 * Updates broken links in README.md. diff --git a/packages/rfw/README.md b/packages/rfw/README.md index 730a7cd211e6..7835248653ae 100644 --- a/packages/rfw/README.md +++ b/packages/rfw/README.md @@ -23,13 +23,6 @@ experiencing them in production. Please [file issues](https://github.com/flutter/flutter/issues/new?labels=p:%20rfw,package,P2) if you run into them. -## Feedback - -We would love to hear your experiences using this package, whether -positive or negative. In particular, stories of uses of this package -in production would be very interesting. Please add comments to [issue -90218](https://github.com/flutter/flutter/issues/90218). - ## Limitations Once you realize that you can ship UI (and maybe logic, e.g. using @@ -491,8 +484,8 @@ not identify a list): 'Foo': (BuildContext context, DataSource source) { final int length = source.length(['text']); if (length > 0) { - final StringBuffer text = StringBuffer(); - for (int index = 0; index < length; index += 1) { + final text = StringBuffer(); + for (var index = 0; index < length; index += 1) { text.write(source.v(['text', index])); } return Text(text.toString(), textDirection: TextDirection.ltr); @@ -936,36 +929,6 @@ This example also shows how an application can implement custom local code for events; in this case, incrementing a counter (both of the "remote" widgets are just different ways of implementing a counter). -### Integrating with scripting language runtimes - -The example in `example/wasm` shows how a program could fetch logic in -addition to UI, in this case using Wasm compiled from C (and let us -briefly appreciate the absurdity of using C as a scripting language -for an application written in Dart). - -In this example, as written, the Dart client could support any -application whose data model consisted of a single integer and whose -logic could be expressed in C without external dependencies. - -This example could be extended to have the C program export data in -the Remote Flutter Widgets binary data blob format which could be -parsed using `decodeDataBlob` and passed to `DynamicContent.update` -(thus allowing any structured data supported by RFW), and similarly -arguments could be passed to the Wasm code using the same format -(encoding using `encodeDataBlob`) to allow arbitrary structured data -to be communicated from the interface to the Wasm logic. In addition, -the Wasm logic could be provided with WASI interface bindings or with -custom bindings that expose platform capabilities (e.g. from Flutter -plugins), greatly extending the scope of what could be implemented in -the Wasm logic. - -As of the time of writing, `package:wasm` does not support Android, -iOS, or web, so this demo is limited to desktop environments. The -underlying Wasmer runtime supports Android and iOS already, and -obviously Wasm in general is supported by web browsers, so it is -expected that these limitations are only temporary (modulo policy -concerns on iOS, anyway). - ## Contributing See [CONTRIBUTING.md](https://github.com/flutter/packages/blob/main/packages/rfw/CONTRIBUTING.md) diff --git a/packages/rfw/example/hello/.metadata b/packages/rfw/example/hello/.metadata index 45c494ed6736..9fb00192b70a 100644 --- a/packages/rfw/example/hello/.metadata +++ b/packages/rfw/example/hello/.metadata @@ -4,7 +4,27 @@ # This file should be version controlled and should not be manually edited. version: - revision: a1cd3f45e02c2429e14630d6cc6de120c3d24bd0 - channel: master + revision: "582a0e7c5581dc0ca5f7bfd8662bb8db6f59d536" + channel: "stable" project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 582a0e7c5581dc0ca5f7bfd8662bb8db6f59d536 + base_revision: 582a0e7c5581dc0ca5f7bfd8662bb8db6f59d536 + - platform: android + create_revision: 582a0e7c5581dc0ca5f7bfd8662bb8db6f59d536 + base_revision: 582a0e7c5581dc0ca5f7bfd8662bb8db6f59d536 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/packages/rfw/example/hello/android/.gitignore b/packages/rfw/example/hello/android/.gitignore index 55afd919c659..be3943c96d8e 100644 --- a/packages/rfw/example/hello/android/.gitignore +++ b/packages/rfw/example/hello/android/.gitignore @@ -5,6 +5,7 @@ gradle-wrapper.jar /gradlew.bat /local.properties GeneratedPluginRegistrant.java +.cxx/ # Remember to never publicly share your keystore. # See https://flutter.dev/to/reference-keystore diff --git a/packages/rfw/example/hello/android/app/build.gradle b/packages/rfw/example/hello/android/app/build.gradle deleted file mode 100644 index a59d6c8b6be7..000000000000 --- a/packages/rfw/example/hello/android/app/build.gradle +++ /dev/null @@ -1,62 +0,0 @@ -plugins { - id "com.android.application" - id "org.jetbrains.kotlin.android" - id "dev.flutter.flutter-gradle-plugin" -} - -def localProperties = new Properties() -def localPropertiesFile = rootProject.file('local.properties') -if (localPropertiesFile.exists()) { - localPropertiesFile.withReader('UTF-8') { reader -> - localProperties.load(reader) - } -} - -def flutterVersionCode = localProperties.getProperty('flutter.versionCode') -if (flutterVersionCode == null) { - flutterVersionCode = '1' -} - -def flutterVersionName = localProperties.getProperty('flutter.versionName') -if (flutterVersionName == null) { - flutterVersionName = '1.0' -} - -android { - namespace = "dev.flutter.rfw.examples.hello" - compileSdk = flutter.compileSdkVersion - - compileOptions { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 - } - - kotlinOptions { - jvmTarget = JavaVersion.VERSION_17.toString() - } - - sourceSets { - main.java.srcDirs += 'src/main/kotlin' - } - - defaultConfig { - // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). - applicationId "dev.flutter.rfw.examples.hello" - minSdkVersion flutter.minSdkVersion - targetSdkVersion flutter.targetSdkVersion - versionCode flutterVersionCode.toInteger() - versionName flutterVersionName - } - - buildTypes { - release { - // TODO: Add your own signing config for the release build. - // Signing with the debug keys for now, so `flutter run --release` works. - signingConfig = signingConfigs.debug - } - } -} - -flutter { - source = '../..' -} diff --git a/packages/rfw/example/hello/android/app/build.gradle.kts b/packages/rfw/example/hello/android/app/build.gradle.kts new file mode 100644 index 000000000000..3bafcc3ce443 --- /dev/null +++ b/packages/rfw/example/hello/android/app/build.gradle.kts @@ -0,0 +1,39 @@ +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "dev.flutter.rfw.examples.hello" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_17.toString() + } + + defaultConfig { + applicationId = "dev.flutter.rfw.examples.hello" + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + signingConfig = signingConfigs.getByName("debug") + } + } +} + +flutter { + source = "../.." +} diff --git a/packages/rfw/example/hello/android/app/src/debug/AndroidManifest.xml b/packages/rfw/example/hello/android/app/src/debug/AndroidManifest.xml index 91a24f1d20cf..399f6981d5d3 100644 --- a/packages/rfw/example/hello/android/app/src/debug/AndroidManifest.xml +++ b/packages/rfw/example/hello/android/app/src/debug/AndroidManifest.xml @@ -1,6 +1,6 @@ - - diff --git a/packages/rfw/example/hello/android/app/src/main/AndroidManifest.xml b/packages/rfw/example/hello/android/app/src/main/AndroidManifest.xml index abb77e597531..390cdb0cd113 100644 --- a/packages/rfw/example/hello/android/app/src/main/AndroidManifest.xml +++ b/packages/rfw/example/hello/android/app/src/main/AndroidManifest.xml @@ -1,15 +1,16 @@ - - + + + + + + + diff --git a/packages/rfw/example/hello/android/app/src/main/kotlin/dev/flutter/rfw/examples/hello/MainActivity.kt b/packages/rfw/example/hello/android/app/src/main/kotlin/dev/flutter/rfw/examples/hello/MainActivity.kt index 231346118d4d..d9e34f2515dd 100644 --- a/packages/rfw/example/hello/android/app/src/main/kotlin/dev/flutter/rfw/examples/hello/MainActivity.kt +++ b/packages/rfw/example/hello/android/app/src/main/kotlin/dev/flutter/rfw/examples/hello/MainActivity.kt @@ -1,8 +1,9 @@ // Copyright 2013 The Flutter Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. + package dev.flutter.rfw.examples.hello import io.flutter.embedding.android.FlutterActivity -class MainActivity : FlutterActivity() {} +class MainActivity : FlutterActivity() diff --git a/packages/rfw/example/hello/android/app/src/main/res/values-night/styles.xml b/packages/rfw/example/hello/android/app/src/main/res/values-night/styles.xml index 449a9f930826..06952be745f9 100644 --- a/packages/rfw/example/hello/android/app/src/main/res/values-night/styles.xml +++ b/packages/rfw/example/hello/android/app/src/main/res/values-night/styles.xml @@ -3,14 +3,14 @@